Module: SplttyCLI::Notes

Defined in:
lib/spltty_cli/notes.rb

Overview

Read / write the YAML frontmatter header of a *.notes.md file, and resolve a ledger's notes-file path. The header (delimited by leading --- fences) carries ledger config under a spltty: sub-map; NotesSync owns that map. Any other frontmatter keys are preserved untouched on round-trip.

Constant Summary collapse

FENCE =
"---"

Class Method Summary collapse

Class Method Details

.parse(path) ⇒ Object

Parse a notes file into its frontmatter + body. { frontmatter: Hash, body: String, mtime: Time } frontmatter is {} when the file has no leading --- block (or the file is absent). body is the content after the closing fence (or the whole file when there is no frontmatter).



20
21
22
23
24
25
26
27
# File 'lib/spltty_cli/notes.rb', line 20

def parse(path)
  return { frontmatter: {}, body: "", mtime: nil } unless File.exist?(path)

  raw = File.read(path)
  mtime = File.mtime(path)
  fm, body = split(raw)
  { frontmatter: fm, body: body, mtime: mtime }
end

.path_for(accounts_dir, name, entry) ⇒ Object

Absolute path of a ledger's notes file, given its config entry.



58
59
60
61
62
63
64
65
# File 'lib/spltty_cli/notes.rb', line 58

def path_for(accounts_dir, name, entry)
  if entry && entry["type"] == "monthly"
    dir = entry["dir"] || name
    File.join(accounts_dir, dir, entry["notes"] || "notes.md")
  else
    File.join(accounts_dir, entry&.fetch("notes", nil) || "#{name}.notes.md")
  end
end

.split(raw) ⇒ Object

Split raw file content into [frontmatter Hash, body String].



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/spltty_cli/notes.rb', line 30

def split(raw)
  lines = raw.lines
  return [{}, raw] unless lines.first&.chomp == FENCE

  close = lines[1..].index { |l| l.chomp == FENCE }
  return [{}, raw] if close.nil?

  yaml = lines[1..close].join
  body = lines[(close + 2)..]&.join || ""
  parsed = YAML.safe_load(yaml) || {}
  parsed = {} unless parsed.is_a?(Hash)
  [parsed, body]
end

.write(path, frontmatter, body) ⇒ Object

Write frontmatter + body back to path. When frontmatter is empty the file is written as body only (no fences).



46
47
48
49
50
51
52
53
54
55
# File 'lib/spltty_cli/notes.rb', line 46

def write(path, frontmatter, body)
  content =
    if frontmatter.nil? || frontmatter.empty?
      body
    else
      # YAML.dump emits a leading "---\n"; append the closing fence.
      "#{YAML.dump(frontmatter)}#{FENCE}\n#{body}"
    end
  File.write(path, content)
end