Skip to content

Instantly share code, notes, and snippets.

@cfillion
Last active December 23, 2015 01:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cfillion/6d99012e7eb971fdf937 to your computer and use it in GitHub Desktop.
Save cfillion/6d99012e7eb971fdf937 to your computer and use it in GitHub Desktop.
Batch header converter for ReaScripts
DEFAULT_VERSION = '0.1'.freeze
PREFIX = ' * '.freeze
INDENT = "\x20" * 2
LOG_REGEX = /
\s*(?:(?:--)?\]\]|\*\/)
(.+
Changelog\s*:\n
(.+?)\n\s*
((?:--)?\]\]|\*\/))
/xm.freeze
SPK_REGEX = /(\/\/ EEL.+spk.+(\d{2})\.(\d{2})\.(\d{4}).*)(\n+)/.freeze
VER_REGEX = /
(?:#{Regexp.escape PREFIX})
\s*v([\d\.]+)\s*([^\n]+)
/x.freeze
Version = Struct.new :name, :changelog
def process_file(path, encoding = Encoding::UTF_8)
file = File.new path, 'r+t', :encoding => encoding
before = file.read
return if before =~ /(?<!\n\n)(?:\*|\/\/|--) Version\s*:/
# fix the usual changelog format
after = before.sub LOG_REGEX do |match|
versions = []
trailing = $1.chomp("--[[\n#{PREFIX}").chomp("/**\n#{PREFIX}").rstrip
close = $3
$2.lines {|line|
if VER_REGEX =~ line
ver = Version.new $1, $2
versions << ver
else
if versions.empty?
ver = Version.new DEFAULT_VERSION, String.new
versions << ver
warn "first changelog line in %s is not a version – assuming %s:" \
% [path, ver.name]
warn line + "\n\n"
end
versions.last.changelog += "\n" + line
end
}
if versions.empty?
warn "Cannot find any version in #{path}"
next match
end
ver = "#{PREFIX}Version: #{versions.first.name}"
"\n#{PREFIX.rstrip}\n" + ver + "\n" + close + trailing
end
# fix scripts with a newline before the version tag
if before.include? "\n// Version"
after = before.sub "\n// Version", '// Version'
end
# fix spk's scripts
if before =~ SPK_REGEX
after = before.sub SPK_REGEX, "\\1\n// Version: 0.\\4.\\3.\\2\\5"
end
# fix scripts without any metadata
if after == before
warn "no version found in %s – creating %s" % [path, DEFAULT_VERSION]
type = File.extname path
comment = type == '.lua' ? '--' : '//'
after = "#{comment} Version: #{DEFAULT_VERSION}\n\n#{before}"
end
file.rewind
file.write after
file.truncate file.pos
rescue ArgumentError => e
if e.message == 'invalid byte sequence in UTF-8'
encoding = Encoding::ISO_8859_1
retry
else
throw
end
ensure
file.close
end
count = 0
Dir.glob '**/*.{lua,eel}' do |path|
count += 1 if process_file path
end
puts "%d files modified!" % count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment