Class: Hiiro::Projects

Inherits:
Object
  • Object
show all
Defined in:
lib/hiiro/projects.rb

Constant Summary collapse

CONFIG_FILE =
File.join(Dir.home, '.config', 'hiiro', 'projects.yml')

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fs: Hiiro::Effects::Filesystem.new) ⇒ Projects

Returns a new instance of Projects.



25
26
27
# File 'lib/hiiro/projects.rb', line 25

def initialize(fs: Hiiro::Effects::Filesystem.new)
  @fs = fs
end

Class Method Details

.add_resolvers(hiiro) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/hiiro/projects.rb', line 7

def self.add_resolvers(hiiro)
  pm = new
  hiiro.add_resolver(:project,
    -> {
      all = pm.all
      return nil if all.empty?
      conf = pm.from_config
      lines = all.each_with_object({}) do |(name, path), h|
        source = conf.key?(name) ? '[config]' : '[dir]'
        h[format("%-15s %-8s %s", name, source, path)] = path
      end
      hiiro.fuzzyfind_from_map(lines)
    }
  ) do |name|
    pm.find(name)
  end
end

Instance Method Details

#allObject



63
64
65
# File 'lib/hiiro/projects.rb', line 63

def all
  dirs.merge(from_config)
end

#dirsObject



29
30
31
32
33
# File 'lib/hiiro/projects.rb', line 29

def dirs
  Dir.glob(File.join(Dir.home, 'proj', '*/')).map { |path|
    [File.basename(path), path]
  }.to_h
end

#find(name) ⇒ Object

Find a project path by name (regex match, exact-match tiebreak). Returns the path string, or nil if 0 or >1 matches.



69
70
71
72
73
74
75
# File 'lib/hiiro/projects.rb', line 69

def find(name)
  re = /#{name}/i
  conf = from_config
  matches = dirs.select { |k, _| k.match?(re) }.merge(conf.select { |k, _| k.match?(re) })
  matches = matches.select { |k, _| k == name } if matches.count > 1
  matches.count == 1 ? matches.values.first : nil
end

#from_configObject



35
36
37
38
39
40
41
# File 'lib/hiiro/projects.rb', line 35

def from_config
  Project.all_as_hash
rescue => e
  warn "Projects DB load failed: #{e}"
  return {} unless File.exist?(CONFIG_FILE)
  YAML.safe_load_file(CONFIG_FILE) || {}
end

#from_config?(name) ⇒ Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/hiiro/projects.rb', line 59

def from_config?(name)
  from_config.key?(name)
end

#save_project(name, path) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/hiiro/projects.rb', line 43

def save_project(name, path)
  existing = Project.find_by_name(name)
  if existing
    existing.update(path: path.to_s)
  else
    Project.create(name: name.to_s, path: path.to_s)
  end
  # Dual-write: rewrite YAML backup
  if Hiiro::DB.dual_write?
    all_projects = Project.all_as_hash
    @fs.write(CONFIG_FILE, YAML.dump(all_projects, stringify_names: true))
  end
rescue => e
  warn "Projects DB save failed: #{e}"
end