Module: PrependCode::Application
- Defined in:
- lib/prepend_code.rb
Class Method Summary collapse
- .exit_with_usage ⇒ Object
- .find_file_paths(dir_name, ext) ⇒ Object
- .prepend_on_file!(file_path, context) ⇒ Object
- .run!(*arguments) ⇒ Object
Class Method Details
.exit_with_usage ⇒ Object
10 11 12 13 |
# File 'lib/prepend_code.rb', line 10 def self.exit_with_usage puts @opts.to_s return 0 end |
.find_file_paths(dir_name, ext) ⇒ Object
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/prepend_code.rb', line 47 def self.find_file_paths(dir_name, ext) ret = [] dirs = Dir.glob(dir_name) dirs.each {|d| next unless FileTest.directory?(d) sub_dirs = Dir.glob("#{d}/**") sub_dirs.each {|d| if FileTest.directory?(d) ret += find_file_paths(d, ext) elsif FileTest.file?(d) if d =~ /^*#{ext}$/ ret << d end end } } return ret end |
.prepend_on_file!(file_path, context) ⇒ Object
67 68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/prepend_code.rb', line 67 def self.prepend_on_file!(file_path, context) f = File.open(file_path, "r+") lines = f.readlines f.close return false if lines && lines[0] == context + "\n" lines = [sprintf('%s%s', context, "\n")] + lines output = File.new(file_path, "w") lines.each { |line| output.write line } output.close return true end |
.run!(*arguments) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/prepend_code.rb', line 15 def self.run!(*arguments) ext = '.rb' = "Usage: prepend_code target_directory context [options]" @opts = OptionParser.new() @opts.on("-e [extension]", "target file extension. (default: .rb)"){|v| ext = v } @opts.parse!(arguments) dir_base = arguments[0] context = arguments[1] return self.exit_with_usage if context.nil? return self.exit_with_usage if dir_base.nil? file_paths = find_file_paths(dir_base, ext) loop do = [] << sprintf("Target directory is %s", dir_base) << sprintf("Context is %s", context) << sprintf("Target file count is %s. Are yor sure?[Y/n]", file_paths.count) input = Readline.readline(.join("\n")) break if input == 'Y' return 0 if input == 'n' end count = 0 file_paths.each do |file_path| result = prepend_on_file!(file_path, context) count += 1 if result end puts sprintf('%s files has been matched.', file_paths.count) puts sprintf('%s files has been updated.', count) return 1 end |