Module: EasyAI::Base::TomlSections

Defined in:
lib/easyai/base/toml_sections.rb

Overview

极简 TOML "段" 处理工具:只按 table 头切块,不解析具体值。

适用范围:codex ~/.codex/config.toml 这类结构简单的文件 (顶层 key/value + 若干 [table] / [a.b] 段,无多行数组 / 复杂内联表)。

提供能力:

  • split_sections 把文本切成有序的段(每段含 header + 原始行)
  • reject_projects 过滤掉所有 [projects.*] 段,返回新文本
  • merge 段级合并:override 覆盖 base 同名段,base 独有段保留

Defined Under Namespace

Classes: Section

Constant Summary collapse

PROJECT_HEADER_PREFIX =
'[projects.'

Class Method Summary collapse

Class Method Details

.header_key(line) ⇒ Object

归一化 header(整行去空白),用于同名段比对



27
28
29
# File 'lib/easyai/base/toml_sections.rb', line 27

def header_key(line)
  line.strip
end

.header_line?(line) ⇒ Boolean

判断一行是否是 table 头:去掉前导空白后以 '[' 开头(含 '[[' 数组表)

Returns:

  • (Boolean)


22
23
24
# File 'lib/easyai/base/toml_sections.rb', line 22

def header_line?(line)
  line.lstrip.start_with?('[')
end

.merge(base_text, override_text) ⇒ Object

段级合并,override 优先:

  • override 出现的 header 覆盖 base 同名段
  • base 独有 header(含 [projects.*])保留,追加在 override 具名段之后
  • 前导段(header=nil):override 非空用 override,否则用 base


63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/easyai/base/toml_sections.rb', line 63

def merge(base_text, override_text)
  base = split_sections(base_text)
  override = split_sections(override_text)
  override_keys = override.map(&:header).compact

  result = []

  over_pre = override.find { |s| s.header.nil? }
  base_pre = base.find { |s| s.header.nil? }
  preamble = over_pre && !over_pre.body.strip.empty? ? over_pre : base_pre
  result << preamble if preamble

  override.each { |s| result << s unless s.header.nil? }
  base.each do |s|
    next if s.header.nil?
    next if override_keys.include?(s.header)

    result << s
  end

  render(result)
end

.project_header?(header) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
34
35
# File 'lib/easyai/base/toml_sections.rb', line 31

def project_header?(header)
  return false if header.nil?

  header.start_with?(PROJECT_HEADER_PREFIX)
end

.reject_projects(text) ⇒ Object



54
55
56
57
# File 'lib/easyai/base/toml_sections.rb', line 54

def reject_projects(text)
  kept = split_sections(text).reject { |s| project_header?(s.header) }
  render(kept)
end

.split_sections(text) ⇒ Object

切段:返回 [Section, ...]。文件开头无 table 头的部分作为 header=nil 的前导段。



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/easyai/base/toml_sections.rb', line 38

def split_sections(text)
  sections = []
  current = Section.new(header: nil, body: +'')

  text.to_s.each_line do |line|
    if header_line?(line)
      sections << current unless empty_preamble?(current)
      current = Section.new(header: header_key(line), body: +line.dup)
    else
      current.body << line
    end
  end
  sections << current unless empty_preamble?(current)
  sections
end