Permalink
Browse files

Preserve the first comment line from the input grammar to the output …

…(for the magic comment)
  • Loading branch information...
1 parent 7ba87fb commit 21416e7ae30da7ca1e20c8ce358d3b5fe97dd1f0 @cjheath committed Jun 4, 2013
Showing with 17 additions and 5 deletions.
  1. +1 −1 bin/tt
  2. +7 −2 lib/treetop/compiler/grammar_compiler.rb
  3. +9 −2 spec/compiler/tt_compiler_spec.rb
View
2 bin/tt
@@ -77,7 +77,7 @@ end
def protect_output?(filename, forced=false)
if !forced and
File.exist?(filename) and
- (l=File.open(filename) { |f| f.gets rescue "" }) != Treetop::Compiler::AUTOGENERATED
+ File.open(filename) { |f| ![(f.gets rescue ''), (f.gets rescue '')].include? Treetop::Compiler::AUTOGENERATED }
puts "ERROR: '#{filename}' output already exists; skipping compilation...\n"
return true
end
@@ -4,8 +4,13 @@ module Compiler
class GrammarCompiler
def compile(source_path, target_path = source_path.gsub(/\.(treetop|tt)\Z/, '.rb'))
File.open(target_path, 'w') do |target_file|
- target_file.write(AUTOGENERATED+"\n\n")
- target_file.write(ruby_source(source_path))
+ ruby = ruby_source(source_path)
+ if ruby =~ /\A#.*\n/
+ ruby.sub!(/\n/, "\n"+AUTOGENERATED+"\n\n")
+ else
+ ruby = AUTOGENERATED+"\n\n"+ruby
+ end
+ target_file.write(ruby)
end
end
@@ -20,6 +20,7 @@
@test_grammar = "#{@test_path}.tt"
@test_ruby = "#{@test_path}.rb"
File.open(@test_grammar, 'w+') do |f|
+ f.print("# Encoding: UTF-8\n")
f.print("grammar Dumb\n")
f.print("end\n")
end unless File.exists?(@test_grammar)
@@ -96,8 +97,14 @@
File.exists?(pf).should be_true
File.zero?(pf).should_not be_true
- # Modify the file and make sure it remains unchanged:
- File.open(pf, "r+") { |f| f.write("# Changed...") }
+ # Check that the magic comment is preserved:
+ written = File.open(pf, "r") { |f| s = f.read }
+ written.should =~ /\A# Encoding: UTF-8/
+
+ # Modify the file's auto-generated comment and make sure it doesn't get overwritten:
+ written.sub!(/generated/, 'broken');
+ File.open(pf, "w") { |f| f.write(written) }
+ # File.open(pf, "r+") { |f| s = f.read; s.sub!(/generated/, 'broken'); f.rewind; f.write(s) }
orig_file_hash = Digest::SHA1.hexdigest(File.read(pf))
Kernel.open("|ruby -S tt -o #{pf} #{@test_path}") do |io|

0 comments on commit 21416e7

Please sign in to comment.