From c677e1f7e814d950d269e7ef22c9bc837660985d Mon Sep 17 00:00:00 2001 From: bfs15 <bruno.serbena@gmail.com> Date: Tue, 4 Jul 2017 14:56:53 -0300 Subject: [PATCH] Added script to add header to files, maintaining shebangs --- insert_header.rb | 82 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 insert_header.rb diff --git a/insert_header.rb b/insert_header.rb new file mode 100644 index 00000000..8e4339c0 --- /dev/null +++ b/insert_header.rb @@ -0,0 +1,82 @@ +#!/usr/bin/env ruby + +require 'fileutils' + +# array of tuples +HEADER_FILENAME = 0 +EXTENSIONS = 1 +headers = [ + # file with license commented with hashtags # like this + # codes with hashtag comments + ["license.txt", [".rb", ".yml", ".rake", ".ru", ".sh"]] + # add other files that use other comment types + # add other extensions that use other comment types +] + +# if your code commets aren't hashtags, create other license files +# add new license file and file extensions to the array like this + +# headers = [ +# ["license.slash.txt", [".ext_with_slash"]] +# ["license.hash.txt", [".ext_with_hash1", ".ext_with_hash2"]] +# ] + +# inserts contents of file 'header_filename' into all files of type in the array 'extensions' +def insert_header_on_filetypes(extensions, header_filename) + extensions.each { |e| + Dir.glob("#{Dir.pwd}/**/*#{e}").each { |filename| + new_f = File.join(File.dirname(filename), File.basename(header_filename) + ".tmp") + + FileUtils.cp(header_filename, new_f) + + puts "Appending " + filename + " into " + new_f + File.open(filename, "r") { |file| + line = file.gets + # if file has shebang on first line + if line.start_with?("#!/") + File.open(new_f,"w") { |merged_file| + # adds the original file shebang #!/usr/bin/[..] as first line + merged_file << line + + # writes header file + File.open(header_filename, "r") { |header_file| + while h_line = header_file.gets + merged_file << h_line + end + } + + # writes remaining source file + while line = file.gets + merged_file << line + end + } + # if file doesn't have shebang on first line + else + File.open(new_f,"a") { |merged_file| + # appends source file to header_file + merged_file << line + while line = file.gets + merged_file << line + end + } + end + } + + puts "Overwriting \"" + new_f + "\" into " + filename + File.rename(new_f, filename) + puts "done\n\n" + } + } +end + +def checkFile(path) + if !File.file?(path) + puts "Header file specified #{File.basename(path)} does not exist on current directory, please create one" + exit + end +end + +headers.each { |header| + checkFile(header[HEADER_FILENAME]) + insert_header_on_filetypes(header[EXTENSIONS], header[HEADER_FILENAME]) +} -- GitLab