Class: Workroom::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/workroom/config.rb

Constant Summary collapse

CONFIG_DIR =
File.expand_path('~/.config/workroom')
DEFAULT_WORKROOMS_DIR =
'~/workrooms'

Instance Method Summary collapse

Instance Method Details

#add_workroom(parent_path, name, workroom_path, vcs) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/workroom/config.rb', line 26

def add_workroom(parent_path, name, workroom_path, vcs)
  update do |data|
    data[parent_path] ||= { 'vcs' => vcs.to_s, 'workrooms' => {} }
    data[parent_path]['vcs'] = vcs.to_s
    data[parent_path]['workrooms'][name] = { 'path' => workroom_path }
  end
end

#config_pathObject



10
11
12
# File 'lib/workroom/config.rb', line 10

def config_path
  @config_path ||= File.join(CONFIG_DIR, 'config.json')
end

#find_current_projectObject

Find the project for the current directory. If pwd is a project in the config, return it directly. Otherwise, check if pwd is a workroom path under any project.



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/workroom/config.rb', line 45

def find_current_project
  data = read
  pwd = Pathname.pwd.to_s
  return [pwd, data[pwd]] if data.key?(pwd)

  data.each do |project_path, project|
    workrooms = project['workrooms'] || {}
    return [project_path, project] if workrooms.any? { |_, info| info['path'] == pwd }
  end

  [pwd, nil]
end

#projects_with_workroomsObject



58
59
60
# File 'lib/workroom/config.rb', line 58

def projects_with_workrooms
  @projects_with_workrooms ||= read.select { |_, p| p['workrooms']&.any? }
end

#readObject



14
15
16
17
18
# File 'lib/workroom/config.rb', line 14

def read
  return {} if !File.exist?(config_path)

  JSON.parse(File.read(config_path))
end

#remove_workroom(parent_path, name) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/workroom/config.rb', line 34

def remove_workroom(parent_path, name)
  update do |data|
    return if !data[parent_path]

    data[parent_path]['workrooms'].delete(name)
    data.delete(parent_path) if data[parent_path]['workrooms'].empty?
  end
end

#workrooms_dirObject



62
63
64
# File 'lib/workroom/config.rb', line 62

def workrooms_dir
  Pathname.new(File.expand_path(read['workrooms_dir'] || DEFAULT_WORKROOMS_DIR))
end

#workrooms_dir=(path) ⇒ Object



66
67
68
# File 'lib/workroom/config.rb', line 66

def workrooms_dir=(path)
  update { |data| data['workrooms_dir'] = path }
end

#write(data) ⇒ Object



20
21
22
23
24
# File 'lib/workroom/config.rb', line 20

def write(data)
  dir = File.dirname(config_path)
  FileUtils.mkdir_p(dir)
  File.write(config_path, JSON.pretty_generate(data))
end