Class: SplttyCLI::Commands::GroupsAdd

Inherits:
Dry::CLI::Command
  • Object
show all
Defined in:
lib/spltty_cli/commands/groups_add.rb

Overview

spltty groups add — define or update a split group. For a ledger the group is written into that ledger's notes header (the source of truth) and then reconciled into config via NotesSync. With --global it is written straight into the config's global groups (globals never live in a header).

Instance Method Summary collapse

Instance Method Details

#call(name:, **opts) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/spltty_cli/commands/groups_add.rb', line 27

def call(name:, **opts)
  config = SplttyCLI.load_config(opts)
  hash = SplttyCLI::Groups.parse_split(opts[:split])
  SplttyCLI::Groups.validate(name, hash)

  if opts[:global]
    config.groups[name] = hash
    config.save
    puts "Added global group #{name.inspect}: #{SplttyCLI::Groups.format(hash)}"
    return
  end

  raise Config::Error, "specify --ledger NAME or --global" if blank?(opts[:ledger])

  Discovery.sync(config)
  key = config.ledger_key(opts[:ledger]) or
    raise Config::Error, "unknown ledger #{opts[:ledger].inspect}"
  entry = config.ledgers[key]
  path = Notes.path_for(config.accounts_dir, key, entry)
  raise Config::Error, "no notes file for #{key} at #{path}" unless File.exist?(path)

  parsed = Notes.parse(path)
  fm = parsed[:frontmatter]
  spltty = (fm["spltty"] ||= {})
  groups = (spltty["groups"] ||= {})
  groups[name] = hash
  Notes.write(path, fm, parsed[:body])

  NotesSync.run(config)
  config.save
  puts "Added group #{name.inspect} to #{key}: #{SplttyCLI::Groups.format(hash)}"
rescue ArgumentError => e
  warn "spltty groups add: #{e.message}"
  exit 1
rescue Config::Error => e
  warn "spltty groups add: #{e.message}"
  exit 1
end