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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
|
# File 'lib/rawfeed/layout.rb', line 30
def self.change_yml(section, key, new_value, path_match = nil)
raise "File #{CONFIG_PATH} not found" unless File.exist?(CONFIG_PATH)
yaml_value = case new_value
when true then "true"
when false then "false"
else
s = new_value.to_s
s =~ /\A[-+]?\d+(\.\d+)?\z/ ? s : "\"#{s.gsub('"', '\"')}\""
end
lines = File.readlines(CONFIG_PATH)
modified = false
if section == "defaults"
path_indices = lines.each_index.select { |i| lines[i] =~ /^\s*path:\s*["']?#{Regexp.escape(path_match)}["']?/ }
path_indices.each do |path_i|
start_i = (0..path_i).to_a.reverse.find { |j| lines[j] =~ /^\s*-\s*scope:/ }
next unless start_i
values_i = ((start_i + 1)..[lines.length - 1, start_i + 40].min)
.find { |k| lines[k] =~ /^\s*values:\s*$/ }
next unless values_i
dash_indent = lines[start_i][/^\s*/].size
published_i = nil
m = values_i + 1
while m < lines.length
line = lines[m]
break if line =~ /^\s*-\s*scope:/ && line[/^\s*/].size == dash_indent
break if line =~ /^\S/ && line[/^\s*/].size <= dash_indent
if line =~ /^\s*#{key}\s*:/
published_i = m
break
end
m += 1
end
if published_i
indent = lines[published_i][/^\s*/]
= lines[published_i][/#.*/] ? " " + lines[published_i][/#.*/] : ""
lines[published_i] = "#{indent}#{key}: #{yaml_value}#{}\n"
modified = true
else
values_indent = lines[values_i][/^\s*/]
insert_indent = values_indent + " "
lines.insert(values_i + 1, "#{insert_indent}#{key}: #{yaml_value}\n")
modified = true
end
end
else
section_i = lines.find_index { |l| l =~ /^#{section}:\s*$/ }
if section_i
indent_section = lines[section_i][/^\s*/]
key_indent = indent_section + " "
key_i = nil
m = section_i + 1
while m < lines.length
line = lines[m]
break if line =~ /^\S/ if line =~ /^\s*#{key}\s*:/
key_i = m
break
end
m += 1
end
if key_i
indent = lines[key_i][/^\s*/]
= lines[key_i][/#.*/] ? " " + lines[key_i][/#.*/] : ""
lines[key_i] = "#{indent}#{key}: #{yaml_value}#{}\n"
modified = true
else
lines.insert(section_i + 1, "#{key_indent}#{key}: #{yaml_value}\n")
modified = true
end
end
end
unless modified
return { changed: false, message: "Nothing changed (structure not found)" }
end
File.write(BACKUP_PATH, File.read(CONFIG_PATH))
File.open(CONFIG_PATH, "w") { |f| f.write(lines.join) }
{ changed: true, backup: BACKUP_PATH, path: CONFIG_PATH }
end
|