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
|
# File 'lib/moonshard.rb', line 44
def self.replace(root_dir)
root_dir = File.expand_path(root_dir)
backup_file = File.expand_path(DEFAULT_BACKUP_FILE)
original_files = {}
Dir.glob(File.join(root_dir, "**", "*")).each do |file|
next unless File.file?(file)
next if File.expand_path(file) == backup_file
begin
content = File.read(file)
rescue => e
warn "Warning: cannot read #{file}: #{e.message}"
next
end
next unless content.match?(/##\{[^}]+\}/)
original_files[file] = content
file_dir = File.dirname(file)
replaced = content.gsub(/^([ \t]*)##\{([^}]+)\}[ \t]*$/) do
indentation = Regexp.last_match(1)
referenced_file = Regexp.last_match(2)
referenced_path = File.expand_path(
referenced_file,
file_dir
)
unless File.file?(referenced_path)
warn "Warning: file not found: #{referenced_path} (referenced from #{file})"
next Regexp.last_match(0)
end
inserted_content = File.read(referenced_path).chomp
inserted_content.lines.map do |line|
if line.strip.empty?
line
else
indentation + line
end
end.join
end
next if replaced == content
File.write(file, replaced)
puts "Updated: #{file}"
end
File.write(
backup_file,
JSON.pretty_generate(original_files)
)
puts "Backup saved to: #{backup_file}"
true
end
|