Skip to content

Instantly share code, notes, and snippets.

@fhirschmann
Created February 11, 2013 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fhirschmann/4755009 to your computer and use it in GitHub Desktop.
Save fhirschmann/4755009 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
volupack - Packs multiple Lua files for Vendetta Online into a single file.
Given the following layout:
main.lua:
mylib = {}
dofile("file1.lua")
dofile("file2.lua")
file1.lua:
mylib.foo = {}
function mylib.foo.bar ... end
file2.lua
mylib.bar = {}
mylib.bar.FOO = 2
calling volupack with the following parameters:
volupack mylib main.lua mylib_packed.lua
results in a file `mylib_packed.lua` with the following contents:
local mylib = {}
mylib.foo = {}
function mylib.foo.bar ... end
mylib.bar = {}
mylib.bar.FOO = 2
return mylib
The library can now be used by plugins like so:
local mylib = dofile("mylib_packed.lua")
print(mylib.bar.FOO)
.. moduleauthor:: Fabian Hirschmann <fabian@hirschm.net>
"""
from __future__ import print_function
import re
import os
import argparse
def walk(output, path, ns):
output.write("-- %s starts.%s" % (path, os.linesep))
with open(path) as f:
lineno = 1
output.write("\n")
for line in f.readlines():
line = line.replace("\r\n", "").replace("\n", "") + os.linesep
if "dofile" in line:
match = re.match("dofile\(['\"]*(.+?)['\"]\)", line)
if not match:
print("WARNING: Could not include file in %s:%s:\n\t%s" % (
path, lineno, line))
output.write(line)
continue
walk(output, match.group(1), ns)
else:
match = False
if line.startswith("declare("):
# replace: declare(ns, ...)
match = re.match("declare\(['\"]*%s['\"], (.+?)\)" % ns, line)
value = match.group(1)
else:
# replace: ns = ...
match = re.match("%s\s=\s(.+)" % ns, line)
if match:
print(line)
if match:
print("WARNING: Replaced global declare in %s:%s" % (
path, lineno))
print("< %s" % line.strip())
newline = "local %s = %s" % (ns, "{}" if "or {}" in value else value)
print("> %s" % newline)
output.write(newline)
else:
output.write(line)
lineno += 1
output.write("-- %s ends.%s" % (path, os.linesep))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=os.linesep.join(__doc__.split("\n")[:-2]),
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("namespace", type=str, help="global namespace to remove")
parser.add_argument("main", type=str, help="file to start with")
parser.add_argument("output", type=str, help="output file")
args = parser.parse_args()
with open(args.output, "w") as output:
output.write("-- packed using volupack." + os.linesep)
walk(output, args.main, args.namespace)
output.write("return " + args.namespace + os.linesep)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment