liner 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/env ruby
  2. # This script reads in a file and annotates it with
  3. # line number directives. Existing line annotations are updated.
  4. require 'optparse'
  5. @options = {}
  6. OptionParser.new do |opts|
  7. opts.on("-o", "--out FILENAME", "Output FILENAME to write to.") do | v |
  8. @options[:out_file] = v
  9. end
  10. opts.on("-i", "--in FILENAME", "Input FILENAME to read.") do | v |
  11. @options[:in_file] = v
  12. end
  13. opts.on("-a", "--annotate REGEXP", "REGEXP, if matched, marker is written.") do | v |
  14. @options[:annotate_re] = Regexp.new(v)
  15. end
  16. opts.on("-f", "--format FORMAT", "printf FORMAT of marker, must contain %s and %d of.") do | v |
  17. @options[:marker_format] = v
  18. end
  19. opts.on("-m", "--marker REGEXP", "REGEXP, if matched, marker is updated.") do | v |
  20. @options[:marker_re] = Regexp.new(v)
  21. end
  22. opts.on("-s", "--skip", "If set skipsthe markers in the line count") do | v |
  23. @options[:skip] = true
  24. end
  25. end.parse!
  26. file_name = @options[:in_file] || ARGV[0]
  27. if file_name == nil
  28. puts "liner: liner [options] file_to_annotate"
  29. exit 1
  30. end
  31. annotate_re = @options[:annotate_re] || %r{^(func|type|const)}
  32. marker_format = @options[:marker_format] || "//line %s:%d\n"
  33. marker_re = @options[:marker_re] || %r{^//line [^:]+:[0-9]+$}
  34. out_name = @options[:out_file]
  35. lines = nil
  36. File.open(file_name) do |file|
  37. lines = file.readlines
  38. end
  39. marker_before = false
  40. out = $stdout
  41. if out_name
  42. out = File.open(out_name, "w+")
  43. if out == nil
  44. puts "liner: cannot open output file #{out_name}"
  45. exit 2
  46. end
  47. end
  48. line_number = 0
  49. lines.each do |line|
  50. line_number += 1
  51. marker_match = marker_re.match(line)
  52. if marker_match != nil
  53. # Update existing marker
  54. out.printf(marker_format, file_name, line_number)
  55. marker_before = true
  56. # Skip read line in output
  57. next
  58. end
  59. if marker_before
  60. marker_before = false
  61. else
  62. annotate_match = annotate_re.match(line)
  63. if annotate_match
  64. out.printf(marker_format, file_name, line_number)
  65. line_number += 1 unless @options[:skip]
  66. end
  67. end
  68. out.puts(line)
  69. end
  70. if out != $stdout
  71. out.close
  72. end