moonscript/bin/splat.moon

71 lines
1.8 KiB
Plaintext
Raw Normal View History

2011-12-12 00:57:07 +00:00
#!/usr/bin/env moon
2024-11-23 20:13:21 +00:00
argparse = require "argparse"
2011-12-12 00:57:07 +00:00
2024-11-23 20:13:21 +00:00
parser = argparse "splat.moon", "Concatenate a collection of Lua modules into a single file"
parser\option("--load -l", "Module names that will be load on require")\count "*"
2011-12-12 00:57:07 +00:00
2024-11-23 20:13:21 +00:00
parser\argument("directories", "Directories to scan for Lua modules")\args "+"
2024-11-23 20:13:21 +00:00
args = parser\parse [v for _, v in ipairs _G.arg]
dirs = args.directories
2011-12-12 00:57:07 +00:00
normalize = (path) ->
path\match("(.-)/*$").."/"
2024-11-23 20:13:21 +00:00
lfs = require "lfs"
2011-12-12 00:57:07 +00:00
scan_directory = (root, patt, collected={}) ->
root = normalize root
for fname in lfs.dir root
if not fname\match "^%."
full_path = root..fname
if lfs.attributes(full_path, "mode") == "directory"
scan_directory full_path, patt, collected
else
if full_path\match patt
2024-11-23 20:13:21 +00:00
table.insert collected, full_path
2011-12-12 00:57:07 +00:00
collected
path_to_module_name = (path) ->
(path\match("(.-)%.lua")\gsub("/", "."))
each_line = (text) ->
coroutine.wrap ->
start = 1
while true
pos, after = text\find "\n", start, true
break if not pos
2024-11-23 20:13:21 +00:00
coroutine.yield text\sub start, pos - 1
2011-12-12 00:57:07 +00:00
start = after + 1
2024-11-23 20:13:21 +00:00
coroutine.yield text\sub start, #text
2011-12-12 00:57:07 +00:00
nil
write_module = (name, text) ->
print "package.preload['"..name.."'] = function()"
for line in each_line text
print " "..line
print "end"
modules = {}
2011-12-12 01:12:17 +00:00
for dir in *dirs
files = scan_directory dir, "%.lua$"
chunks = for path in *files
module_name = path_to_module_name path
content = io.open(path)\read"*a"
modules[module_name] = true
{module_name, content}
for chunk in *chunks
name, content = unpack chunk
base = name\match"(.-)%.init"
if base and not modules[base] then
modules[base] = true
name = base
write_module name, content
2024-11-23 20:13:21 +00:00
for module_name in *args.load
if modules[module_name]
print ([[package.preload["%s"]()]])\format module_name
2011-12-12 00:57:07 +00:00