Class: SplttyCLI::Commands::GroupsRm

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

Overview

spltty groups rm — remove a split group from a ledger header (source of truth, then reconciled via NotesSync) or from the global groups (--global).

Instance Method Summary collapse

Instance Method Details

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



17
18
19
20
21
22
23
24
25
26
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_rm.rb', line 17

def call(name:, **opts)
  config = SplttyCLI.load_config(opts)

  if opts[:global]
    removed = config.groups.delete(name)
    config.save
    puts removed ? "Removed global group #{name.inspect}" : "No global group #{name.inspect}"
    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)
  groups = parsed[:frontmatter].dig("spltty", "groups")
  unless groups.is_a?(Hash) && groups.key?(name)
    puts "No group #{name.inspect} in #{key}"
    return
  end

  groups.delete(name)
  if groups.empty?
    parsed[:frontmatter]["spltty"].delete("groups")
    parsed[:frontmatter].delete("spltty") if parsed[:frontmatter]["spltty"].empty?
  end
  Notes.write(path, parsed[:frontmatter], parsed[:body])

  # Apply the deletion to config directly: when the header's last group is
  # removed the "groups" key vanishes, and NotesSync's absent-key guard
  # would otherwise leave the stale copy in config.
  if entry["groups"].is_a?(Hash)
    entry["groups"].delete(name)
    entry.delete("groups") if entry["groups"].empty?
  end

  NotesSync.run(config)
  config.save
  puts "Removed group #{name.inspect} from #{key}"
rescue Config::Error => e
  warn "spltty groups rm: #{e.message}"
  exit 1
end