#!/usr/bin/python # -*- coding: utf8 -*- # # Filename: archive.py # Copyright: Odd Stråbø # License: MIT - http://opensource.org/licenses/MIT # import sys import os class S(object): def __init__(self, s, multi=False): self.multi = multi self.s = s def __str__(self): return self.s CC_SFX = """ local function extract(be, p) if p == nil then p = "" end if not fs.exists(p) then fs.makeDir(p) end for n,e in pairs(be) do local ep = fs.combine(p, n) if type(e) == "table" then print(ep .. "/") if fs.exists(ep) then error("Path exists on filesystem: " .. ep .. "/") end extract(e, ep) else print(ep) if fs.exists(ep) then error("Path exists on filesystem: " .. ep) end local fh = fs.open(ep, "w") fh.write(e) fh.close() end end end extract(data, ({...})[1]) """ IGNORE = [ ".hg", ".hgignore", ".git", ".gitignore", ] def encodeString(s): if not '\n' in s: if not '"' in s: return S('"{s}"'.format(s=s)) if not "'" in s: return S("'{s}'".format(s=s)) sep = [] while "]" + ''.join(sep) + "]" in s: sep.append("=") return S("[{sep}[{s}]{sep}]".format(s=s, sep=''.join(sep)), multi=True) def encodeFile(path): with open(path, "rb") as fh: data = fh.read() name = encodeString(os.path.basename(path)) if name.multi: return "[({name})]={data}".format(data=encodeString(data), name=name) else: return "[{name}]={data}".format(data=encodeString(data), name=name) def encodePath(path): if os.path.isfile(path): files = [path] elif os.path.isdir(path): files = map(lambda x: os.path.join(path, x), os.listdir(path)) content = [] for fn in files: if os.path.isfile(fn): content.append(encodeFile(fn)) if os.path.isdir(fn): content.append(encodePath(fn)) name = encodeString(os.path.basename(path)) if name.multi: return "[({name})]={{{data}}}".format(data=','.join(content), name=name) else: return "[{name}]={{{data}}}".format(data=','.join(content), name=name) def archive(path): return "local data={{{data}}}\n".format(data=encodePath(path)) if len(sys.argv) != 2: print("Usage: {0} (|)".format(sys.argv[0])) else: print(archive(sys.argv[1])) print(CC_SFX)