Module: Chatwerk::Helpers

Defined in:
lib/chatwerk/helpers.rb

Class Method Summary collapse

Class Method Details

.all_packages(path_pattern = '') ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/chatwerk/helpers.rb', line 37

def all_packages(path_pattern = '')
  path_pattern = normalize_package_path(path_pattern)
  if path_pattern.empty?
    QueryPackwerk::Packages.all.to_a
  else
    QueryPackwerk::Packages.where(name: Regexp.new(Regexp.escape(path_pattern))).to_a
  end
end

.chdirObject



3
4
5
# File 'lib/chatwerk/helpers.rb', line 3

def chdir(&)
  Dir.chdir(env_pwd, &)
end

.env_pwdObject



8
9
10
11
12
# File 'lib/chatwerk/helpers.rb', line 8

def env_pwd
  path = ENV.fetch('PWD', pwd)
  # Use realpath if the path exists, otherwise fall back to expand_path
  File.directory?(path) ? File.realpath(path) : File.expand_path(path)
end

.find_package(path_pattern) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/chatwerk/helpers.rb', line 47

def find_package(path_pattern)
  packages = all_packages(path_pattern)

  if packages.empty?
    raise "Unable to find a package for #{path_pattern.inspect}."
  elsif packages.size == 1
    packages.first
  else
    # Return an exact match even if it's a subset of another match
    # e.g. packs/payments and packs/payments_api
    exact_match = packages.find { |package| package.name == path_pattern }
    return exact_match if exact_match

    raise Chatwerk::Error, <<~ERROR
      Found multiple packages for #{path_pattern.inspect}:

      #{packages.map(&:name).join("\n")}

      Please use full path to specify the correct package.
    ERROR
  end
end

.normalize_constant_name(constant_name) ⇒ Object



29
30
31
32
33
34
# File 'lib/chatwerk/helpers.rb', line 29

def normalize_constant_name(constant_name)
  constant_name = constant_name.to_s.strip
  return '' if constant_name.empty?

  constant_name.sub(/^(::)?/, '::')
end

.normalize_package_path(package_path) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/chatwerk/helpers.rb', line 20

def normalize_package_path(package_path)
  package_path = package_path.to_s.strip
  package_path = package_path.delete_prefix('/')
  package_path = package_path.delete_suffix('/package.yml')
  package_path = package_path.delete_suffix('/package_todo.yml')
  package_path.delete_suffix('/')
end

.pwdObject



15
16
17
# File 'lib/chatwerk/helpers.rb', line 15

def pwd
  File.realpath(Dir.pwd)
end