Skip to content

Instantly share code, notes, and snippets.

@Ryan1729
Created April 7, 2016 20:35
Show Gist options
  • Save Ryan1729/9609a3ca5915f3e2aff3bc7ae84c8d9b to your computer and use it in GitHub Desktop.
Save Ryan1729/9609a3ca5915f3e2aff3bc7ae84c8d9b to your computer and use it in GitHub Desktop.
get local, (non library) lua dependencies in tgf
-- this creates a Trivial Graph Format representaion of the
-- require-based dependancies of the lua files in the current directory,
-- then saves it to <containing folder name>_deps.tgf
-- run in the directory you want to graph like this:
-- lua dependanciesTGF.lua
--requires Penlight
local file = require "pl.file"
local dir = require "pl.dir"
local path = require "pl.path"
local tablex = require "pl.tablex"
local stringio = require "pl.stringio"
local func = require "pl.func"
local fileList = dir.getfiles(".", "*.lua")
-- from http://lua-users.org/wiki/CommonFunctions
-- Lua pattern for matching Lua single line comment.
local pat_scomment = "(%-%-[^\n]*)"
-- Lua pattern for matching Lua multi-line comment.
local pat_mcomment = "(%-%-%[(=*)%[.-%]%2%])"
local nodes = stringio.create()
local edges = stringio.create()
local getRequireTarget = function(str) return string.match(str, "%./(.*)%.lua") end
local requireTargets = tablex.map(getRequireTarget, fileList)
local nodeIndicies = tablex.index_map (requireTargets)
tablex.foreachi (fileList, function(filename, index)
nodes:write(index .. " " .. requireTargets[index] .. "\n")
local contents = file.read(filename) .. "\n"
contents = contents:gsub(pat_mcomment, "")
contents = contents:gsub(pat_scomment, "")
for line in contents:gmatch("[^\r\n]+") do
local requireLine = line:match(".*require.-[^\r\n]+") or ""
local requireTarget = requireLine:match("\"(.*)\"")
if requireTarget then
local sourceIndex = nodeIndicies[requireTargets[index]]
local targetIndex = nodeIndicies[requireTarget]
if sourceIndex and targetIndex then
edges:write(sourceIndex .. " " .. targetIndex .. " " .. requireTarget .. "\n")
end
end
end
end)
local result = nodes:value() .. "#\n" .. edges:value()
print(file.write((path.currentdir() or ""):match("/([^/]-)$") .. "_deps.tgf", result))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment