"
print_banner()
print_section("NAME")
util.printout("\t"..program.." "..command.." - "..cmd.help_summary)
print_section("SYNOPSIS")
util.printout("\t"..program.." "..command.." "..arguments)
print_section("DESCRIPTION")
util.printout("",(cmd.help:gsub("\n","\n\t"):gsub("\n\t$","")))
print_section("SEE ALSO")
util.printout("","'"..program.." help' for general options and configuration.\n")
else
return nil, "Unknown command: "..command
end
end
return true
end
return help
luarocks-2.4.2+dfsg/src/luarocks/index.lua 0000664 0000000 0000000 00000012564 13030154704 0020512 0 ustar 00root root 0000000 0000000
--- Module which builds the index.html page to be used in rocks servers.
local index = {}
package.loaded["luarocks.index"] = index
local util = require("luarocks.util")
local fs = require("luarocks.fs")
local deps = require("luarocks.deps")
local persist = require("luarocks.persist")
local dir = require("luarocks.dir")
local manif = require("luarocks.manif")
local ext_url_target = ' target="_blank"'
local index_header = [[
Available rocks
Available rocks
Lua modules available from this location for use with LuaRocks:
]]
local index_package_begin = [[
$package - $summary
$detailed
$externaldependencies
latest sources $homepage | License: $license
|
]]
local index_package_end = [[
|
|
]]
local index_footer_begin = [[
manifest file
]]
local index_manifest_ver = [[
• Lua $VER manifest file (zip)
]]
local index_footer_end = [[
]]
function index.format_external_dependencies(rockspec)
if rockspec.external_dependencies then
local deplist = {}
local listed_set = {}
local plats = nil
for name, desc in util.sortedpairs(rockspec.external_dependencies) do
if name ~= "platforms" then
table.insert(deplist, name:lower())
listed_set[name] = true
else
plats = desc
end
end
if plats then
for plat, entries in util.sortedpairs(plats) do
for name, desc in util.sortedpairs(entries) do
if not listed_set[name] then
table.insert(deplist, name:lower() .. " (on "..plat..")")
end
end
end
end
return 'External dependencies: ' .. table.concat(deplist, ', ').. '
'
else
return ""
end
end
function index.make_index(repo)
if not fs.is_dir(repo) then
return nil, "Cannot access repository at "..repo
end
local manifest = manif.load_manifest(repo)
local out = io.open(dir.path(repo, "index.html"), "w")
out:write(index_header)
for package, version_list in util.sortedpairs(manifest.repository) do
local latest_rockspec = nil
local output = index_package_begin
for version, data in util.sortedpairs(version_list, deps.compare_versions) do
local versions = {}
output = output..version..': '
table.sort(data, function(a,b) return a.arch < b.arch end)
for _, item in ipairs(data) do
local file
if item.arch == 'rockspec' then
file = ("%s-%s.rockspec"):format(package, version)
if not latest_rockspec then latest_rockspec = file end
else
file = ("%s-%s.%s.rock"):format(package, version, item.arch)
end
table.insert(versions, ''..item.arch..'')
end
output = output .. table.concat(versions, ', ') .. '
'
end
output = output .. index_package_end
if latest_rockspec then
local rockspec = persist.load_into_table(dir.path(repo, latest_rockspec))
local descript = rockspec.description or {}
local vars = {
anchor = package,
package = rockspec.package,
original = rockspec.source.url,
summary = descript.summary or "",
detailed = descript.detailed or "",
license = descript.license or "N/A",
homepage = descript.homepage and ('| project homepage') or "",
externaldependencies = index.format_external_dependencies(rockspec)
}
vars.detailed = vars.detailed:gsub("\n\n", ""):gsub("%s+", " ")
vars.detailed = vars.detailed:gsub("(https?://[a-zA-Z0-9%.%%-_%+%[%]=%?&/$@;:]+)", '%1')
output = output:gsub("$(%w+)", vars)
else
output = output:gsub("$anchor", package)
output = output:gsub("$package", package)
output = output:gsub("$(%w+)", "")
end
out:write(output)
end
out:write(index_footer_begin)
for ver in util.lua_versions() do
out:write((index_manifest_ver:gsub("$VER", ver)))
end
out:write(index_footer_end)
out:close()
end
return index
luarocks-2.4.2+dfsg/src/luarocks/install.lua 0000664 0000000 0000000 00000016150 13030154704 0021044 0 ustar 00root root 0000000 0000000 --- Module implementing the LuaRocks "install" command.
-- Installs binary rocks.
local install = {}
package.loaded["luarocks.install"] = install
local path = require("luarocks.path")
local repos = require("luarocks.repos")
local fetch = require("luarocks.fetch")
local util = require("luarocks.util")
local fs = require("luarocks.fs")
local deps = require("luarocks.deps")
local manif = require("luarocks.manif")
local remove = require("luarocks.remove")
local cfg = require("luarocks.cfg")
util.add_run_function(install)
install.help_summary = "Install a rock."
install.help_arguments = "{| []}"
install.help = [[
Argument may be the name of a rock to be fetched from a repository
or a filename of a locally available rock.
--keep Do not remove previously installed versions of the
rock after installing a new one. This behavior can
be made permanent by setting keep_other_versions=true
in the configuration file.
--only-deps Installs only the dependencies of the rock.
]]..util.deps_mode_help()
--- Install a binary rock.
-- @param rock_file string: local or remote filename of a rock.
-- @param deps_mode: string: Which trees to check dependencies for:
-- "one" for the current default tree, "all" for all trees,
-- "order" for all trees with priority >= the current default, "none" for no trees.
-- @return (string, string) or (nil, string, [string]): Name and version of
-- installed rock if succeeded or nil and an error message followed by an error code.
function install.install_binary_rock(rock_file, deps_mode)
assert(type(rock_file) == "string")
local name, version, arch = path.parse_name(rock_file)
if not name then
return nil, "Filename "..rock_file.." does not match format 'name-version-revision.arch.rock'."
end
if arch ~= "all" and arch ~= cfg.arch then
return nil, "Incompatible architecture "..arch, "arch"
end
if repos.is_installed(name, version) then
repos.delete_version(name, version, deps_mode)
end
local rollback = util.schedule_function(function()
fs.delete(path.install_dir(name, version))
fs.remove_dir_if_empty(path.versions_dir(name))
end)
local ok, err, errcode = fetch.fetch_and_unpack_rock(rock_file, path.install_dir(name, version))
if not ok then return nil, err, errcode end
local rockspec, err, errcode = fetch.load_rockspec(path.rockspec_file(name, version))
if err then
return nil, "Failed loading rockspec for installed package: "..err, errcode
end
if deps_mode == "none" then
util.printerr("Warning: skipping dependency checks.")
else
ok, err, errcode = deps.check_external_deps(rockspec, "install")
if err then return nil, err, errcode end
end
-- For compatibility with .rock files built with LuaRocks 1
if not fs.exists(path.rock_manifest_file(name, version)) then
ok, err = manif.make_rock_manifest(name, version)
if err then return nil, err end
end
if deps_mode ~= "none" then
ok, err, errcode = deps.fulfill_dependencies(rockspec, deps_mode)
if err then return nil, err, errcode end
end
ok, err = repos.deploy_files(name, version, repos.should_wrap_bin_scripts(rockspec), deps_mode)
if err then return nil, err end
util.remove_scheduled_function(rollback)
rollback = util.schedule_function(function()
repos.delete_version(name, version, deps_mode)
end)
ok, err = repos.run_hook(rockspec, "post_install")
if err then return nil, err end
util.announce_install(rockspec)
util.remove_scheduled_function(rollback)
return name, version
end
--- Installs the dependencies of a binary rock.
-- @param rock_file string: local or remote filename of a rock.
-- @param deps_mode: string: Which trees to check dependencies for:
-- "one" for the current default tree, "all" for all trees,
-- "order" for all trees with priority >= the current default, "none" for no trees.
-- @return (string, string) or (nil, string, [string]): Name and version of
-- the rock whose dependencies were installed if succeeded or nil and an error message
-- followed by an error code.
function install.install_binary_rock_deps(rock_file, deps_mode)
assert(type(rock_file) == "string")
local name, version, arch = path.parse_name(rock_file)
if not name then
return nil, "Filename "..rock_file.." does not match format 'name-version-revision.arch.rock'."
end
if arch ~= "all" and arch ~= cfg.arch then
return nil, "Incompatible architecture "..arch, "arch"
end
local ok, err, errcode = fetch.fetch_and_unpack_rock(rock_file, path.install_dir(name, version))
if not ok then return nil, err, errcode end
local rockspec, err, errcode = fetch.load_rockspec(path.rockspec_file(name, version))
if err then
return nil, "Failed loading rockspec for installed package: "..err, errcode
end
ok, err, errcode = deps.fulfill_dependencies(rockspec, deps_mode)
if err then return nil, err, errcode end
util.printout()
util.printout("Successfully installed dependencies for " ..name.." "..version)
return name, version
end
--- Driver function for the "install" command.
-- @param name string: name of a binary rock. If an URL or pathname
-- to a binary rock is given, fetches and installs it. If a rockspec or a
-- source rock is given, forwards the request to the "build" command.
-- If a package name is given, forwards the request to "search" and,
-- if returned a result, installs the matching rock.
-- @param version string: When passing a package name, a version number
-- may also be given.
-- @return boolean or (nil, string, exitcode): True if installation was
-- successful, nil and an error message otherwise. exitcode is optionally returned.
function install.command(flags, name, version)
if type(name) ~= "string" then
return nil, "Argument missing. "..util.see_help("install")
end
local ok, err = fs.check_command_permissions(flags)
if not ok then return nil, err, cfg.errorcodes.PERMISSIONDENIED end
if name:match("%.rockspec$") or name:match("%.src%.rock$") then
local build = require("luarocks.build")
return build.command(flags, name)
elseif name:match("%.rock$") then
if flags["only-deps"] then
ok, err = install.install_binary_rock_deps(name, deps.get_deps_mode(flags))
else
ok, err = install.install_binary_rock(name, deps.get_deps_mode(flags))
end
if not ok then return nil, err end
name, version = ok, err
if (not flags["only-deps"]) and (not flags["keep"]) and not cfg.keep_other_versions then
local ok, err = remove.remove_other_versions(name, version, flags["force"], flags["force-fast"])
if not ok then util.printerr(err) end
end
manif.check_dependencies(nil, deps.get_deps_mode(flags))
return name, version
else
local search = require("luarocks.search")
local url, err = search.find_suitable_rock(search.make_query(name:lower(), version))
if not url then
return nil, err
end
util.printout("Installing "..url)
return install.command(flags, url)
end
end
return install
luarocks-2.4.2+dfsg/src/luarocks/lint.lua 0000664 0000000 0000000 00000002767 13030154704 0020355 0 ustar 00root root 0000000 0000000
--- Module implementing the LuaRocks "lint" command.
-- Utility function that checks syntax of the rockspec.
local lint = {}
package.loaded["luarocks.lint"] = lint
local util = require("luarocks.util")
local download = require("luarocks.download")
local fetch = require("luarocks.fetch")
util.add_run_function(lint)
lint.help_summary = "Check syntax of a rockspec."
lint.help_arguments = ""
lint.help = [[
This is a utility function that checks the syntax of a rockspec.
It returns success or failure if the text of a rockspec is
syntactically correct.
]]
function lint.command(flags, input)
if not input then
return nil, "Argument missing. "..util.see_help("lint")
end
local filename = input
if not input:match(".rockspec$") then
local err
filename, err = download.download("rockspec", input:lower())
if not filename then
return nil, err
end
end
local rs, err = fetch.load_local_rockspec(filename)
if not rs then
return nil, "Failed loading rockspec: "..err
end
local ok = true
-- This should have been done in the type checker,
-- but it would break compatibility of other commands.
-- Making 'lint' alone be stricter shouldn't be a problem,
-- because extra-strict checks is what lint-type commands
-- are all about.
if not rs.description.license then
util.printerr("Rockspec has no license field.")
ok = false
end
return ok, ok or filename.." failed consistency checks."
end
return lint
luarocks-2.4.2+dfsg/src/luarocks/list.lua 0000664 0000000 0000000 00000006373 13030154704 0020357 0 ustar 00root root 0000000 0000000
--- Module implementing the LuaRocks "list" command.
-- Lists currently installed rocks.
local list = {}
package.loaded["luarocks.list"] = list
local search = require("luarocks.search")
local deps = require("luarocks.deps")
local cfg = require("luarocks.cfg")
local util = require("luarocks.util")
local path = require("luarocks.path")
util.add_run_function(list)
list.help_summary = "List currently installed rocks."
list.help_arguments = "[--porcelain] "
list.help = [[
is a substring of a rock name to filter by.
--outdated List only rocks for which there is a
higher version available in the rocks server.
--porcelain Produce machine-friendly output.
]]
local function check_outdated(trees, query)
local results_installed = {}
for _, tree in ipairs(trees) do
search.manifest_search(results_installed, path.rocks_dir(tree), query)
end
local outdated = {}
for name, versions in util.sortedpairs(results_installed) do
versions = util.keys(versions)
table.sort(versions, deps.compare_versions)
local latest_installed = versions[1]
local query_available = search.make_query(name:lower())
query.exact_name = true
local results_available, err = search.search_repos(query_available)
if results_available[name] then
local available_versions = util.keys(results_available[name])
table.sort(available_versions, deps.compare_versions)
local latest_available = available_versions[1]
local latest_available_repo = results_available[name][latest_available][1].repo
if deps.compare_versions(latest_available, latest_installed) then
table.insert(outdated, { name = name, installed = latest_installed, available = latest_available, repo = latest_available_repo })
end
end
end
return outdated
end
local function list_outdated(trees, query, porcelain)
util.title("Outdated rocks:", porcelain)
local outdated = check_outdated(trees, query)
for _, item in ipairs(outdated) do
if porcelain then
util.printout(item.name, item.installed, item.available, item.repo)
else
util.printout(item.name)
util.printout(" "..item.installed.." < "..item.available.." at "..item.repo)
util.printout()
end
end
return true
end
--- Driver function for "list" command.
-- @param filter string or nil: A substring of a rock name to filter by.
-- @param version string or nil: a version may also be passed.
-- @return boolean: True if succeeded, nil on errors.
function list.command(flags, filter, version)
local query = search.make_query(filter and filter:lower() or "", version)
query.exact_name = false
local trees = cfg.rocks_trees
if flags["tree"] then
trees = { flags["tree"] }
end
if flags["outdated"] then
return list_outdated(trees, query, flags["porcelain"])
end
local results = {}
for _, tree in ipairs(trees) do
local ok, err, errcode = search.manifest_search(results, path.rocks_dir(tree), query)
if not ok and errcode ~= "open" then
util.warning(err)
end
end
util.title("Installed rocks:", flags["porcelain"])
search.print_results(results, flags["porcelain"])
return true
end
return list
luarocks-2.4.2+dfsg/src/luarocks/loader.lua 0000664 0000000 0000000 00000022732 13030154704 0020647 0 ustar 00root root 0000000 0000000
--- A module which installs a Lua package loader that is LuaRocks-aware.
-- This loader uses dependency information from the LuaRocks tree to load
-- correct versions of modules. It does this by constructing a "context"
-- table in the environment, which records which versions of packages were
-- used to load previous modules, so that the loader chooses versions
-- that are declared to be compatible with the ones loaded earlier.
local loaders = package.loaders or package.searchers
local package, require, ipairs, table, type, next, tostring, error =
package, require, ipairs, table, type, next, tostring, error
local unpack = unpack or table.unpack
--module("luarocks.loader")
local loader = {}
package.loaded["luarocks.loader"] = loader
local cfg = require("luarocks.cfg")
cfg.init_package_paths()
local path = require("luarocks.path")
local manif_core = require("luarocks.manif_core")
local deps = require("luarocks.deps")
local util = require("luarocks.util")
-- Workaround for wrappers produced by older versions of LuaRocks
local temporary_global = false
if luarocks then
-- The site_config.lua file generated by old versions uses module(),
-- so it produces a global `luarocks` table. Since we have the table,
-- add the `loader` field to make the old wrappers happy.
luarocks.loader = loader
else
-- When a new version is installed on top of an old version,
-- site_config.lua may be replaced, and then it no longer creates
-- a global.
-- Detect when being called via -lluarocks.loader; this is
-- most likely a wrapper.
local info = debug.getinfo(2, "nS")
if info.what == "C" and not info.name then
luarocks = { loader = loader }
temporary_global = true
-- For the other half of this hack,
-- see the next use of `temporary_global` below.
end
end
loader.context = {}
-- Contains a table when rocks trees are loaded,
-- or 'false' to indicate rocks trees failed to load.
-- 'nil' indicates rocks trees were not attempted to be loaded yet.
loader.rocks_trees = nil
local function load_rocks_trees()
local any_ok = false
local trees = {}
for _, tree in ipairs(cfg.rocks_trees) do
local manifest, err = manif_core.load_local_manifest(path.rocks_dir(tree))
if manifest then
any_ok = true
table.insert(trees, {tree=tree, manifest=manifest})
end
end
if not any_ok then
loader.rocks_trees = false
return false
end
loader.rocks_trees = trees
return true
end
--- Process the dependencies of a package to determine its dependency
-- chain for loading modules.
-- @param name string: The name of an installed rock.
-- @param version string: The version of the rock, in string format
function loader.add_context(name, version)
-- assert(type(name) == "string")
-- assert(type(version) == "string")
if temporary_global then
-- The first thing a wrapper does is to call add_context.
-- From here on, it's safe to clean the global environment.
luarocks = nil
temporary_global = false
end
if loader.context[name] then
return
end
loader.context[name] = version
if not loader.rocks_trees and not load_rocks_trees() then
return nil
end
for _, tree in ipairs(loader.rocks_trees) do
local manifest = tree.manifest
local pkgdeps
if manifest.dependencies and manifest.dependencies[name] then
pkgdeps = manifest.dependencies[name][version]
end
if not pkgdeps then
return nil
end
for _, dep in ipairs(pkgdeps) do
local pkg, constraints = dep.name, dep.constraints
for _, tree in ipairs(loader.rocks_trees) do
local entries = tree.manifest.repository[pkg]
if entries then
for version, pkgs in util.sortedpairs(entries, deps.compare_versions) do
if (not constraints) or deps.match_constraints(deps.parse_version(version), constraints) then
loader.add_context(pkg, version)
end
end
end
end
end
end
end
--- Internal sorting function.
-- @param a table: A provider table.
-- @param b table: Another provider table.
-- @return boolean: True if the version of a is greater than that of b.
local function sort_versions(a,b)
return a.version > b.version
end
--- Request module to be loaded through other loaders,
-- once the proper name of the module has been determined.
-- For example, in case the module "socket.core" has been requested
-- to the LuaRocks loader and it determined based on context that
-- the version 2.0.2 needs to be loaded and it is not the current
-- version, the module requested for the other loaders will be
-- "socket.core_2_0_2".
-- @param module The module name requested by the user, such as "socket.core"
-- @param name The rock name, such as "luasocket"
-- @param version The rock version, such as "2.0.2-1"
-- @param module_name The actual module name, such as "socket.core" or "socket.core_2_0_2".
-- @return table or (nil, string): The module table as returned by some other loader,
-- or nil followed by an error message if no other loader managed to load the module.
local function call_other_loaders(module, name, version, module_name)
for i, a_loader in ipairs(loaders) do
if a_loader ~= loader.luarocks_loader then
local results = { a_loader(module_name) }
if type(results[1]) == "function" then
return unpack(results)
end
end
end
return "Failed loading module "..module.." in LuaRocks rock "..name.." "..version
end
--- Search for a module in the rocks trees
-- @param module string: module name (eg. "socket.core")
-- @param filter_file_name function(string, string, string, string, number):
-- a function that takes the module file name (eg "socket/core.so"), the rock name
-- (eg "luasocket"), the version (eg "2.0.2-1"), the path of the rocks tree
-- (eg "/usr/local"), and the numeric index of the matching entry, so the
-- filter function can know if the matching module was the first entry or not.
-- @return string, string, string, (string or table):
-- * name of the rock containing the module (eg. "luasocket")
-- * version of the rock (eg. "2.0.2-1")
-- * return value of filter_file_name
-- * tree of the module (string or table in `rocks_trees` format)
local function select_module(module, filter_file_name)
--assert(type(module) == "string")
--assert(type(filter_module_name) == "function")
if not loader.rocks_trees and not load_rocks_trees() then
return nil
end
local providers = {}
for _, tree in ipairs(loader.rocks_trees) do
local entries = tree.manifest.modules[module]
if entries then
for i, entry in ipairs(entries) do
local name, version = entry:match("^([^/]*)/(.*)$")
local file_name = tree.manifest.repository[name][version][1].modules[module]
if type(file_name) ~= "string" then
error("Invalid data in manifest file for module "..tostring(module).." (invalid data for "..tostring(name).." "..tostring(version)..")")
end
file_name = filter_file_name(file_name, name, version, tree.tree, i)
if loader.context[name] == version then
return name, version, file_name
end
version = deps.parse_version(version)
table.insert(providers, {name = name, version = version, module_name = file_name, tree = tree})
end
end
end
if next(providers) then
table.sort(providers, sort_versions)
local first = providers[1]
return first.name, first.version.string, first.module_name, first.tree
end
end
--- Search for a module
-- @param module string: module name (eg. "socket.core")
-- @return string, string, string, (string or table):
-- * name of the rock containing the module (eg. "luasocket")
-- * version of the rock (eg. "2.0.2-1")
-- * name of the module (eg. "socket.core", or "socket.core_2_0_2" if file is stored versioned).
-- * tree of the module (string or table in `rocks_trees` format)
local function pick_module(module)
return
select_module(module, function(file_name, name, version, tree, i)
if i > 1 then
file_name = path.versioned_name(file_name, "", name, version)
end
return path.path_to_module(file_name)
end)
end
--- Return the pathname of the file that would be loaded for a module.
-- @param module string: module name (eg. "socket.core")
-- @return string: filename of the module (eg. "/usr/local/lib/lua/5.1/socket/core.so")
function loader.which(module)
local _, _, file_name = select_module(module, path.which_i)
return file_name
end
--- Package loader for LuaRocks support.
-- A module is searched in installed rocks that match the
-- current LuaRocks context. If module is not part of the
-- context, or if a context has not yet been set, the module
-- in the package with the highest version is used.
-- @param module string: The module name, like in plain require().
-- @return table: The module table (typically), like in plain
-- require(). See require()
-- in the Lua reference manual for details.
function loader.luarocks_loader(module)
local name, version, module_name = pick_module(module)
if not name then
return "No LuaRocks module found for "..module
else
loader.add_context(name, version)
return call_other_loaders(module, name, version, module_name)
end
end
table.insert(loaders, 1, loader.luarocks_loader)
return loader
luarocks-2.4.2+dfsg/src/luarocks/make.lua 0000664 0000000 0000000 00000007147 13030154704 0020321 0 ustar 00root root 0000000 0000000
--- Module implementing the LuaRocks "make" command.
-- Builds sources in the current directory, but unlike "build",
-- it does not fetch sources, etc., assuming everything is
-- available in the current directory.
local make = {}
package.loaded["luarocks.make"] = make
local build = require("luarocks.build")
local fs = require("luarocks.fs")
local util = require("luarocks.util")
local cfg = require("luarocks.cfg")
local fetch = require("luarocks.fetch")
local pack = require("luarocks.pack")
local remove = require("luarocks.remove")
local deps = require("luarocks.deps")
local manif = require("luarocks.manif")
util.add_run_function(make)
make.help_summary = "Compile package in current directory using a rockspec."
make.help_arguments = "[--pack-binary-rock] []"
make.help = [[
Builds sources in the current directory, but unlike "build",
it does not fetch sources, etc., assuming everything is
available in the current directory. If no argument is given,
it looks for a rockspec in the current directory and in "rockspec/"
and "rockspecs/" subdirectories, picking the rockspec with newest version
or without version name. If rockspecs for different rocks are found
or there are several rockspecs without version, you must specify which to use,
through the command-line.
This command is useful as a tool for debugging rockspecs.
To install rocks, you'll normally want to use the "install" and
"build" commands. See the help on those for details.
--pack-binary-rock Do not install rock. Instead, produce a .rock file
with the contents of compilation in the current
directory.
--keep Do not remove previously installed versions of the
rock after installing a new one. This behavior can
be made permanent by setting keep_other_versions=true
in the configuration file.
--branch= Override the `source.branch` field in the loaded
rockspec. Allows to specify a different branch to
fetch. Particularly for SCM rocks.
]]
--- Driver function for "make" command.
-- @param name string: A local rockspec.
-- @return boolean or (nil, string, exitcode): True if build was successful; nil and an
-- error message otherwise. exitcode is optionally returned.
function make.command(flags, rockspec)
assert(type(rockspec) == "string" or not rockspec)
if not rockspec then
local err
rockspec, err = util.get_default_rockspec()
if not rockspec then
return nil, err
end
end
if not rockspec:match("rockspec$") then
return nil, "Invalid argument: 'make' takes a rockspec as a parameter. "..util.see_help("make")
end
if flags["pack-binary-rock"] then
local rspec, err, errcode = fetch.load_rockspec(rockspec)
if not rspec then
return nil, err
end
return pack.pack_binary_rock(rspec.name, rspec.version, build.build_rockspec, rockspec, false, true, deps.get_deps_mode(flags))
else
local ok, err = fs.check_command_permissions(flags)
if not ok then return nil, err, cfg.errorcodes.PERMISSIONDENIED end
ok, err = build.build_rockspec(rockspec, false, true, deps.get_deps_mode(flags))
if not ok then return nil, err end
local name, version = ok, err
if (not flags["keep"]) and not cfg.keep_other_versions then
local ok, err = remove.remove_other_versions(name, version, flags["force"], flags["force-fast"])
if not ok then util.printerr(err) end
end
manif.check_dependencies(nil, deps.get_deps_mode(flags))
return name, version
end
end
return make
luarocks-2.4.2+dfsg/src/luarocks/make_manifest.lua 0000664 0000000 0000000 00000003517 13030154704 0022204 0 ustar 00root root 0000000 0000000
--- Module implementing the luarocks-admin "make_manifest" command.
-- Compile a manifest file for a repository.
local make_manifest = {}
package.loaded["luarocks.make_manifest"] = make_manifest
local manif = require("luarocks.manif")
local index = require("luarocks.index")
local cfg = require("luarocks.cfg")
local util = require("luarocks.util")
local deps = require("luarocks.deps")
local fs = require("luarocks.fs")
local dir = require("luarocks.dir")
util.add_run_function(make_manifest)
make_manifest.help_summary = "Compile a manifest file for a repository."
make_manifest.help = [[
, if given, is a local repository pathname.
--local-tree If given, do not write versioned versions of the manifest file.
Use this when rebuilding the manifest of a local rocks tree.
]]
--- Driver function for "make_manifest" command.
-- @param repo string or nil: Pathname of a local repository. If not given,
-- the default local repository configured as cfg.rocks_dir is used.
-- @return boolean or (nil, string): True if manifest was generated,
-- or nil and an error message.
function make_manifest.command(flags, repo)
assert(type(repo) == "string" or not repo)
repo = repo or cfg.rocks_dir
util.printout("Making manifest for "..repo)
if repo:match("/lib/luarocks") and not flags["local-tree"] then
util.warning("This looks like a local rocks tree, but you did not pass --local-tree.")
end
local ok, err = manif.make_manifest(repo, deps.get_deps_mode(flags), not flags["local-tree"])
if ok and not flags["local-tree"] then
util.printout("Generating index.html for "..repo)
index.make_index(repo)
end
if flags["local-tree"] then
for luaver in util.lua_versions() do
fs.delete(dir.path(repo, "manifest-"..luaver))
end
end
return ok, err
end
return make_manifest
luarocks-2.4.2+dfsg/src/luarocks/manif.lua 0000664 0000000 0000000 00000057005 13030154704 0020474 0 ustar 00root root 0000000 0000000 --- Module for handling manifest files and tables.
-- Manifest files describe the contents of a LuaRocks tree or server.
-- They are loaded into manifest tables, which are then used for
-- performing searches, matching dependencies, etc.
local manif = {}
package.loaded["luarocks.manif"] = manif
local manif_core = require("luarocks.manif_core")
local persist = require("luarocks.persist")
local fetch = require("luarocks.fetch")
local dir = require("luarocks.dir")
local fs = require("luarocks.fs")
local search = require("luarocks.search")
local util = require("luarocks.util")
local cfg = require("luarocks.cfg")
local path = require("luarocks.path")
local repos = require("luarocks.repos")
local deps = require("luarocks.deps")
manif.rock_manifest_cache = {}
--- Commit a table to disk in given local path.
-- @param where string: The directory where the table should be saved.
-- @param name string: The filename.
-- @param tbl table: The table to be saved.
-- @return boolean or (nil, string): true if successful, or nil and a
-- message in case of errors.
local function save_table(where, name, tbl)
assert(type(where) == "string")
assert(type(name) == "string")
assert(type(tbl) == "table")
local filename = dir.path(where, name)
local ok, err = persist.save_from_table(filename..".tmp", tbl)
if ok then
ok, err = fs.replace_file(filename, filename..".tmp")
end
return ok, err
end
function manif.load_rock_manifest(name, version, root)
assert(type(name) == "string")
assert(type(version) == "string")
local name_version = name.."/"..version
if manif.rock_manifest_cache[name_version] then
return manif.rock_manifest_cache[name_version].rock_manifest
end
local pathname = path.rock_manifest_file(name, version, root)
local rock_manifest = persist.load_into_table(pathname)
if not rock_manifest then return nil end
manif.rock_manifest_cache[name_version] = rock_manifest
return rock_manifest.rock_manifest
end
function manif.make_rock_manifest(name, version)
local install_dir = path.install_dir(name, version)
local tree = {}
for _, file in ipairs(fs.find(install_dir)) do
local full_path = dir.path(install_dir, file)
local walk = tree
local last
local last_name
for name in file:gmatch("[^/]+") do
local next = walk[name]
if not next then
next = {}
walk[name] = next
end
last = walk
last_name = name
walk = next
end
if fs.is_file(full_path) then
local sum, err = fs.get_md5(full_path)
if not sum then
return nil, "Failed producing checksum: "..tostring(err)
end
last[last_name] = sum
end
end
local rock_manifest = { rock_manifest=tree }
manif.rock_manifest_cache[name.."/"..version] = rock_manifest
save_table(install_dir, "rock_manifest", rock_manifest )
end
local function fetch_manifest_from(repo_url, filename)
local url = dir.path(repo_url, filename)
local name = repo_url:gsub("[/:]","_")
local cache_dir = dir.path(cfg.local_cache, name)
local ok = fs.make_dir(cache_dir)
if not ok then
return nil, "Failed creating temporary cache directory "..cache_dir
end
local file, err, errcode = fetch.fetch_url(url, dir.path(cache_dir, filename), true)
if not file then
return nil, "Failed fetching manifest for "..repo_url..(err and " - "..err or ""), errcode
end
return file
end
--- Load a local or remote manifest describing a repository.
-- All functions that use manifest tables assume they were obtained
-- through either this function or load_local_manifest.
-- @param repo_url string: URL or pathname for the repository.
-- @param lua_version string: Lua version in "5.x" format, defaults to installed version.
-- @return table or (nil, string, [string]): A table representing the manifest,
-- or nil followed by an error message and an optional error code.
function manif.load_manifest(repo_url, lua_version)
assert(type(repo_url) == "string")
assert(type(lua_version) == "string" or not lua_version)
lua_version = lua_version or cfg.lua_version
local cached_manifest = manif_core.get_cached_manifest(repo_url, lua_version)
if cached_manifest then
return cached_manifest
end
local filenames = {
"manifest-"..lua_version..".zip",
"manifest-"..lua_version,
"manifest",
}
local protocol, repodir = dir.split_url(repo_url)
local pathname
if protocol == "file" then
for _, filename in ipairs(filenames) do
pathname = dir.path(repodir, filename)
if fs.exists(pathname) then
break
end
end
else
local err, errcode
for _, filename in ipairs(filenames) do
pathname, err, errcode = fetch_manifest_from(repo_url, filename)
if pathname then
break
end
end
if not pathname then
return nil, err, errcode
end
end
if pathname:match(".*%.zip$") then
pathname = fs.absolute_name(pathname)
local dir = dir.dir_name(pathname)
fs.change_dir(dir)
local nozip = pathname:match("(.*)%.zip$")
fs.delete(nozip)
local ok = fs.unzip(pathname)
fs.pop_dir()
if not ok then
fs.delete(pathname)
fs.delete(pathname..".timestamp")
return nil, "Failed extracting manifest file"
end
pathname = nozip
end
return manif_core.manifest_loader(pathname, repo_url, lua_version)
end
--- Update storage table to account for items provided by a package.
-- @param storage table: a table storing items in the following format:
-- keys are item names and values are arrays of packages providing each item,
-- where a package is specified as string `name/version`.
-- @param items table: a table mapping item names to paths.
-- @param name string: package name.
-- @param version string: package version.
local function store_package_items(storage, name, version, items)
assert(type(storage) == "table")
assert(type(items) == "table")
assert(type(name) == "string")
assert(type(version) == "string")
local package_identifier = name.."/"..version
for item_name, path in pairs(items) do
if not storage[item_name] then
storage[item_name] = {}
end
table.insert(storage[item_name], package_identifier)
end
end
--- Update storage table removing items provided by a package.
-- @param storage table: a table storing items in the following format:
-- keys are item names and values are arrays of packages providing each item,
-- where a package is specified as string `name/version`.
-- @param items table: a table mapping item names to paths.
-- @param name string: package name.
-- @param version string: package version.
local function remove_package_items(storage, name, version, items)
assert(type(storage) == "table")
assert(type(items) == "table")
assert(type(name) == "string")
assert(type(version) == "string")
local package_identifier = name.."/"..version
for item_name, path in pairs(items) do
local all_identifiers = storage[item_name]
for i, identifier in ipairs(all_identifiers) do
if identifier == package_identifier then
table.remove(all_identifiers, i)
break
end
end
if #all_identifiers == 0 then
storage[item_name] = nil
end
end
end
--- Sort function for ordering rock identifiers in a manifest's
-- modules table. Rocks are ordered alphabetically by name, and then
-- by version which greater first.
-- @param a string: Version to compare.
-- @param b string: Version to compare.
-- @return boolean: The comparison result, according to the
-- rule outlined above.
local function sort_pkgs(a, b)
assert(type(a) == "string")
assert(type(b) == "string")
local na, va = a:match("(.*)/(.*)$")
local nb, vb = b:match("(.*)/(.*)$")
return (na == nb) and deps.compare_versions(va, vb) or na < nb
end
--- Sort items of a package matching table by version number (higher versions first).
-- @param tbl table: the package matching table: keys should be strings
-- and values arrays of strings with packages names in "name/version" format.
local function sort_package_matching_table(tbl)
assert(type(tbl) == "table")
if next(tbl) then
for item, pkgs in pairs(tbl) do
if #pkgs > 1 then
table.sort(pkgs, sort_pkgs)
-- Remove duplicates from the sorted array.
local prev = nil
local i = 1
while pkgs[i] do
local curr = pkgs[i]
if curr == prev then
table.remove(pkgs, i)
else
prev = curr
i = i + 1
end
end
end
end
end
end
--- Process the dependencies of a manifest table to determine its dependency
-- chains for loading modules. The manifest dependencies information is filled
-- and any dependency inconsistencies or missing dependencies are reported to
-- standard error.
-- @param manifest table: a manifest table.
-- @param deps_mode string: Dependency mode: "one" for the current default tree,
-- "all" for all trees, "order" for all trees with priority >= the current default,
-- "none" for no trees.
local function update_dependencies(manifest, deps_mode)
assert(type(manifest) == "table")
assert(type(deps_mode) == "string")
for pkg, versions in pairs(manifest.repository) do
for version, repositories in pairs(versions) do
for _, repo in ipairs(repositories) do
if repo.arch == "installed" then
repo.dependencies = {}
deps.scan_deps(repo.dependencies, manifest, pkg, version, deps_mode)
repo.dependencies[pkg] = nil
end
end
end
end
end
--- Filter manifest table by Lua version, removing rockspecs whose Lua version
-- does not match.
-- @param manifest table: a manifest table.
-- @param lua_version string or nil: filter by Lua version
-- @param repodir string: directory of repository being scanned
-- @param cache table: temporary rockspec cache table
local function filter_by_lua_version(manifest, lua_version, repodir, cache)
assert(type(manifest) == "table")
assert(type(repodir) == "string")
assert((not cache) or type(cache) == "table")
cache = cache or {}
lua_version = deps.parse_version(lua_version)
for pkg, versions in pairs(manifest.repository) do
local to_remove = {}
for version, repositories in pairs(versions) do
for _, repo in ipairs(repositories) do
if repo.arch == "rockspec" then
local pathname = dir.path(repodir, pkg.."-"..version..".rockspec")
local rockspec, err = cache[pathname]
if not rockspec then
rockspec, err = fetch.load_local_rockspec(pathname, true)
end
if rockspec then
cache[pathname] = rockspec
for _, dep in ipairs(rockspec.dependencies) do
if dep.name == "lua" then
if not deps.match_constraints(lua_version, dep.constraints) then
table.insert(to_remove, version)
end
break
end
end
else
util.printerr("Error loading rockspec for "..pkg.." "..version..": "..err)
end
end
end
end
if next(to_remove) then
for _, incompat in ipairs(to_remove) do
versions[incompat] = nil
end
if not next(versions) then
manifest.repository[pkg] = nil
end
end
end
end
--- Store search results in a manifest table.
-- @param results table: The search results as returned by search.disk_search.
-- @param manifest table: A manifest table (must contain repository, modules, commands tables).
-- It will be altered to include the search results.
-- @return boolean or (nil, string): true in case of success, or nil followed by an error message.
local function store_results(results, manifest)
assert(type(results) == "table")
assert(type(manifest) == "table")
for name, versions in pairs(results) do
local pkgtable = manifest.repository[name] or {}
for version, entries in pairs(versions) do
local versiontable = {}
for _, entry in ipairs(entries) do
local entrytable = {}
entrytable.arch = entry.arch
if entry.arch == "installed" then
local rock_manifest = manif.load_rock_manifest(name, version)
if not rock_manifest then
return nil, "rock_manifest file not found for "..name.." "..version.." - not a LuaRocks 2 tree?"
end
entrytable.modules = repos.package_modules(name, version)
store_package_items(manifest.modules, name, version, entrytable.modules)
entrytable.commands = repos.package_commands(name, version)
store_package_items(manifest.commands, name, version, entrytable.commands)
end
table.insert(versiontable, entrytable)
end
pkgtable[version] = versiontable
end
manifest.repository[name] = pkgtable
end
sort_package_matching_table(manifest.modules)
sort_package_matching_table(manifest.commands)
return true
end
--- Scan a LuaRocks repository and output a manifest file.
-- A file called 'manifest' will be written in the root of the given
-- repository directory.
-- @param repo A local repository directory.
-- @param deps_mode string: Dependency mode: "one" for the current default tree,
-- "all" for all trees, "order" for all trees with priority >= the current default,
-- "none" for the default dependency mode from the configuration.
-- @param remote boolean: 'true' if making a manifest for a rocks server.
-- @return boolean or (nil, string): True if manifest was generated,
-- or nil and an error message.
function manif.make_manifest(repo, deps_mode, remote)
assert(type(repo) == "string")
assert(type(deps_mode) == "string")
if deps_mode == "none" then deps_mode = cfg.deps_mode end
if not fs.is_dir(repo) then
return nil, "Cannot access repository at "..repo
end
local query = search.make_query("")
query.exact_name = false
query.arch = "any"
local results = search.disk_search(repo, query)
local manifest = { repository = {}, modules = {}, commands = {} }
manif_core.cache_manifest(repo, nil, manifest)
local ok, err = store_results(results, manifest)
if not ok then return nil, err end
if remote then
local cache = {}
for luaver in util.lua_versions() do
local vmanifest = { repository = {}, modules = {}, commands = {} }
local ok, err = store_results(results, vmanifest)
filter_by_lua_version(vmanifest, luaver, repo, cache)
save_table(repo, "manifest-"..luaver, vmanifest)
end
else
update_dependencies(manifest, deps_mode)
end
return save_table(repo, "manifest", manifest)
end
--- Update manifest file for a local repository
-- adding information about a version of a package installed in that repository.
-- @param name string: Name of a package from the repository.
-- @param version string: Version of a package from the repository.
-- @param repo string or nil: Pathname of a local repository. If not given,
-- the default local repository is used.
-- @param deps_mode string: Dependency mode: "one" for the current default tree,
-- "all" for all trees, "order" for all trees with priority >= the current default,
-- "none" for using the default dependency mode from the configuration.
-- @return boolean or (nil, string): True if manifest was updated successfully,
-- or nil and an error message.
function manif.add_to_manifest(name, version, repo, deps_mode)
assert(type(name) == "string")
assert(type(version) == "string")
local rocks_dir = path.rocks_dir(repo or cfg.root_dir)
assert(type(deps_mode) == "string")
if deps_mode == "none" then deps_mode = cfg.deps_mode end
local manifest, err = manif_core.load_local_manifest(rocks_dir)
if not manifest then
util.printerr("No existing manifest. Attempting to rebuild...")
-- Manifest built by `manif.make_manifest` should already
-- include information about given name and version,
-- no need to update it.
return manif.make_manifest(rocks_dir, deps_mode)
end
local results = {[name] = {[version] = {{arch = "installed", repo = rocks_dir}}}}
local ok, err = store_results(results, manifest)
if not ok then return nil, err end
update_dependencies(manifest, deps_mode)
return save_table(rocks_dir, "manifest", manifest)
end
--- Update manifest file for a local repository
-- removing information about a version of a package.
-- @param name string: Name of a package removed from the repository.
-- @param version string: Version of a package removed from the repository.
-- @param repo string or nil: Pathname of a local repository. If not given,
-- the default local repository is used.
-- @param deps_mode string: Dependency mode: "one" for the current default tree,
-- "all" for all trees, "order" for all trees with priority >= the current default,
-- "none" for using the default dependency mode from the configuration.
-- @return boolean or (nil, string): True if manifest was updated successfully,
-- or nil and an error message.
function manif.remove_from_manifest(name, version, repo, deps_mode)
assert(type(name) == "string")
assert(type(version) == "string")
local rocks_dir = path.rocks_dir(repo or cfg.root_dir)
assert(type(deps_mode) == "string")
if deps_mode == "none" then deps_mode = cfg.deps_mode end
local manifest, err = manif_core.load_local_manifest(rocks_dir)
if not manifest then
util.printerr("No existing manifest. Attempting to rebuild...")
-- Manifest built by `manif.make_manifest` should already
-- include up-to-date information, no need to update it.
return manif.make_manifest(rocks_dir, deps_mode)
end
local package_entry = manifest.repository[name]
local version_entry = package_entry[version][1]
remove_package_items(manifest.modules, name, version, version_entry.modules)
remove_package_items(manifest.commands, name, version, version_entry.commands)
package_entry[version] = nil
manifest.dependencies[name][version] = nil
if not next(package_entry) then
-- No more versions of this package.
manifest.repository[name] = nil
manifest.dependencies[name] = nil
end
update_dependencies(manifest, deps_mode)
return save_table(rocks_dir, "manifest", manifest)
end
--- Report missing dependencies for all rocks installed in a repository.
-- @param repo string or nil: Pathname of a local repository. If not given,
-- the default local repository is used.
-- @param deps_mode string: Dependency mode: "one" for the current default tree,
-- "all" for all trees, "order" for all trees with priority >= the current default,
-- "none" for using the default dependency mode from the configuration.
function manif.check_dependencies(repo, deps_mode)
local rocks_dir = path.rocks_dir(repo or cfg.root_dir)
assert(type(deps_mode) == "string")
if deps_mode == "none" then deps_mode = cfg.deps_mode end
local manifest = manif_core.load_local_manifest(rocks_dir)
if not manifest then
return
end
for name, versions in util.sortedpairs(manifest.repository) do
for version, version_entries in util.sortedpairs(versions, deps.compare_versions) do
for _, entry in ipairs(version_entries) do
if entry.arch == "installed" then
if manifest.dependencies[name] and manifest.dependencies[name][version] then
deps.report_missing_dependencies(name, version, manifest.dependencies[name][version], deps_mode)
end
end
end
end
end
end
function manif.zip_manifests()
for ver in util.lua_versions() do
local file = "manifest-"..ver
local zip = file..".zip"
fs.delete(dir.path(fs.current_dir(), zip))
fs.zip(zip, file)
end
end
--- Get type and name of an item (a module or a command) provided by a file.
-- @param deploy_type string: rock manifest subtree the file comes from ("bin", "lua", or "lib").
-- @param file_path string: path to the file relatively to deploy_type subdirectory.
-- @return (string, string): item type ("module" or "command") and name.
function manif.get_provided_item(deploy_type, file_path)
assert(type(deploy_type) == "string")
assert(type(file_path) == "string")
local item_type = deploy_type == "bin" and "command" or "module"
local item_name = item_type == "command" and file_path or path.path_to_module(file_path)
return item_type, item_name
end
local function get_providers(item_type, item_name, repo)
assert(type(item_type) == "string")
assert(type(item_name) == "string")
local rocks_dir = path.rocks_dir(repo or cfg.root_dir)
local manifest = manif_core.load_local_manifest(rocks_dir)
return manifest and manifest[item_type .. "s"][item_name]
end
--- Given a name of a module or a command, figure out which rock name and version
-- correspond to it in the rock tree manifest.
-- @param item_type string: "module" or "command".
-- @param item_name string: module or command name.
-- @param root string or nil: A local root dir for a rocks tree. If not given, the default is used.
-- @return (string, string) or nil: name and version of the provider rock or nil if there
-- is no provider.
function manif.get_current_provider(item_type, item_name, repo)
local providers = get_providers(item_type, item_name, repo)
if providers then
return providers[1]:match("([^/]*)/([^/]*)")
end
end
function manif.get_next_provider(item_type, item_name, repo)
local providers = get_providers(item_type, item_name, repo)
if providers and providers[2] then
return providers[2]:match("([^/]*)/([^/]*)")
end
end
--- Given a name of a module or a command provided by a package, figure out
-- which file provides it.
-- @param name string: package name.
-- @param version string: package version.
-- @param item_type string: "module" or "command".
-- @param item_name string: module or command name.
-- @param root string or nil: A local root dir for a rocks tree. If not given, the default is used.
-- @return (string, string): rock manifest subtree the file comes from ("bin", "lua", or "lib")
-- and path to the providing file relatively to that subtree.
function manif.get_providing_file(name, version, item_type, item_name, repo)
local rocks_dir = path.rocks_dir(repo or cfg.root_dir)
local manifest = manif_core.load_local_manifest(rocks_dir)
local entry_table = manifest.repository[name][version][1]
local file_path = entry_table[item_type .. "s"][item_name]
if item_type == "command" then
return "bin", file_path
end
-- A module can be in "lua" or "lib". Decide based on extension first:
-- most likely Lua modules are in "lua/" and C modules are in "lib/".
if file_path:match("%." .. cfg.lua_extension .. "$") then
return "lua", file_path
elseif file_path:match("%." .. cfg.lib_extension .. "$") then
return "lib", file_path
end
-- Fallback to rock manifest scanning.
local rock_manifest = manif.load_rock_manifest(name, version)
local subtree = rock_manifest.lib
for path_part in file_path:gmatch("[^/]+") do
if type(subtree) == "table" then
subtree = subtree[path_part]
else
-- Assume it's in "lua/" if it's not in "lib/".
return "lua", file_path
end
end
return type(subtree) == "string" and "lib" or "lua", file_path
end
return manif
luarocks-2.4.2+dfsg/src/luarocks/manif_core.lua 0000664 0000000 0000000 00000010071 13030154704 0021474 0 ustar 00root root 0000000 0000000
--- Core functions for querying manifest files.
-- This module requires no specific 'fs' functionality.
local manif_core = {}
package.loaded["luarocks.manif_core"] = manif_core
local persist = require("luarocks.persist")
local type_check = require("luarocks.type_check")
local cfg = require("luarocks.cfg")
local dir = require("luarocks.dir")
local util = require("luarocks.util")
local path = require("luarocks.path")
-- Table with repository identifiers as keys and tables mapping
-- Lua versions to cached loaded manifests as values.
local manifest_cache = {}
--- Cache a loaded manifest.
-- @param repo_url string: The repository identifier.
-- @param lua_version string: Lua version in "5.x" format, defaults to installed version.
-- @param manifest table: the manifest to be cached.
function manif_core.cache_manifest(repo_url, lua_version, manifest)
lua_version = lua_version or cfg.lua_version
manifest_cache[repo_url] = manifest_cache[repo_url] or {}
manifest_cache[repo_url][lua_version] = manifest
end
--- Attempt to get cached loaded manifest.
-- @param repo_url string: The repository identifier.
-- @param lua_version string: Lua version in "5.x" format, defaults to installed version.
-- @return table or nil: loaded manifest or nil if cache is empty.
function manif_core.get_cached_manifest(repo_url, lua_version)
lua_version = lua_version or cfg.lua_version
return manifest_cache[repo_url] and manifest_cache[repo_url][lua_version]
end
--- Back-end function that actually loads the manifest
-- and stores it in the manifest cache.
-- @param file string: The local filename of the manifest file.
-- @param repo_url string: The repository identifier.
-- @param lua_version string: Lua version in "5.x" format, defaults to installed version.
-- @param quick boolean: If given, skips type checking.
-- @return table or (nil, string, string): the manifest or nil,
-- error message and error code ("open", "load", "run" or "type").
function manif_core.manifest_loader(file, repo_url, lua_version, quick)
local manifest, err, errcode = persist.load_into_table(file)
if not manifest then
return nil, "Failed loading manifest for "..repo_url..": "..err, errcode
end
local globals = err
if not quick then
local ok, err = type_check.type_check_manifest(manifest, globals)
if not ok then
return nil, "Error checking manifest: "..err, "type"
end
end
manif_core.cache_manifest(repo_url, lua_version, manifest)
return manifest
end
--- Load a local manifest describing a repository.
-- All functions that use manifest tables assume they were obtained
-- through either this function or load_manifest.
-- @param repo_url string: URL or pathname for the repository.
-- @return table or (nil, string, string): A table representing the manifest,
-- or nil followed by an error message and an error code, see manifest_loader.
function manif_core.load_local_manifest(repo_url)
assert(type(repo_url) == "string")
local cached_manifest = manif_core.get_cached_manifest(repo_url)
if cached_manifest then
return cached_manifest
end
local pathname = dir.path(repo_url, "manifest")
return manif_core.manifest_loader(pathname, repo_url, nil, true)
end
--- Get all versions of a package listed in a manifest file.
-- @param name string: a package name.
-- @param deps_mode string: "one", to use only the currently
-- configured tree; "order" to select trees based on order
-- (use the current tree and all trees below it on the list)
-- or "all", to use all trees.
-- @return table: An array of strings listing installed
-- versions of a package.
function manif_core.get_versions(name, deps_mode)
assert(type(name) == "string")
assert(type(deps_mode) == "string")
local version_set = {}
path.map_trees(deps_mode, function(tree)
local manifest = manif_core.load_local_manifest(path.rocks_dir(tree))
if manifest and manifest.repository[name] then
for version in pairs(manifest.repository[name]) do
version_set[version] = true
end
end
end)
return util.keys(version_set)
end
return manif_core
luarocks-2.4.2+dfsg/src/luarocks/new_version.lua 0000664 0000000 0000000 00000014224 13030154704 0021734 0 ustar 00root root 0000000 0000000
--- Module implementing the LuaRocks "new_version" command.
-- Utility function that writes a new rockspec, updating data from a previous one.
local new_version = {}
local util = require("luarocks.util")
local download = require("luarocks.download")
local fetch = require("luarocks.fetch")
local persist = require("luarocks.persist")
local fs = require("luarocks.fs")
local type_check = require("luarocks.type_check")
util.add_run_function(new_version)
new_version.help_summary = "Auto-write a rockspec for a new version of a rock."
new_version.help_arguments = "[--tag=] [|] [] []"
new_version.help = [[
This is a utility function that writes a new rockspec, updating data
from a previous one.
If a package name is given, it downloads the latest rockspec from the
default server. If a rockspec is given, it uses it instead. If no argument
is given, it looks for a rockspec same way 'luarocks make' does.
If the version number is not given and tag is passed using --tag,
it is used as the version, with 'v' removed from beginning.
Otherwise, it only increments the revision number of the given
(or downloaded) rockspec.
If a URL is given, it replaces the one from the old rockspec with the
given URL. If a URL is not given and a new version is given, it tries
to guess the new URL by replacing occurrences of the version number
in the URL or tag. It also tries to download the new URL to determine
the new MD5 checksum.
If a tag is given, it replaces the one from the old rockspec. If there is
an old tag but no new one passed, it is guessed in the same way URL is.
WARNING: it writes the new rockspec to the current directory,
overwriting the file if it already exists.
]]
local function try_replace(tbl, field, old, new)
if not tbl[field] then
return false
end
local old_field = tbl[field]
local new_field = tbl[field]:gsub(old, new)
if new_field ~= old_field then
util.printout("Guessing new '"..field.."' field as "..new_field)
tbl[field] = new_field
return true
end
return false
end
-- Try to download source file using URL from a rockspec.
-- If it specified MD5, update it.
-- @return (true, false) if MD5 was not specified or it stayed same,
-- (true, true) if MD5 changed, (nil, string) on error.
local function check_url_and_update_md5(out_rs)
local file, temp_dir = fetch.fetch_url_at_temp_dir(out_rs.source.url, "luarocks-new-version-"..out_rs.package)
if not file then
util.printerr("Warning: invalid URL - "..temp_dir)
return true, false
end
local inferred_dir, found_dir = fetch.find_base_dir(file, temp_dir, out_rs.source.url, out_rs.source.dir)
if not inferred_dir then
return nil, found_dir
end
if found_dir and found_dir ~= inferred_dir then
out_rs.source.dir = found_dir
end
if file then
if out_rs.source.md5 then
util.printout("File successfully downloaded. Updating MD5 checksum...")
local new_md5, err = fs.get_md5(file)
if not new_md5 then
return nil, err
end
local old_md5 = out_rs.source.md5
out_rs.source.md5 = new_md5
return true, new_md5 ~= old_md5
else
util.printout("File successfully downloaded.")
return true, false
end
end
end
local function update_source_section(out_rs, url, tag, old_ver, new_ver)
if tag then
out_rs.source.tag = tag
end
if url then
out_rs.source.url = url
return check_url_and_update_md5(out_rs)
end
if new_ver == old_ver then
return true
end
if out_rs.source.dir then
try_replace(out_rs.source, "dir", old_ver, new_ver)
end
if out_rs.source.file then
try_replace(out_rs.source, "file", old_ver, new_ver)
end
if try_replace(out_rs.source, "url", old_ver, new_ver) then
return check_url_and_update_md5(out_rs)
end
if tag or try_replace(out_rs.source, "tag", old_ver, new_ver) then
return true
end
-- Couldn't replace anything significant, use the old URL.
local ok, md5_changed = check_url_and_update_md5(out_rs)
if not ok then
return nil, md5_changed
end
if md5_changed then
util.printerr("Warning: URL is the same, but MD5 has changed. Old rockspec is broken.")
end
return true
end
function new_version.command(flags, input, version, url)
if not input then
local err
input, err = util.get_default_rockspec()
if not input then
return nil, err
end
end
assert(type(input) == "string")
local filename, err
if input:match("rockspec$") then
filename, err = fetch.fetch_url(input)
if not filename then
return nil, err
end
else
filename, err = download.download("rockspec", input:lower())
if not filename then
return nil, err
end
end
local valid_rs, err = fetch.load_rockspec(filename)
if not valid_rs then
return nil, err
end
local old_ver, old_rev = valid_rs.version:match("(.*)%-(%d+)$")
local new_ver, new_rev
if flags.tag and not version then
version = flags.tag:gsub("^v", "")
end
if version then
new_ver, new_rev = version:match("(.*)%-(%d+)$")
new_rev = tonumber(new_rev)
if not new_rev then
new_ver = version
new_rev = 1
end
else
new_ver = old_ver
new_rev = tonumber(old_rev) + 1
end
local new_rockver = new_ver:gsub("-", "")
local out_rs, err = persist.load_into_table(filename)
local out_name = out_rs.package:lower()
out_rs.version = new_rockver.."-"..new_rev
local ok, err = update_source_section(out_rs, url, flags.tag, old_ver, new_ver)
if not ok then return nil, err end
if out_rs.build and out_rs.build.type == "module" then
out_rs.build.type = "builtin"
end
local out_filename = out_name.."-"..new_rockver.."-"..new_rev..".rockspec"
persist.save_from_table(out_filename, out_rs, type_check.rockspec_order)
util.printout("Wrote "..out_filename)
local valid_out_rs, err = fetch.load_local_rockspec(out_filename)
if not valid_out_rs then
return nil, "Failed loading generated rockspec: "..err
end
return true
end
return new_version
luarocks-2.4.2+dfsg/src/luarocks/pack.lua 0000664 0000000 0000000 00000015603 13030154704 0020316 0 ustar 00root root 0000000 0000000
--- Module implementing the LuaRocks "pack" command.
-- Creates a rock, packing sources or binaries.
local pack = {}
package.loaded["luarocks.pack"] = pack
local unpack = unpack or table.unpack
local path = require("luarocks.path")
local repos = require("luarocks.repos")
local fetch = require("luarocks.fetch")
local fs = require("luarocks.fs")
local cfg = require("luarocks.cfg")
local util = require("luarocks.util")
local dir = require("luarocks.dir")
local manif = require("luarocks.manif")
local search = require("luarocks.search")
util.add_run_function(pack)
pack.help_summary = "Create a rock, packing sources or binaries."
pack.help_arguments = "{| []}"
pack.help = [[
Argument may be a rockspec file, for creating a source rock,
or the name of an installed package, for creating a binary rock.
In the latter case, the app version may be given as a second
argument.
]]
--- Create a source rock.
-- Packages a rockspec and its required source files in a rock
-- file with the .src.rock extension, which can later be built and
-- installed with the "build" command.
-- @param rockspec_file string: An URL or pathname for a rockspec file.
-- @return string or (nil, string): The filename of the resulting
-- .src.rock file; or nil and an error message.
function pack.pack_source_rock(rockspec_file)
assert(type(rockspec_file) == "string")
local rockspec, err = fetch.load_rockspec(rockspec_file)
if err then
return nil, "Error loading rockspec: "..err
end
rockspec_file = rockspec.local_filename
local name_version = rockspec.name .. "-" .. rockspec.version
local rock_file = fs.absolute_name(name_version .. ".src.rock")
local source_file, source_dir = fetch.fetch_sources(rockspec, false)
if not source_file then
return nil, source_dir
end
local ok, err = fs.change_dir(source_dir)
if not ok then return nil, err end
fs.delete(rock_file)
fs.copy(rockspec_file, source_dir, cfg.perm_read)
if not fs.zip(rock_file, dir.base_name(rockspec_file), dir.base_name(source_file)) then
return nil, "Failed packing "..rock_file
end
fs.pop_dir()
return rock_file
end
local function copy_back_files(name, version, file_tree, deploy_dir, pack_dir, perms)
local ok, err = fs.make_dir(pack_dir)
if not ok then return nil, err end
for file, sub in pairs(file_tree) do
local source = dir.path(deploy_dir, file)
local target = dir.path(pack_dir, file)
if type(sub) == "table" then
local ok, err = copy_back_files(name, version, sub, source, target)
if not ok then return nil, err end
else
local versioned = path.versioned_name(source, deploy_dir, name, version)
if fs.exists(versioned) then
fs.copy(versioned, target, perms)
else
fs.copy(source, target, perms)
end
end
end
return true
end
-- @param name string: Name of package to pack.
-- @param version string or nil: A version number may also be passed.
-- @param tree string or nil: An optional tree to pick the package from.
-- @return string or (nil, string): The filename of the resulting
-- .src.rock file; or nil and an error message.
local function do_pack_binary_rock(name, version, tree)
assert(type(name) == "string")
assert(type(version) == "string" or not version)
local repo, repo_url
name, version, repo, repo_url = search.pick_installed_rock(name, version, tree)
if not name then
return nil, version
end
local root = path.root_dir(repo_url)
local prefix = path.install_dir(name, version, root)
if not fs.exists(prefix) then
return nil, "'"..name.." "..version.."' does not seem to be an installed rock."
end
local rock_manifest = manif.load_rock_manifest(name, version, root)
if not rock_manifest then
return nil, "rock_manifest file not found for "..name.." "..version.." - not a LuaRocks 2 tree?"
end
local name_version = name .. "-" .. version
local rock_file = fs.absolute_name(name_version .. "."..cfg.arch..".rock")
local temp_dir = fs.make_temp_dir("pack")
fs.copy_contents(prefix, temp_dir)
local is_binary = false
if rock_manifest.lib then
local ok, err = copy_back_files(name, version, rock_manifest.lib, path.deploy_lib_dir(root), dir.path(temp_dir, "lib"), cfg.perm_exec)
if not ok then return nil, "Failed copying back files: " .. err end
is_binary = true
end
if rock_manifest.lua then
local ok, err = copy_back_files(name, version, rock_manifest.lua, path.deploy_lua_dir(root), dir.path(temp_dir, "lua"), cfg.perm_read)
if not ok then return nil, "Failed copying back files: " .. err end
end
local ok, err = fs.change_dir(temp_dir)
if not ok then return nil, err end
if not is_binary and not repos.has_binaries(name, version) then
rock_file = rock_file:gsub("%."..cfg.arch:gsub("%-","%%-").."%.", ".all.")
end
fs.delete(rock_file)
if not fs.zip(rock_file, unpack(fs.list_dir())) then
return nil, "Failed packing "..rock_file
end
fs.pop_dir()
fs.delete(temp_dir)
return rock_file
end
function pack.pack_binary_rock(name, version, cmd, ...)
-- The --pack-binary-rock option for "luarocks build" basically performs
-- "luarocks build" on a temporary tree and then "luarocks pack". The
-- alternative would require refactoring parts of luarocks.build and
-- luarocks.pack, which would save a few file operations: the idea would be
-- to shave off the final deploy steps from the build phase and the initial
-- collect steps from the pack phase.
local temp_dir, err = fs.make_temp_dir("luarocks-build-pack-"..dir.base_name(name))
if not temp_dir then
return nil, "Failed creating temporary directory: "..err
end
util.schedule_function(fs.delete, temp_dir)
path.use_tree(temp_dir)
local ok, err = cmd(...)
if not ok then
return nil, err
end
local rname, rversion = path.parse_name(name)
if not rname then
rname, rversion = name, version
end
return do_pack_binary_rock(rname, rversion, temp_dir)
end
--- Driver function for the "pack" command.
-- @param arg string: may be a rockspec file, for creating a source rock,
-- or the name of an installed package, for creating a binary rock.
-- @param version string or nil: if the name of a package is given, a
-- version may also be passed.
-- @return boolean or (nil, string): true if successful or nil followed
-- by an error message.
function pack.command(flags, arg, version)
assert(type(version) == "string" or not version)
if type(arg) ~= "string" then
return nil, "Argument missing. "..util.see_help("pack")
end
local file, err
if arg:match(".*%.rockspec") then
file, err = pack.pack_source_rock(arg)
else
file, err = do_pack_binary_rock(arg:lower(), version, flags["tree"])
end
if err then
return nil, err
else
util.printout("Packed: "..file)
return true
end
end
return pack
luarocks-2.4.2+dfsg/src/luarocks/path.lua 0000664 0000000 0000000 00000035224 13030154704 0020335 0 ustar 00root root 0000000 0000000
--- LuaRocks-specific path handling functions.
-- All paths are configured in this module, making it a single
-- point where the layout of the local installation is defined in LuaRocks.
local path = {}
local dir = require("luarocks.dir")
local cfg = require("luarocks.cfg")
local util = require("luarocks.util")
--- Infer rockspec filename from a rock filename.
-- @param rock_name string: Pathname of a rock file.
-- @return string: Filename of the rockspec, without path.
function path.rockspec_name_from_rock(rock_name)
assert(type(rock_name) == "string")
local base_name = dir.base_name(rock_name)
return base_name:match("(.*)%.[^.]*.rock") .. ".rockspec"
end
function path.rocks_dir(tree)
if type(tree) == "string" then
return dir.path(tree, cfg.rocks_subdir)
else
assert(type(tree) == "table")
return tree.rocks_dir or dir.path(tree.root, cfg.rocks_subdir)
end
end
function path.root_dir(rocks_dir)
assert(type(rocks_dir) == "string")
return rocks_dir:match("(.*)" .. util.matchquote(cfg.rocks_subdir) .. ".*$")
end
function path.rocks_tree_to_string(tree)
if type(tree) == "string" then
return tree
else
assert(type(tree) == "table")
return tree.root
end
end
function path.deploy_bin_dir(tree)
if type(tree) == "string" then
return dir.path(tree, "bin")
else
assert(type(tree) == "table")
return tree.bin_dir or dir.path(tree.root, "bin")
end
end
function path.deploy_lua_dir(tree)
if type(tree) == "string" then
return dir.path(tree, cfg.lua_modules_path)
else
assert(type(tree) == "table")
return tree.lua_dir or dir.path(tree.root, cfg.lua_modules_path)
end
end
function path.deploy_lib_dir(tree)
if type(tree) == "string" then
return dir.path(tree, cfg.lib_modules_path)
else
assert(type(tree) == "table")
return tree.lib_dir or dir.path(tree.root, cfg.lib_modules_path)
end
end
function path.manifest_file(tree)
if type(tree) == "string" then
return dir.path(tree, cfg.rocks_subdir, "manifest")
else
assert(type(tree) == "table")
return (tree.rocks_dir and dir.path(tree.rocks_dir, "manifest")) or dir.path(tree.root, cfg.rocks_subdir, "manifest")
end
end
--- Get the directory for all versions of a package in a tree.
-- @param name string: The package name.
-- @return string: The resulting path -- does not guarantee that
-- @param tree string or nil: If given, specifies the local tree to use.
-- the package (and by extension, the path) exists.
function path.versions_dir(name, tree)
assert(type(name) == "string")
tree = tree or cfg.root_dir
return dir.path(path.rocks_dir(tree), name)
end
--- Get the local installation directory (prefix) for a package.
-- @param name string: The package name.
-- @param version string: The package version.
-- @param tree string or nil: If given, specifies the local tree to use.
-- @return string: The resulting path -- does not guarantee that
-- the package (and by extension, the path) exists.
function path.install_dir(name, version, tree)
assert(type(name) == "string")
assert(type(version) == "string")
tree = tree or cfg.root_dir
return dir.path(path.rocks_dir(tree), name, version)
end
--- Get the local filename of the rockspec of an installed rock.
-- @param name string: The package name.
-- @param version string: The package version.
-- @param tree string or nil: If given, specifies the local tree to use.
-- @return string: The resulting path -- does not guarantee that
-- the package (and by extension, the file) exists.
function path.rockspec_file(name, version, tree)
assert(type(name) == "string")
assert(type(version) == "string")
tree = tree or cfg.root_dir
return dir.path(path.rocks_dir(tree), name, version, name.."-"..version..".rockspec")
end
--- Get the local filename of the rock_manifest file of an installed rock.
-- @param name string: The package name.
-- @param version string: The package version.
-- @param tree string or nil: If given, specifies the local tree to use.
-- @return string: The resulting path -- does not guarantee that
-- the package (and by extension, the file) exists.
function path.rock_manifest_file(name, version, tree)
assert(type(name) == "string")
assert(type(version) == "string")
tree = tree or cfg.root_dir
return dir.path(path.rocks_dir(tree), name, version, "rock_manifest")
end
--- Get the local installation directory for C libraries of a package.
-- @param name string: The package name.
-- @param version string: The package version.
-- @param tree string or nil: If given, specifies the local tree to use.
-- @return string: The resulting path -- does not guarantee that
-- the package (and by extension, the path) exists.
function path.lib_dir(name, version, tree)
assert(type(name) == "string")
assert(type(version) == "string")
tree = tree or cfg.root_dir
return dir.path(path.rocks_dir(tree), name, version, "lib")
end
--- Get the local installation directory for Lua modules of a package.
-- @param name string: The package name.
-- @param version string: The package version.
-- @param tree string or nil: If given, specifies the local tree to use.
-- @return string: The resulting path -- does not guarantee that
-- the package (and by extension, the path) exists.
function path.lua_dir(name, version, tree)
assert(type(name) == "string")
assert(type(version) == "string")
tree = tree or cfg.root_dir
return dir.path(path.rocks_dir(tree), name, version, "lua")
end
--- Get the local installation directory for documentation of a package.
-- @param name string: The package name.
-- @param version string: The package version.
-- @param tree string or nil: If given, specifies the local tree to use.
-- @return string: The resulting path -- does not guarantee that
-- the package (and by extension, the path) exists.
function path.doc_dir(name, version, tree)
assert(type(name) == "string")
assert(type(version) == "string")
tree = tree or cfg.root_dir
return dir.path(path.rocks_dir(tree), name, version, "doc")
end
--- Get the local installation directory for configuration files of a package.
-- @param name string: The package name.
-- @param version string: The package version.
-- @param tree string or nil: If given, specifies the local tree to use.
-- @return string: The resulting path -- does not guarantee that
-- the package (and by extension, the path) exists.
function path.conf_dir(name, version, tree)
assert(type(name) == "string")
assert(type(version) == "string")
tree = tree or cfg.root_dir
return dir.path(path.rocks_dir(tree), name, version, "conf")
end
--- Get the local installation directory for command-line scripts
-- of a package.
-- @param name string: The package name.
-- @param version string: The package version.
-- @param tree string or nil: If given, specifies the local tree to use.
-- @return string: The resulting path -- does not guarantee that
-- the package (and by extension, the path) exists.
function path.bin_dir(name, version, tree)
assert(type(name) == "string")
assert(type(version) == "string")
tree = tree or cfg.root_dir
return dir.path(path.rocks_dir(tree), name, version, "bin")
end
--- Extract name, version and arch of a rock filename,
-- or name, version and "rockspec" from a rockspec name.
-- @param file_name string: pathname of a rock or rockspec
-- @return (string, string, string) or nil: name, version and arch
-- or nil if name could not be parsed
function path.parse_name(file_name)
assert(type(file_name) == "string")
if file_name:match("%.rock$") then
return dir.base_name(file_name):match("(.*)-([^-]+-%d+)%.([^.]+)%.rock$")
else
return dir.base_name(file_name):match("(.*)-([^-]+-%d+)%.(rockspec)")
end
end
--- Make a rockspec or rock URL.
-- @param pathname string: Base URL or pathname.
-- @param name string: Package name.
-- @param version string: Package version.
-- @param arch string: Architecture identifier, or "rockspec" or "installed".
-- @return string: A URL or pathname following LuaRocks naming conventions.
function path.make_url(pathname, name, version, arch)
assert(type(pathname) == "string")
assert(type(name) == "string")
assert(type(version) == "string")
assert(type(arch) == "string")
local filename = name.."-"..version
if arch == "installed" then
filename = dir.path(name, version, filename..".rockspec")
elseif arch == "rockspec" then
filename = filename..".rockspec"
else
filename = filename.."."..arch..".rock"
end
return dir.path(pathname, filename)
end
--- Convert a pathname to a module identifier.
-- In Unix, for example, a path "foo/bar/baz.lua" is converted to
-- "foo.bar.baz"; "bla/init.lua" returns "bla"; "foo.so" returns "foo".
-- @param file string: Pathname of module
-- @return string: The module identifier, or nil if given path is
-- not a conformant module path (the function does not check if the
-- path actually exists).
function path.path_to_module(file)
assert(type(file) == "string")
local name = file:match("(.*)%."..cfg.lua_extension.."$")
if name then
name = name:gsub(dir.separator, ".")
local init = name:match("(.*)%.init$")
if init then
name = init
end
else
name = file:match("(.*)%."..cfg.lib_extension.."$")
if name then
name = name:gsub(dir.separator, ".")
end
end
if not name then name = file end
name = name:gsub("^%.+", ""):gsub("%.+$", "")
return name
end
--- Obtain the directory name where a module should be stored.
-- For example, on Unix, "foo.bar.baz" will return "foo/bar".
-- @param mod string: A module name in Lua dot-separated format.
-- @return string: A directory name using the platform's separator.
function path.module_to_path(mod)
assert(type(mod) == "string")
return (mod:gsub("[^.]*$", ""):gsub("%.", dir.separator))
end
--- Set up path-related variables for a given rock.
-- Create a "variables" table in the rockspec table, containing
-- adjusted variables according to the configuration file.
-- @param rockspec table: The rockspec table.
function path.configure_paths(rockspec)
assert(type(rockspec) == "table")
local vars = {}
for k,v in pairs(cfg.variables) do
vars[k] = v
end
local name, version = rockspec.name, rockspec.version
vars.PREFIX = path.install_dir(name, version)
vars.LUADIR = path.lua_dir(name, version)
vars.LIBDIR = path.lib_dir(name, version)
vars.CONFDIR = path.conf_dir(name, version)
vars.BINDIR = path.bin_dir(name, version)
vars.DOCDIR = path.doc_dir(name, version)
rockspec.variables = vars
end
--- Produce a versioned version of a filename.
-- @param file string: filename (must start with prefix)
-- @param prefix string: Path prefix for file
-- @param name string: Rock name
-- @param version string: Rock version
-- @return string: a pathname with the same directory parts and a versioned basename.
function path.versioned_name(file, prefix, name, version)
assert(type(file) == "string")
assert(type(name) == "string")
assert(type(version) == "string")
local rest = file:sub(#prefix+1):gsub("^/*", "")
local name_version = (name.."_"..version):gsub("%-", "_"):gsub("%.", "_")
return dir.path(prefix, name_version.."-"..rest)
end
function path.use_tree(tree)
cfg.root_dir = tree
cfg.rocks_dir = path.rocks_dir(tree)
cfg.deploy_bin_dir = path.deploy_bin_dir(tree)
cfg.deploy_lua_dir = path.deploy_lua_dir(tree)
cfg.deploy_lib_dir = path.deploy_lib_dir(tree)
end
--- Apply a given function to the active rocks trees based on chosen dependency mode.
-- @param deps_mode string: Dependency mode: "one" for the current default tree,
-- "all" for all trees, "order" for all trees with priority >= the current default,
-- "none" for no trees (this function becomes a nop).
-- @param fn function: function to be applied, with the tree dir (string) as the first
-- argument and the remaining varargs of map_trees as the following arguments.
-- @return a table with all results of invocations of fn collected.
function path.map_trees(deps_mode, fn, ...)
local result = {}
if deps_mode == "one" then
table.insert(result, (fn(cfg.root_dir, ...)) or 0)
elseif deps_mode == "all" or deps_mode == "order" then
local use = false
if deps_mode == "all" then
use = true
end
for _, tree in ipairs(cfg.rocks_trees) do
if dir.normalize(path.rocks_tree_to_string(tree)) == dir.normalize(path.rocks_tree_to_string(cfg.root_dir)) then
use = true
end
if use then
table.insert(result, (fn(tree, ...)) or 0)
end
end
end
return result
end
local is_src_extension = { [".lua"] = true, [".tl"] = true, [".tld"] = true, [".moon"] = true }
--- Return the pathname of the file that would be loaded for a module, indexed.
-- @param file_name string: module file name as in manifest (eg. "socket/core.so")
-- @param name string: name of the package (eg. "luasocket")
-- @param version string: version number (eg. "2.0.2-1")
-- @param tree string: repository path (eg. "/usr/local")
-- @param i number: the index, 1 if version is the current default, > 1 otherwise.
-- This is done this way for use by select_module in luarocks.loader.
-- @return string: filename of the module (eg. "/usr/local/lib/lua/5.1/socket/core.so")
function path.which_i(file_name, name, version, tree, i)
local deploy_dir
local extension = file_name:match("%.[a-z]+$")
if is_src_extension[extension] then
deploy_dir = path.deploy_lua_dir(tree)
file_name = dir.path(deploy_dir, file_name)
else
deploy_dir = path.deploy_lib_dir(tree)
file_name = dir.path(deploy_dir, file_name)
end
if i > 1 then
file_name = path.versioned_name(file_name, deploy_dir, name, version)
end
return file_name
end
--- Return the pathname of the file that would be loaded for a module,
-- returning the versioned pathname if given version is not the default version
-- in the given manifest.
-- @param module_name string: module name (eg. "socket.core")
-- @param file_name string: module file name as in manifest (eg. "socket/core.so")
-- @param name string: name of the package (eg. "luasocket")
-- @param version string: version number (eg. "2.0.2-1")
-- @param tree string: repository path (eg. "/usr/local")
-- @param manifest table: the manifest table for the tree.
-- @return string: filename of the module (eg. "/usr/local/lib/lua/5.1/socket/core.so")
function path.which(module_name, file_name, name, version, tree, manifest)
local versions = manifest.modules[module_name]
assert(versions)
for i, name_version in ipairs(versions) do
if name_version == name.."/"..version then
return path.which_i(file_name, name, version, tree, i):gsub("//", "/")
end
end
assert(false)
end
return path
luarocks-2.4.2+dfsg/src/luarocks/path_cmd.lua 0000664 0000000 0000000 00000004334 13030154704 0021156 0 ustar 00root root 0000000 0000000
--- @module luarocks.path_cmd
-- Driver for the `luarocks path` command.
local path_cmd = {}
local util = require("luarocks.util")
local cfg = require("luarocks.cfg")
util.add_run_function(path_cmd)
path_cmd.help_summary = "Return the currently configured package path."
path_cmd.help_arguments = ""
path_cmd.help = [[
Returns the package path currently configured for this installation
of LuaRocks, formatted as shell commands to update LUA_PATH and LUA_CPATH.
--bin Adds the system path to the output
--append Appends the paths to the existing paths. Default is to prefix
the LR paths to the existing paths.
--lr-path Exports the Lua path (not formatted as shell command)
--lr-cpath Exports the Lua cpath (not formatted as shell command)
--lr-bin Exports the system path (not formatted as shell command)
On Unix systems, you may run:
eval `luarocks path`
And on Windows:
luarocks path > "%temp%\_lrp.bat" && call "%temp%\_lrp.bat" && del "%temp%\_lrp.bat"
]]
--- Driver function for "path" command.
-- @return boolean This function always succeeds.
function path_cmd.command(flags)
local lr_path, lr_cpath, lr_bin = cfg.package_paths(flags["tree"])
local path_sep = cfg.export_path_separator
if flags["lr-path"] then
util.printout(util.remove_path_dupes(lr_path, ';'))
return true
elseif flags["lr-cpath"] then
util.printout(util.remove_path_dupes(lr_cpath, ';'))
return true
elseif flags["lr-bin"] then
util.printout(util.remove_path_dupes(lr_bin, path_sep))
return true
end
if flags["append"] then
lr_path = package.path .. ";" .. lr_path
lr_cpath = package.cpath .. ";" .. lr_cpath
lr_bin = os.getenv("PATH") .. path_sep .. lr_bin
else
lr_path = lr_path.. ";" .. package.path
lr_cpath = lr_cpath .. ";" .. package.cpath
lr_bin = lr_bin .. path_sep .. os.getenv("PATH")
end
util.printout(cfg.export_lua_path:format(util.remove_path_dupes(lr_path, ';')))
util.printout(cfg.export_lua_cpath:format(util.remove_path_dupes(lr_cpath, ';')))
if flags["bin"] then
util.printout(cfg.export_path:format(util.remove_path_dupes(lr_bin, path_sep)))
end
return true
end
return path_cmd
luarocks-2.4.2+dfsg/src/luarocks/persist.lua 0000664 0000000 0000000 00000015343 13030154704 0021072 0 ustar 00root root 0000000 0000000
--- Utility module for loading files into tables and
-- saving tables into files.
-- Implemented separately to avoid interdependencies,
-- as it is used in the bootstrapping stage of the cfg module.
local persist = {}
package.loaded["luarocks.persist"] = persist
local util = require("luarocks.util")
--- Load and run a Lua file in an environment.
-- @param filename string: the name of the file.
-- @param env table: the environment table.
-- @return (true, any) or (nil, string, string): true and the return value
-- of the file, or nil, an error message and an error code ("open", "load"
-- or "run") in case of errors.
local function run_file(filename, env)
local fd, err = io.open(filename)
if not fd then
return nil, err, "open"
end
local str, err = fd:read("*a")
fd:close()
if not str then
return nil, err, "open"
end
str = str:gsub("^#![^\n]*\n", "")
local chunk, ran
if _VERSION == "Lua 5.1" then -- Lua 5.1
chunk, err = loadstring(str, filename)
if chunk then
setfenv(chunk, env)
ran, err = pcall(chunk)
end
else -- Lua 5.2
chunk, err = load(str, filename, "t", env)
if chunk then
ran, err = pcall(chunk)
end
end
if not chunk then
return nil, "Error loading file: "..err, "load"
end
if not ran then
return nil, "Error running file: "..err, "run"
end
return true, err
end
--- Load a Lua file containing assignments, storing them in a table.
-- The global environment is not propagated to the loaded file.
-- @param filename string: the name of the file.
-- @param tbl table or nil: if given, this table is used to store
-- loaded values.
-- @return (table, table) or (nil, string, string): a table with the file's assignments
-- as fields and set of undefined globals accessed in file,
-- or nil, an error message and an error code ("open"; couldn't open the file,
-- "load"; compile-time error, or "run"; run-time error)
-- in case of errors.
function persist.load_into_table(filename, tbl)
assert(type(filename) == "string")
assert(type(tbl) == "table" or not tbl)
local result = tbl or {}
local globals = {}
local globals_mt = {
__index = function(t, k)
globals[k] = true
end
}
local save_mt = getmetatable(result)
setmetatable(result, globals_mt)
local ok, err, errcode = run_file(filename, result)
setmetatable(result, save_mt)
if not ok then
return nil, err, errcode
end
return result, globals
end
local write_table
--- Write a value as Lua code.
-- This function handles only numbers and strings, invoking write_table
-- to write tables.
-- @param out table or userdata: a writer object supporting :write() method.
-- @param v: the value to be written.
-- @param level number: the indentation level
-- @param sub_order table: optional prioritization table
-- @see write_table
local function write_value(out, v, level, sub_order)
if type(v) == "table" then
write_table(out, v, level + 1, sub_order)
elseif type(v) == "string" then
if v:match("[\r\n]") then
local open, close = "[[", "]]"
local equals = 0
local v_with_bracket = v.."]"
while v_with_bracket:find(close, 1, true) do
equals = equals + 1
local eqs = ("="):rep(equals)
open, close = "["..eqs.."[", "]"..eqs.."]"
end
out:write(open.."\n"..v..close)
else
out:write(("%q"):format(v))
end
else
out:write(tostring(v))
end
end
--- Write a table as Lua code in curly brackets notation to a writer object.
-- Only numbers, strings and tables (containing numbers, strings
-- or other recursively processed tables) are supported.
-- @param out table or userdata: a writer object supporting :write() method.
-- @param tbl table: the table to be written.
-- @param level number: the indentation level
-- @param field_order table: optional prioritization table
write_table = function(out, tbl, level, field_order)
out:write("{")
local sep = "\n"
local indentation = " "
local indent = true
local i = 1
for k, v, sub_order in util.sortedpairs(tbl, field_order) do
out:write(sep)
if indent then
for n = 1,level do out:write(indentation) end
end
if k == i then
i = i + 1
else
if type(k) == "string" and k:match("^[a-zA-Z_][a-zA-Z0-9_]*$") then
out:write(k)
else
out:write("[")
write_value(out, k, level)
out:write("]")
end
out:write(" = ")
end
write_value(out, v, level, sub_order)
if type(v) == "number" then
sep = ", "
indent = false
else
sep = ",\n"
indent = true
end
end
if sep ~= "\n" then
out:write("\n")
for n = 1,level-1 do out:write(indentation) end
end
out:write("}")
end
--- Write a table as series of assignments to a writer object.
-- @param out table or userdata: a writer object supporting :write() method.
-- @param tbl table: the table to be written.
-- @param field_order table: optional prioritization table
local function write_table_as_assignments(out, tbl, field_order)
for k, v, sub_order in util.sortedpairs(tbl, field_order) do
out:write(k.." = ")
write_value(out, v, 0, sub_order)
out:write("\n")
end
end
--- Save the contents of a table to a string.
-- Each element of the table is saved as a global assignment.
-- Only numbers, strings and tables (containing numbers, strings
-- or other recursively processed tables) are supported.
-- @param tbl table: the table containing the data to be written
-- @param field_order table: an optional array indicating the order of top-level fields.
-- @return string
function persist.save_from_table_to_string(tbl, field_order)
local out = {buffer = {}}
function out:write(data) table.insert(self.buffer, data) end
write_table_as_assignments(out, tbl, field_order)
return table.concat(out.buffer)
end
--- Save the contents of a table in a file.
-- Each element of the table is saved as a global assignment.
-- Only numbers, strings and tables (containing numbers, strings
-- or other recursively processed tables) are supported.
-- @param filename string: the output filename
-- @param tbl table: the table containing the data to be written
-- @param field_order table: an optional array indicating the order of top-level fields.
-- @return boolean or (nil, string): true if successful, or nil and a
-- message in case of errors.
function persist.save_from_table(filename, tbl, field_order)
local out = io.open(filename, "w")
if not out then
return nil, "Cannot create file at "..filename
end
write_table_as_assignments(out, tbl, field_order)
out:close()
return true
end
return persist
luarocks-2.4.2+dfsg/src/luarocks/purge.lua 0000664 0000000 0000000 00000005066 13030154704 0020524 0 ustar 00root root 0000000 0000000
--- Module implementing the LuaRocks "purge" command.
-- Remove all rocks from a given tree.
local purge = {}
package.loaded["luarocks.purge"] = purge
local util = require("luarocks.util")
local fs = require("luarocks.fs")
local path = require("luarocks.path")
local search = require("luarocks.search")
local deps = require("luarocks.deps")
local repos = require("luarocks.repos")
local manif = require("luarocks.manif")
local cfg = require("luarocks.cfg")
local remove = require("luarocks.remove")
util.add_run_function(purge)
purge.help_summary = "Remove all installed rocks from a tree."
purge.help_arguments = "--tree= [--old-versions]"
purge.help = [[
This command removes rocks en masse from a given tree.
By default, it removes all rocks from a tree.
The --tree argument is mandatory: luarocks purge does not
assume a default tree.
--old-versions Keep the highest-numbered version of each
rock and remove the other ones. By default
it only removes old versions if they are
not needed as dependencies. This can be
overridden with the flag --force.
]]
function purge.command(flags)
local tree = flags["tree"]
if type(tree) ~= "string" then
return nil, "The --tree argument is mandatory. "..util.see_help("purge")
end
local results = {}
local query = search.make_query("")
query.exact_name = false
if not fs.is_dir(tree) then
return nil, "Directory not found: "..tree
end
local ok, err = fs.check_command_permissions(flags)
if not ok then return nil, err, cfg.errorcodes.PERMISSIONDENIED end
search.manifest_search(results, path.rocks_dir(tree), query)
local sort = function(a,b) return deps.compare_versions(b,a) end
if flags["old-versions"] then
sort = deps.compare_versions
end
for package, versions in util.sortedpairs(results) do
for version, repositories in util.sortedpairs(versions, sort) do
if flags["old-versions"] then
util.printout("Keeping "..package.." "..version.."...")
local ok, err = remove.remove_other_versions(package, version, flags["force"], flags["force-fast"])
if not ok then
util.printerr(err)
end
break
else
util.printout("Removing "..package.." "..version.."...")
local ok, err = repos.delete_version(package, version, "none", true)
if not ok then
util.printerr(err)
end
end
end
end
return manif.make_manifest(cfg.rocks_dir, "one")
end
return purge
luarocks-2.4.2+dfsg/src/luarocks/refresh_cache.lua 0000664 0000000 0000000 00000002045 13030154704 0022155 0 ustar 00root root 0000000 0000000
--- Module implementing the luarocks-admin "refresh_cache" command.
local refresh_cache = {}
package.loaded["luarocks.refresh_cache"] = refresh_cache
local util = require("luarocks.util")
local cfg = require("luarocks.cfg")
local cache = require("luarocks.cache")
util.add_run_function(refresh_cache)
refresh_cache.help_summary = "Refresh local cache of a remote rocks server."
refresh_cache.help_arguments = "[--from=]"
refresh_cache.help = [[
The flag --from indicates which server to use.
If not given, the default server set in the upload_server variable
from the configuration file is used instead.
]]
function refresh_cache.command(flags)
local server, upload_server = cache.get_upload_server(flags["server"])
if not server then return nil, upload_server end
local download_url = cache.get_server_urls(server, upload_server)
local ok, err = cache.refresh_local_cache(server, download_url, cfg.upload_user, cfg.upload_password)
if not ok then
return nil, err
else
return true
end
end
return refresh_cache
luarocks-2.4.2+dfsg/src/luarocks/remove.lua 0000664 0000000 0000000 00000014702 13030154704 0020674 0 ustar 00root root 0000000 0000000
--- Module implementing the LuaRocks "remove" command.
-- Uninstalls rocks.
local remove = {}
package.loaded["luarocks.remove"] = remove
local search = require("luarocks.search")
local deps = require("luarocks.deps")
local fetch = require("luarocks.fetch")
local repos = require("luarocks.repos")
local path = require("luarocks.path")
local util = require("luarocks.util")
local cfg = require("luarocks.cfg")
local fs = require("luarocks.fs")
local manif = require("luarocks.manif")
util.add_run_function(remove)
remove.help_summary = "Uninstall a rock."
remove.help_arguments = "[--force|--force-fast] []"
remove.help = [[
Argument is the name of a rock to be uninstalled.
If a version is not given, try to remove all versions at once.
Will only perform the removal if it does not break dependencies.
To override this check and force the removal, use --force.
To perform a forced removal without reporting dependency issues,
use --force-fast.
]]..util.deps_mode_help()
--- Obtain a list of packages that depend on the given set of packages
-- (where all packages of the set are versions of one program).
-- @param name string: the name of a program
-- @param versions array of string: the versions to be deleted.
-- @return array of string: an empty table if no packages depend on any
-- of the given list, or an array of strings in "name/version" format.
local function check_dependents(name, versions, deps_mode)
local dependents = {}
local blacklist = {}
blacklist[name] = {}
for version, _ in pairs(versions) do
blacklist[name][version] = true
end
local local_rocks = {}
local query_all = search.make_query("")
query_all.exact_name = false
search.manifest_search(local_rocks, cfg.rocks_dir, query_all)
local_rocks[name] = nil
for rock_name, rock_versions in pairs(local_rocks) do
for rock_version, _ in pairs(rock_versions) do
local rockspec, err = fetch.load_rockspec(path.rockspec_file(rock_name, rock_version))
if rockspec then
local _, missing = deps.match_deps(rockspec, blacklist, deps_mode)
if missing[name] then
table.insert(dependents, { name = rock_name, version = rock_version })
end
end
end
end
return dependents
end
--- Delete given versions of a program.
-- @param name string: the name of a program
-- @param versions array of string: the versions to be deleted.
-- @param deps_mode: string: Which trees to check dependencies for:
-- "one" for the current default tree, "all" for all trees,
-- "order" for all trees with priority >= the current default, "none" for no trees.
-- @return boolean or (nil, string): true on success or nil and an error message.
local function delete_versions(name, versions, deps_mode)
for version, _ in pairs(versions) do
util.printout("Removing "..name.." "..version.."...")
local ok, err = repos.delete_version(name, version, deps_mode)
if not ok then return nil, err end
end
return true
end
function remove.remove_search_results(results, name, deps_mode, force, fast)
local versions = results[name]
local version = next(versions)
local second = next(versions, version)
local dependents = {}
if not fast then
util.printout("Checking stability of dependencies in the absence of")
util.printout(name.." "..table.concat(util.keys(versions), ", ").."...")
util.printout()
dependents = check_dependents(name, versions, deps_mode)
end
if #dependents > 0 then
if force or fast then
util.printerr("The following packages may be broken by this forced removal:")
for _, dependent in ipairs(dependents) do
util.printerr(dependent.name.." "..dependent.version)
end
util.printerr()
else
if not second then
util.printerr("Will not remove "..name.." "..version..".")
util.printerr("Removing it would break dependencies for: ")
else
util.printerr("Will not remove installed versions of "..name..".")
util.printerr("Removing them would break dependencies for: ")
end
for _, dependent in ipairs(dependents) do
util.printerr(dependent.name.." "..dependent.version)
end
util.printerr()
util.printerr("Use --force to force removal (warning: this may break modules).")
return nil, "Failed removing."
end
end
local ok, err = delete_versions(name, versions, deps_mode)
if not ok then return nil, err end
util.printout("Removal successful.")
return true
end
function remove.remove_other_versions(name, version, force, fast)
local results = {}
search.manifest_search(results, cfg.rocks_dir, { name = name, exact_name = true, constraints = {{ op = "~=", version = version}} })
if results[name] then
return remove.remove_search_results(results, name, cfg.deps_mode, force, fast)
end
return true
end
--- Driver function for the "remove" command.
-- @param name string: name of a rock. If a version is given, refer to
-- a specific version; otherwise, try to remove all versions.
-- @param version string: When passing a package name, a version number
-- may also be given.
-- @return boolean or (nil, string, exitcode): True if removal was
-- successful, nil and an error message otherwise. exitcode is optionally returned.
function remove.command(flags, name, version)
if type(name) ~= "string" then
return nil, "Argument missing. "..util.see_help("remove")
end
local deps_mode = flags["deps-mode"] or cfg.deps_mode
local ok, err = fs.check_command_permissions(flags)
if not ok then return nil, err, cfg.errorcodes.PERMISSIONDENIED end
local rock_type = name:match("%.(rock)$") or name:match("%.(rockspec)$")
local filename = name
if rock_type then
name, version = path.parse_name(filename)
if not name then return nil, "Invalid "..rock_type.." filename: "..filename end
end
local results = {}
name = name:lower()
search.manifest_search(results, cfg.rocks_dir, search.make_query(name, version))
if not results[name] then
return nil, "Could not find rock '"..name..(version and " "..version or "").."' in "..path.rocks_tree_to_string(cfg.root_dir)
end
local ok, err = remove.remove_search_results(results, name, deps_mode, flags["force"], flags["force-fast"])
if not ok then
return nil, err
end
manif.check_dependencies(nil, deps.get_deps_mode(flags))
return true
end
return remove
luarocks-2.4.2+dfsg/src/luarocks/repos.lua 0000664 0000000 0000000 00000037250 13030154704 0020532 0 ustar 00root root 0000000 0000000
--- Functions for managing the repository on disk.
local repos = {}
package.loaded["luarocks.repos"] = repos
local fs = require("luarocks.fs")
local path = require("luarocks.path")
local cfg = require("luarocks.cfg")
local util = require("luarocks.util")
local dir = require("luarocks.dir")
local manif = require("luarocks.manif")
local deps = require("luarocks.deps")
-- Tree of files installed by a package are stored
-- in its rock manifest. Some of these files have to
-- be deployed to locations where Lua can load them as
-- modules or where they can be used as commands.
-- These files are characterised by pair
-- (deploy_type, file_path), where deploy_type is the first
-- component of the file path and file_path is the rest of the
-- path. Only files with deploy_type in {"lua", "lib", "bin"}
-- are deployed somewhere.
-- Each deployed file provides an "item". An item is
-- characterised by pair (item_type, item_name).
-- item_type is "command" for files with deploy_type
-- "bin" and "module" for deploy_type in {"lua", "lib"}.
-- item_name is same as file_path for commands
-- and is produced using path.path_to_module(file_path)
-- for modules.
--- Get all installed versions of a package.
-- @param name string: a package name.
-- @return table or nil: An array of strings listing installed
-- versions of a package, or nil if none is available.
local function get_installed_versions(name)
assert(type(name) == "string")
local dirs = fs.list_dir(path.versions_dir(name))
return (dirs and #dirs > 0) and dirs or nil
end
--- Check if a package exists in a local repository.
-- Version numbers are compared as exact string comparison.
-- @param name string: name of package
-- @param version string: package version in string format
-- @return boolean: true if a package is installed,
-- false otherwise.
function repos.is_installed(name, version)
assert(type(name) == "string")
assert(type(version) == "string")
return fs.is_dir(path.install_dir(name, version))
end
local function recurse_rock_manifest_tree(file_tree, action)
assert(type(file_tree) == "table")
assert(type(action) == "function")
local function do_recurse_rock_manifest_tree(tree, parent_path, parent_module)
for file, sub in pairs(tree) do
if type(sub) == "table" then
local ok, err = do_recurse_rock_manifest_tree(sub, parent_path..file.."/", parent_module..file..".")
if not ok then return nil, err end
else
local ok, err = action(parent_path, parent_module, file)
if not ok then return nil, err end
end
end
return true
end
return do_recurse_rock_manifest_tree(file_tree, "", "")
end
local function store_package_data(result, name, file_tree)
if not file_tree then return end
return recurse_rock_manifest_tree(file_tree,
function(parent_path, parent_module, file)
local pathname = parent_path..file
result[path.path_to_module(pathname)] = pathname
return true
end
)
end
--- Obtain a list of modules within an installed package.
-- @param package string: The package name; for example "luasocket"
-- @param version string: The exact version number including revision;
-- for example "2.0.1-1".
-- @return table: A table of modules where keys are module identifiers
-- in "foo.bar" format and values are pathnames in architecture-dependent
-- "foo/bar.so" format. If no modules are found or if package or version
-- are invalid, an empty table is returned.
function repos.package_modules(package, version)
assert(type(package) == "string")
assert(type(version) == "string")
local result = {}
local rock_manifest = manif.load_rock_manifest(package, version)
store_package_data(result, package, rock_manifest.lib)
store_package_data(result, package, rock_manifest.lua)
return result
end
--- Obtain a list of command-line scripts within an installed package.
-- @param package string: The package name; for example "luasocket"
-- @param version string: The exact version number including revision;
-- for example "2.0.1-1".
-- @return table: A table of items where keys are command names
-- as strings and values are pathnames in architecture-dependent
-- ".../bin/foo" format. If no modules are found or if package or version
-- are invalid, an empty table is returned.
function repos.package_commands(package, version)
assert(type(package) == "string")
assert(type(version) == "string")
local result = {}
local rock_manifest = manif.load_rock_manifest(package, version)
store_package_data(result, package, rock_manifest.bin)
return result
end
--- Check if a rock contains binary executables.
-- @param name string: name of an installed rock
-- @param version string: version of an installed rock
-- @return boolean: returns true if rock contains platform-specific
-- binary executables, or false if it is a pure-Lua rock.
function repos.has_binaries(name, version)
assert(type(name) == "string")
assert(type(version) == "string")
local rock_manifest = manif.load_rock_manifest(name, version)
if rock_manifest.bin then
for name, md5 in pairs(rock_manifest.bin) do
-- TODO verify that it is the same file. If it isn't, find the actual command.
if fs.is_actual_binary(dir.path(cfg.deploy_bin_dir, name)) then
return true
end
end
end
return false
end
function repos.run_hook(rockspec, hook_name)
assert(type(rockspec) == "table")
assert(type(hook_name) == "string")
local hooks = rockspec.hooks
if not hooks then
return true
end
if cfg.hooks_enabled == false then
return nil, "This rockspec contains hooks, which are blocked by the 'hooks_enabled' setting in your LuaRocks configuration."
end
if not hooks.substituted_variables then
util.variable_substitutions(hooks, rockspec.variables)
hooks.substituted_variables = true
end
local hook = hooks[hook_name]
if hook then
util.printout(hook)
if not fs.execute(hook) then
return nil, "Failed running "..hook_name.." hook."
end
end
return true
end
function repos.should_wrap_bin_scripts(rockspec)
assert(type(rockspec) == "table")
if cfg.wrap_bin_scripts ~= nil then
return cfg.wrap_bin_scripts
end
if rockspec.deploy and rockspec.deploy.wrap_bin_scripts == false then
return false
end
return true
end
local function find_suffixed(file, suffix)
local filenames = {file}
if suffix and suffix ~= "" then
table.insert(filenames, 1, file .. suffix)
end
for _, filename in ipairs(filenames) do
if fs.exists(filename) then
return filename
end
end
return nil, table.concat(filenames, ", ") .. " not found"
end
local function move_suffixed(from_file, to_file, suffix)
local suffixed_from_file, err = find_suffixed(from_file, suffix)
if not suffixed_from_file then
return nil, "Could not move " .. from_file .. " to " .. to_file .. ": " .. err
end
suffix = suffixed_from_file:sub(#from_file + 1)
local suffixed_to_file = to_file .. suffix
return fs.move(suffixed_from_file, suffixed_to_file)
end
local function delete_suffixed(file, suffix)
local suffixed_file, err = find_suffixed(file, suffix)
if not suffixed_file then
return nil, "Could not remove " .. file .. ": " .. err
end
fs.delete(suffixed_file)
if fs.exists(suffixed_file) then
return nil, "Failed deleting " .. suffixed_file .. ": file still exists"
end
return true
end
-- Files can be deployed using versioned and non-versioned names.
-- Several items with same type and name can exist if they are
-- provided by different packages or versions. In any case
-- item from the newest version of lexicographically smallest package
-- is deployed using non-versioned name and others use versioned names.
local function get_deploy_paths(name, version, deploy_type, file_path)
local deploy_dir = cfg["deploy_" .. deploy_type .. "_dir"]
local non_versioned = dir.path(deploy_dir, file_path)
local versioned = path.versioned_name(non_versioned, deploy_dir, name, version)
return non_versioned, versioned
end
local function prepare_target(name, version, deploy_type, file_path, suffix)
local non_versioned, versioned = get_deploy_paths(name, version, deploy_type, file_path)
local item_type, item_name = manif.get_provided_item(deploy_type, file_path)
local cur_name, cur_version = manif.get_current_provider(item_type, item_name)
if not cur_name then
return non_versioned
elseif name < cur_name or (name == cur_name and deps.compare_versions(version, cur_version)) then
-- New version has priority. Move currently provided version back using versioned name.
local cur_deploy_type, cur_file_path = manif.get_providing_file(cur_name, cur_version, item_type, item_name)
local cur_non_versioned, cur_versioned = get_deploy_paths(cur_name, cur_version, cur_deploy_type, cur_file_path)
local dir_ok, dir_err = fs.make_dir(dir.dir_name(cur_versioned))
if not dir_ok then return nil, dir_err end
local move_ok, move_err = move_suffixed(cur_non_versioned, cur_versioned, suffix)
if not move_ok then return nil, move_err end
return non_versioned
else
-- Current version has priority, deploy new version using versioned name.
return versioned
end
end
--- Deploy a package from the rocks subdirectory.
-- @param name string: name of package
-- @param version string: exact package version in string format
-- @param wrap_bin_scripts bool: whether commands written in Lua should be wrapped.
-- @param deps_mode: string: Which trees to check dependencies for:
-- "one" for the current default tree, "all" for all trees,
-- "order" for all trees with priority >= the current default, "none" for no trees.
function repos.deploy_files(name, version, wrap_bin_scripts, deps_mode)
assert(type(name) == "string")
assert(type(version) == "string")
assert(type(wrap_bin_scripts) == "boolean")
local rock_manifest = manif.load_rock_manifest(name, version)
local function deploy_file_tree(deploy_type, source_dir, move_fn, suffix)
if not rock_manifest[deploy_type] then
return true
end
return recurse_rock_manifest_tree(rock_manifest[deploy_type], function(parent_path, parent_module, file)
local file_path = parent_path .. file
local source = dir.path(source_dir, file_path)
local target, prepare_err = prepare_target(name, version, deploy_type, file_path, suffix)
if not target then return nil, prepare_err end
local dir_ok, dir_err = fs.make_dir(dir.dir_name(target))
if not dir_ok then return nil, dir_err end
local suffixed_target, mover = move_fn(source, target)
if fs.exists(suffixed_target) then
local backup = suffixed_target
repeat
backup = backup.."~"
until not fs.exists(backup) -- Slight race condition here, but shouldn't be a problem.
util.printerr("Warning: "..suffixed_target.." is not tracked by this installation of LuaRocks. Moving it to "..backup)
local move_ok, move_err = fs.move(suffixed_target, backup)
if not move_ok then return nil, move_err end
end
local move_ok, move_err = mover()
if not move_ok then return nil, move_err end
fs.remove_dir_tree_if_empty(dir.dir_name(source))
return true
end)
end
local function install_binary(source, target)
if wrap_bin_scripts and fs.is_lua(source) then
return target .. (cfg.wrapper_suffix or ""), function() return fs.wrap_script(source, target, name, version) end
else
return target, function() return fs.copy_binary(source, target) end
end
end
local function make_mover(perms)
return function(source, target)
return target, function() return fs.move(source, target, perms) end
end
end
local ok, err = deploy_file_tree("bin", path.bin_dir(name, version), install_binary, cfg.wrapper_suffix)
if not ok then return nil, err end
ok, err = deploy_file_tree("lua", path.lua_dir(name, version), make_mover(cfg.perm_read))
if not ok then return nil, err end
ok, err = deploy_file_tree("lib", path.lib_dir(name, version), make_mover(cfg.perm_exec))
if not ok then return nil, err end
return manif.add_to_manifest(name, version, nil, deps_mode)
end
--- Delete a package from the local repository.
-- @param name string: name of package
-- @param version string: exact package version in string format
-- @param deps_mode: string: Which trees to check dependencies for:
-- "one" for the current default tree, "all" for all trees,
-- "order" for all trees with priority >= the current default, "none" for no trees.
-- @param quick boolean: do not try to fix the versioned name
-- of another version that provides the same module that
-- was deleted. This is used during 'purge', as every module
-- will be eventually deleted.
function repos.delete_version(name, version, deps_mode, quick)
assert(type(name) == "string")
assert(type(version) == "string")
assert(type(deps_mode) == "string")
local rock_manifest = manif.load_rock_manifest(name, version)
if not rock_manifest then
return nil, "rock_manifest file not found for "..name.." "..version.." - not a LuaRocks 2 tree?"
end
local function delete_deployed_file_tree(deploy_type, suffix)
if not rock_manifest[deploy_type] then
return true
end
return recurse_rock_manifest_tree(rock_manifest[deploy_type], function(parent_path, parent_module, file)
local file_path = parent_path .. file
local non_versioned, versioned = get_deploy_paths(name, version, deploy_type, file_path)
-- Figure out if the file is deployed using versioned or non-versioned name.
local target
local item_type, item_name = manif.get_provided_item(deploy_type, file_path)
local cur_name, cur_version = manif.get_current_provider(item_type, item_name)
if cur_name == name and cur_version == version then
-- This package has highest priority, should be in non-versioned location.
target = non_versioned
else
target = versioned
end
local ok, err = delete_suffixed(target, suffix)
if not ok then return nil, err end
if not quick and target == non_versioned then
-- If another package provides this file, move its version
-- into non-versioned location instead.
local next_name, next_version = manif.get_next_provider(item_type, item_name)
if next_name then
local next_deploy_type, next_file_path = manif.get_providing_file(next_name, next_version, item_type, item_name)
local next_non_versioned, next_versioned = get_deploy_paths(next_name, next_version, next_deploy_type, next_file_path)
local move_ok, move_err = move_suffixed(next_versioned, next_non_versioned, suffix)
if not move_ok then return nil, move_err end
fs.remove_dir_tree_if_empty(dir.dir_name(next_versioned))
end
end
fs.remove_dir_tree_if_empty(dir.dir_name(target))
return true
end)
end
local ok, err = delete_deployed_file_tree("bin", cfg.wrapper_suffix)
if not ok then return nil, err end
ok, err = delete_deployed_file_tree("lua")
if not ok then return nil, err end
ok, err = delete_deployed_file_tree("lib")
if not ok then return nil, err end
fs.delete(path.install_dir(name, version))
if not get_installed_versions(name) then
fs.delete(dir.path(cfg.rocks_dir, name))
end
if quick then
return true
end
return manif.remove_from_manifest(name, version, nil, deps_mode)
end
return repos
luarocks-2.4.2+dfsg/src/luarocks/require.lua 0000664 0000000 0000000 00000000154 13030154704 0021047 0 ustar 00root root 0000000 0000000 --- Retained for compatibility reasons only. Use luarocks.loader instead.
return require("luarocks.loader")
luarocks-2.4.2+dfsg/src/luarocks/search.lua 0000664 0000000 0000000 00000043775 13030154704 0020660 0 ustar 00root root 0000000 0000000
--- Module implementing the LuaRocks "search" command.
-- Queries LuaRocks servers.
local search = {}
package.loaded["luarocks.search"] = search
local dir = require("luarocks.dir")
local path = require("luarocks.path")
local manif = require("luarocks.manif")
local deps = require("luarocks.deps")
local cfg = require("luarocks.cfg")
local util = require("luarocks.util")
util.add_run_function(search)
search.help_summary = "Query the LuaRocks servers."
search.help_arguments = "[--source] [--binary] { [] | --all }"
search.help = [[
--source Return only rockspecs and source rocks,
to be used with the "build" command.
--binary Return only pure Lua and binary rocks (rocks that can be used
with the "install" command without requiring a C toolchain).
--all List all contents of the server that are suitable to
this platform, do not filter by name.
]]
--- Convert the arch field of a query table to table format.
-- @param query table: A query table.
local function query_arch_as_table(query)
local format = type(query.arch)
if format == "table" then
return
elseif format == "nil" then
local accept = {}
accept["src"] = true
accept["all"] = true
accept["rockspec"] = true
accept["installed"] = true
accept[cfg.arch] = true
query.arch = accept
elseif format == "string" then
local accept = {}
for a in query.arch:gmatch("[%w_-]+") do
accept[a] = true
end
query.arch = accept
end
end
--- Store a search result (a rock or rockspec) in the results table.
-- @param results table: The results table, where keys are package names and
-- values are tables matching version strings to arrays of
-- tables with fields "arch" and "repo".
-- @param name string: Package name.
-- @param version string: Package version.
-- @param arch string: Architecture of rock ("all", "src" or platform
-- identifier), "rockspec" or "installed"
-- @param repo string: Pathname of a local repository of URL of
-- rocks server.
local function store_result(results, name, version, arch, repo)
assert(type(results) == "table")
assert(type(name) == "string")
assert(type(version) == "string")
assert(type(arch) == "string")
assert(type(repo) == "string")
if not results[name] then results[name] = {} end
if not results[name][version] then results[name][version] = {} end
table.insert(results[name][version], {
arch = arch,
repo = repo
})
end
--- Test the name field of a query.
-- If query has a boolean field exact_name set to false,
-- then substring match is performed; otherwise, exact string
-- comparison is done.
-- @param query table: A query in dependency table format.
-- @param name string: A package name.
-- @return boolean: True if names match, false otherwise.
local function match_name(query, name)
assert(type(query) == "table")
assert(type(name) == "string")
if query.exact_name == false then
return name:find(query.name, 0, true) and true or false
else
return name == query.name
end
end
--- Store a match in a results table if version matches query.
-- Name, version, arch and repository path are stored in a given
-- table, optionally checking if version and arch (if given) match
-- a query.
-- @param results table: The results table, where keys are package names and
-- values are tables matching version strings to arrays of
-- tables with fields "arch" and "repo".
-- @param repo string: URL or pathname of the repository.
-- @param name string: The name of the package being tested.
-- @param version string: The version of the package being tested.
-- @param arch string: The arch of the package being tested.
-- @param query table: A table describing the query in dependency
-- format (for example, {name = "filesystem", exact_name = false,
-- constraints = {op = "~>", version = {1,0}}}, arch = "rockspec").
-- If the arch field is omitted, the local architecture (cfg.arch)
-- is used. The special value "any" is also recognized, returning all
-- matches regardless of architecture.
local function store_if_match(results, repo, name, version, arch, query)
if match_name(query, name) then
if query.arch[arch] or query.arch["any"] then
if deps.match_constraints(deps.parse_version(version), query.constraints) then
store_result(results, name, version, arch, repo)
end
end
end
end
--- Perform search on a local repository.
-- @param repo string: The pathname of the local repository.
-- @param query table: A table describing the query in dependency
-- format (for example, {name = "filesystem", exact_name = false,
-- constraints = {op = "~>", version = {1,0}}}, arch = "rockspec").
-- If the arch field is omitted, the local architecture (cfg.arch)
-- is used. The special value "any" is also recognized, returning all
-- matches regardless of architecture.
-- @param results table or nil: If given, this table will store the
-- results; if not given, a new table will be created.
-- @return table: The results table, where keys are package names and
-- values are tables matching version strings to arrays of
-- tables with fields "arch" and "repo".
-- If a table was given in the "results" parameter, that is the result value.
function search.disk_search(repo, query, results)
assert(type(repo) == "string")
assert(type(query) == "table")
assert(type(results) == "table" or not results)
local fs = require("luarocks.fs")
if not results then
results = {}
end
query_arch_as_table(query)
for name in fs.dir(repo) do
local pathname = dir.path(repo, name)
local rname, rversion, rarch = path.parse_name(name)
if rname and (pathname:match(".rockspec$") or pathname:match(".rock$")) then
store_if_match(results, repo, rname, rversion, rarch, query)
elseif fs.is_dir(pathname) then
for version in fs.dir(pathname) do
if version:match("-%d+$") then
store_if_match(results, repo, name, version, "installed", query)
end
end
end
end
return results
end
--- Perform search on a rocks server or tree.
-- @param results table: The results table, where keys are package names and
-- values are tables matching version strings to arrays of
-- tables with fields "arch" and "repo".
-- @param repo string: The URL of a rocks server or
-- the pathname of a rocks tree (as returned by path.rocks_dir()).
-- @param query table: A table describing the query in dependency
-- format (for example, {name = "filesystem", exact_name = false,
-- constraints = {op = "~>", version = {1,0}}}, arch = "rockspec").
-- If the arch field is omitted, the local architecture (cfg.arch)
-- is used. The special value "any" is also recognized, returning all
-- matches regardless of architecture.
-- @param lua_version string: Lua version in "5.x" format, defaults to installed version.
-- @return true or, in case of errors, nil, an error message and an optional error code.
function search.manifest_search(results, repo, query, lua_version)
assert(type(results) == "table")
assert(type(repo) == "string")
assert(type(query) == "table")
query_arch_as_table(query)
local manifest, err, errcode = manif.load_manifest(repo, lua_version)
if not manifest then
return nil, err, errcode
end
for name, versions in pairs(manifest.repository) do
for version, items in pairs(versions) do
for _, item in ipairs(items) do
store_if_match(results, repo, name, version, item.arch, query)
end
end
end
return true
end
--- Search on all configured rocks servers.
-- @param query table: A dependency query.
-- @param lua_version string: Lua version in "5.x" format, defaults to installed version.
-- @return table: A table where keys are package names
-- and values are tables matching version strings to arrays of
-- tables with fields "arch" and "repo".
function search.search_repos(query, lua_version)
assert(type(query) == "table")
local results = {}
for _, repo in ipairs(cfg.rocks_servers) do
if not cfg.disabled_servers[repo] then
if type(repo) == "string" then
repo = { repo }
end
for _, mirror in ipairs(repo) do
local protocol, pathname = dir.split_url(mirror)
if protocol == "file" then
mirror = pathname
end
local ok, err, errcode = search.manifest_search(results, mirror, query, lua_version)
if errcode == "network" then
cfg.disabled_servers[repo] = true
end
if ok then
break
else
util.warning("Failed searching manifest: "..err)
end
end
end
end
-- search through rocks in cfg.rocks_provided
local provided_repo = "provided by VM or rocks_provided"
for name, versions in pairs(cfg.rocks_provided) do
store_if_match(results, provided_repo, name, versions, "installed", query)
end
return results
end
--- Prepare a query in dependency table format.
-- @param name string: The query name.
-- @param version string or nil:
-- @return table: A query in table format
function search.make_query(name, version)
assert(type(name) == "string")
assert(type(version) == "string" or not version)
local query = {
name = name,
constraints = {}
}
if version then
table.insert(query.constraints, { op = "==", version = deps.parse_version(version)})
end
return query
end
--- Get the URL for the latest in a set of versions.
-- @param name string: The package name to be used in the URL.
-- @param versions table: An array of version informations, as stored
-- in search results tables.
-- @return string or nil: the URL for the latest version if one could
-- be picked, or nil.
local function pick_latest_version(name, versions)
assert(type(name) == "string")
assert(type(versions) == "table")
local vtables = {}
for v, _ in pairs(versions) do
table.insert(vtables, deps.parse_version(v))
end
table.sort(vtables)
local version = vtables[#vtables].string
local items = versions[version]
if items then
local pick = 1
for i, item in ipairs(items) do
if (item.arch == 'src' and items[pick].arch == 'rockspec')
or (item.arch ~= 'src' and item.arch ~= 'rockspec') then
pick = i
end
end
return path.make_url(items[pick].repo, name, version, items[pick].arch)
end
return nil
end
-- Find out which other Lua versions provide rock versions matching a query,
-- @param query table: A dependency query matching a single rock.
-- @return table: array of Lua versions supported, in "5.x" format.
local function supported_lua_versions(query)
local results = {}
for lua_version in util.lua_versions() do
if lua_version ~= cfg.lua_version then
if search.search_repos(query, lua_version)[query.name] then
table.insert(results, lua_version)
end
end
end
return results
end
--- Attempt to get a single URL for a given search for a rock.
-- @param query table: A dependency query matching a single rock.
-- @return string or (nil, string): URL for latest matching version
-- of the rock if it was found, or nil followed by an error message.
function search.find_suitable_rock(query)
assert(type(query) == "table")
local results = search.search_repos(query)
local first_rock = next(results)
if not first_rock then
if cfg.rocks_provided[query.name] == nil then
-- Check if constraints are satisfiable with other Lua versions.
local lua_versions = supported_lua_versions(query)
if #lua_versions ~= 0 then
-- Build a nice message in "only Lua 5.x and 5.y but not 5.z." format
for i, lua_version in ipairs(lua_versions) do
lua_versions[i] = "Lua "..lua_version
end
local versions_message = "only "..table.concat(lua_versions, " and ")..
" but not Lua "..cfg.lua_version.."."
if #query.constraints == 0 then
return nil, query.name.." supports "..versions_message
elseif #query.constraints == 1 and query.constraints[1].op == "==" then
return nil, query.name.." "..query.constraints[1].version.string.." supports "..versions_message
else
return nil, "Matching "..query.name.." versions support "..versions_message
end
end
end
return nil, "No results matching query were found."
elseif next(results, first_rock) then
-- Shouldn't happen as query must match only one package.
return nil, "Several rocks matched query."
elseif cfg.rocks_provided[query.name] ~= nil then
-- Do not install versions listed in cfg.rocks_provided.
return nil, "Rock "..query.name.." "..cfg.rocks_provided[query.name]..
" was found but it is provided by VM or 'rocks_provided' in the config file."
else
return pick_latest_version(query.name, results[first_rock])
end
end
--- Print a list of rocks/rockspecs on standard output.
-- @param results table: A table where keys are package names and versions
-- are tables matching version strings to an array of rocks servers.
-- @param porcelain boolean or nil: A flag to force machine-friendly output.
function search.print_results(results, porcelain)
assert(type(results) == "table")
assert(type(porcelain) == "boolean" or not porcelain)
for package, versions in util.sortedpairs(results) do
if not porcelain then
util.printout(package)
end
for version, repos in util.sortedpairs(versions, deps.compare_versions) do
for _, repo in ipairs(repos) do
repo.repo = dir.normalize(repo.repo)
if porcelain then
util.printout(package, version, repo.arch, repo.repo)
else
util.printout(" "..version.." ("..repo.arch..") - "..repo.repo)
end
end
end
if not porcelain then
util.printout()
end
end
end
--- Splits a list of search results into two lists, one for "source" results
-- to be used with the "build" command, and one for "binary" results to be
-- used with the "install" command.
-- @param results table: A search results table.
-- @return (table, table): Two tables, one for source and one for binary
-- results.
local function split_source_and_binary_results(results)
local sources, binaries = {}, {}
for name, versions in pairs(results) do
for version, repositories in pairs(versions) do
for _, repo in ipairs(repositories) do
local where = sources
if repo.arch == "all" or repo.arch == cfg.arch then
where = binaries
end
store_result(where, name, version, repo.arch, repo.repo)
end
end
end
return sources, binaries
end
--- Given a name and optionally a version, try to find in the rocks
-- servers a single .src.rock or .rockspec file that satisfies
-- the request, and run the given function on it; or display to the
-- user possibilities if it couldn't narrow down a single match.
-- @param action function: A function that takes a .src.rock or
-- .rockspec URL as a parameter.
-- @param name string: A rock name
-- @param version string or nil: A version number may also be given.
-- @return The result of the action function, or nil and an error message.
function search.act_on_src_or_rockspec(action, name, version, ...)
assert(type(action) == "function")
assert(type(name) == "string")
assert(type(version) == "string" or not version)
local query = search.make_query(name, version)
query.arch = "src|rockspec"
local url, err = search.find_suitable_rock(query)
if not url then
return nil, "Could not find a result named "..name..(version and " "..version or "")..": "..err
end
return action(url, ...)
end
function search.pick_installed_rock(name, version, given_tree)
local results = {}
local query = search.make_query(name, version)
query.exact_name = true
local tree_map = {}
local trees = cfg.rocks_trees
if given_tree then
trees = { given_tree }
end
for _, tree in ipairs(trees) do
local rocks_dir = path.rocks_dir(tree)
tree_map[rocks_dir] = tree
search.manifest_search(results, rocks_dir, query)
end
if not next(results) then --
return nil,"cannot find package "..name.." "..(version or "").."\nUse 'list' to find installed rocks."
end
version = nil
local repo_url
local package, versions = util.sortedpairs(results)()
--question: what do we do about multiple versions? This should
--give us the latest version on the last repo (which is usually the global one)
for vs, repositories in util.sortedpairs(versions, deps.compare_versions) do
if not version then version = vs end
for _, rp in ipairs(repositories) do repo_url = rp.repo end
end
local repo = tree_map[repo_url]
return name, version, repo, repo_url
end
--- Driver function for "search" command.
-- @param name string: A substring of a rock name to search.
-- @param version string or nil: a version may also be passed.
-- @return boolean or (nil, string): True if build was successful; nil and an
-- error message otherwise.
function search.command(flags, name, version)
if flags["all"] then
name, version = "", nil
end
if type(name) ~= "string" and not flags["all"] then
return nil, "Enter name and version or use --all. "..util.see_help("search")
end
local query = search.make_query(name:lower(), version)
query.exact_name = false
local results, err = search.search_repos(query)
local porcelain = flags["porcelain"]
util.title("Search results:", porcelain, "=")
local sources, binaries = split_source_and_binary_results(results)
if next(sources) and not flags["binary"] then
util.title("Rockspecs and source rocks:", porcelain)
search.print_results(sources, porcelain)
end
if next(binaries) and not flags["source"] then
util.title("Binary and pure-Lua rocks:", porcelain)
search.print_results(binaries, porcelain)
end
return true
end
return search
luarocks-2.4.2+dfsg/src/luarocks/show.lua 0000664 0000000 0000000 00000012262 13030154704 0020356 0 ustar 00root root 0000000 0000000 --- Module implementing the LuaRocks "show" command.
-- Shows information about an installed rock.
local show = {}
package.loaded["luarocks.show"] = show
local search = require("luarocks.search")
local cfg = require("luarocks.cfg")
local util = require("luarocks.util")
local path = require("luarocks.path")
local deps = require("luarocks.deps")
local fetch = require("luarocks.fetch")
local manif = require("luarocks.manif")
util.add_run_function(show)
show.help_summary = "Show information about an installed rock."
show.help = [[
is an existing package name.
Without any flags, show all module information.
With these flags, return only the desired information:
--home home page of project
--modules all modules provided by this package as used by require()
--deps packages this package depends on
--rockspec the full path of the rockspec file
--mversion the package version
--rock-tree local tree where rock is installed
--rock-dir data directory of the installed rock
]]
local function keys_as_string(t, sep)
local keys = util.keys(t)
table.sort(keys)
return table.concat(keys, sep or " ")
end
local function word_wrap(line)
local width = tonumber(os.getenv("COLUMNS")) or 80
if width > 80 then width = 80 end
if #line > width then
local brk = width
while brk > 0 and line:sub(brk, brk) ~= " " do
brk = brk - 1
end
if brk > 0 then
return line:sub(1, brk-1) .. "\n" .. word_wrap(line:sub(brk+1))
end
end
return line
end
local function format_text(text)
text = text:gsub("^%s*",""):gsub("%s$", ""):gsub("\n[ \t]+","\n"):gsub("([^\n])\n([^\n])","%1 %2")
local paragraphs = util.split_string(text, "\n\n")
for n, line in ipairs(paragraphs) do
paragraphs[n] = word_wrap(line)
end
return (table.concat(paragraphs, "\n\n"):gsub("%s$", ""))
end
local function installed_rock_label(name, tree)
local installed, version
if cfg.rocks_provided[name] then
installed, version = true, cfg.rocks_provided[name]
else
installed, version = search.pick_installed_rock(name, nil, tree)
end
return installed and "(using "..version..")" or "(missing)"
end
--- Driver function for "show" command.
-- @param name or nil: an existing package name.
-- @param version string or nil: a version may also be passed.
-- @return boolean: True if succeeded, nil on errors.
function show.command(flags, name, version)
if not name then
return nil, "Argument missing. "..util.see_help("show")
end
local repo, repo_url
name, version, repo, repo_url = search.pick_installed_rock(name:lower(), version, flags["tree"])
if not name then
return nil, version
end
local directory = path.install_dir(name,version,repo)
local rockspec_file = path.rockspec_file(name, version, repo)
local rockspec, err = fetch.load_local_rockspec(rockspec_file)
if not rockspec then return nil,err end
local descript = rockspec.description or {}
local manifest, err = manif.load_manifest(repo_url)
if not manifest then return nil,err end
local minfo = manifest.repository[name][version][1]
if flags["rock-tree"] then util.printout(path.rocks_tree_to_string(repo))
elseif flags["rock-dir"] then util.printout(directory)
elseif flags["home"] then util.printout(descript.homepage)
elseif flags["modules"] then util.printout(keys_as_string(minfo.modules, "\n"))
elseif flags["deps"] then util.printout(keys_as_string(minfo.dependencies))
elseif flags["rockspec"] then util.printout(rockspec_file)
elseif flags["mversion"] then util.printout(version)
else
util.printout()
util.printout(rockspec.package.." "..rockspec.version.." - "..(descript.summary or ""))
util.printout()
if descript.detailed then
util.printout(format_text(descript.detailed))
util.printout()
end
if descript.license then
util.printout("License: ", descript.license)
end
if descript.homepage then
util.printout("Homepage: ", descript.homepage)
end
util.printout("Installed in: ", path.rocks_tree_to_string(repo))
if next(minfo.modules) then
util.printout()
util.printout("Modules:")
for mod, filename in util.sortedpairs(minfo.modules) do
util.printout("\t"..mod.." ("..path.which(mod, filename, name, version, repo, manifest)..")")
end
end
local direct_deps = {}
if #rockspec.dependencies > 0 then
util.printout()
util.printout("Depends on:")
for _, dep in ipairs(rockspec.dependencies) do
direct_deps[dep.name] = true
util.printout("\t"..deps.show_dep(dep).." "..installed_rock_label(dep.name, flags["tree"]))
end
end
local has_indirect_deps
for dep_name in util.sortedpairs(minfo.dependencies) do
if not direct_deps[dep_name] then
if not has_indirect_deps then
util.printout()
util.printout("Indirectly pulling:")
has_indirect_deps = true
end
util.printout("\t"..dep_name.." "..installed_rock_label(dep_name, flags["tree"]))
end
end
util.printout()
end
return true
end
return show
luarocks-2.4.2+dfsg/src/luarocks/tools/ 0000775 0000000 0000000 00000000000 13030154704 0020030 5 ustar 00root root 0000000 0000000 luarocks-2.4.2+dfsg/src/luarocks/tools/patch.lua 0000664 0000000 0000000 00000052772 13030154704 0021647 0 ustar 00root root 0000000 0000000 --- Patch utility to apply unified diffs.
--
-- http://lua-users.org/wiki/LuaPatch
--
-- (c) 2008 David Manura, Licensed under the same terms as Lua (MIT license).
-- Code is heavilly based on the Python-based patch.py version 8.06-1
-- Copyright (c) 2008 rainforce.org, MIT License
-- Project home: http://code.google.com/p/python-patch/ .
-- Version 0.1
local patch = {}
local fs = require("luarocks.fs")
local util = require("luarocks.util")
local io = io
local os = os
local string = string
local table = table
local format = string.format
-- logging
local debugmode = false
local function debug(_) end
local function info(_) end
local function warning(s) io.stderr:write(s .. '\n') end
-- Returns boolean whether string s2 starts with string s.
local function startswith(s, s2)
return s:sub(1, #s2) == s2
end
-- Returns boolean whether string s2 ends with string s.
local function endswith(s, s2)
return #s >= #s2 and s:sub(#s-#s2+1) == s2
end
-- Returns string s after filtering out any new-line characters from end.
local function endlstrip(s)
return s:gsub('[\r\n]+$', '')
end
-- Returns shallow copy of table t.
local function table_copy(t)
local t2 = {}
for k,v in pairs(t) do t2[k] = v end
return t2
end
local function exists(filename)
local fh = io.open(filename)
local result = fh ~= nil
if fh then fh:close() end
return result
end
local function isfile() return true end --FIX?
local function read_file(filename)
local fh, data, err, oserr
fh, err, oserr = io.open(filename, 'rb')
if not fh then return fh, err, oserr end
data, err, oserr = fh:read'*a'
fh:close()
if not data then return nil, err, oserr end
return data
end
local function write_file(filename, data)
local fh, status, err, oserr
fh, err, oserr = io.open(filename 'wb')
if not fh then return fh, err, oserr end
status, err, oserr = fh:write(data)
fh:close()
if not status then return nil, err, oserr end
return true
end
local function file_copy(src, dest)
local data, status, err, oserr
data, err, oserr = read_file(src)
if not data then return data, err, oserr end
status, err, oserr = write_file(dest)
if not status then return status, err, oserr end
return true
end
local function string_as_file(s)
return {
at = 0,
str = s,
len = #s,
eof = false,
read = function(self, n)
if self.eof then return nil end
local chunk = self.str:sub(self.at, self.at + n - 1)
self.at = self.at + n
if self.at > self.len then
self.eof = true
end
return chunk
end,
close = function(self)
self.eof = true
end,
}
end
--
-- file_lines(f) is similar to f:lines() for file f.
-- The main difference is that read_lines includes
-- new-line character sequences ("\n", "\r\n", "\r"),
-- if any, at the end of each line. Embedded "\0" are also handled.
-- Caution: The newline behavior can depend on whether f is opened
-- in binary or ASCII mode.
-- (file_lines - version 20080913)
--
local function file_lines(f)
local CHUNK_SIZE = 1024
local buffer = ""
local pos_beg = 1
return function()
local pos, chars
while 1 do
pos, chars = buffer:match('()([\r\n].)', pos_beg)
if pos or not f then
break
elseif f then
local chunk = f:read(CHUNK_SIZE)
if chunk then
buffer = buffer:sub(pos_beg) .. chunk
pos_beg = 1
else
f = nil
end
end
end
if not pos then
pos = #buffer
elseif chars == '\r\n' then
pos = pos + 1
end
local line = buffer:sub(pos_beg, pos)
pos_beg = pos + 1
if #line > 0 then
return line
end
end
end
local function match_linerange(line)
local m1, m2, m3, m4 = line:match("^@@ %-(%d+),(%d+) %+(%d+),(%d+)")
if not m1 then m1, m3, m4 = line:match("^@@ %-(%d+) %+(%d+),(%d+)") end
if not m1 then m1, m2, m3 = line:match("^@@ %-(%d+),(%d+) %+(%d+)") end
if not m1 then m1, m3 = line:match("^@@ %-(%d+) %+(%d+)") end
return m1, m2, m3, m4
end
function patch.read_patch(filename, data)
-- define possible file regions that will direct the parser flow
local state = 'header'
-- 'header' - comments before the patch body
-- 'filenames' - lines starting with --- and +++
-- 'hunkhead' - @@ -R +R @@ sequence
-- 'hunkbody'
-- 'hunkskip' - skipping invalid hunk mode
local all_ok = true
local lineends = {lf=0, crlf=0, cr=0}
local files = {source={}, target={}, hunks={}, fileends={}, hunkends={}}
local nextfileno = 0
local nexthunkno = 0 --: even if index starts with 0 user messages
-- number hunks from 1
-- hunkinfo holds parsed values, hunkactual - calculated
local hunkinfo = {
startsrc=nil, linessrc=nil, starttgt=nil, linestgt=nil,
invalid=false, text={}
}
local hunkactual = {linessrc=nil, linestgt=nil}
info(format("reading patch %s", filename))
local fp
if data then
fp = string_as_file(data)
else
fp = filename == '-' and io.stdin or assert(io.open(filename, "rb"))
end
local lineno = 0
for line in file_lines(fp) do
lineno = lineno + 1
if state == 'header' then
if startswith(line, "--- ") then
state = 'filenames'
end
-- state is 'header' or 'filenames'
end
if state == 'hunkbody' then
-- skip hunkskip and hunkbody code until definition of hunkhead read
if line:match"^[\r\n]*$" then
-- prepend space to empty lines to interpret them as context properly
line = " " .. line
end
-- process line first
if line:match"^[- +\\]" then
-- gather stats about line endings
local he = files.hunkends[nextfileno]
if endswith(line, "\r\n") then
he.crlf = he.crlf + 1
elseif endswith(line, "\n") then
he.lf = he.lf + 1
elseif endswith(line, "\r") then
he.cr = he.cr + 1
end
if startswith(line, "-") then
hunkactual.linessrc = hunkactual.linessrc + 1
elseif startswith(line, "+") then
hunkactual.linestgt = hunkactual.linestgt + 1
elseif startswith(line, "\\") then
-- nothing
else
hunkactual.linessrc = hunkactual.linessrc + 1
hunkactual.linestgt = hunkactual.linestgt + 1
end
table.insert(hunkinfo.text, line)
-- todo: handle \ No newline cases
else
warning(format("invalid hunk no.%d at %d for target file %s",
nexthunkno, lineno, files.target[nextfileno]))
-- add hunk status node
table.insert(files.hunks[nextfileno], table_copy(hunkinfo))
files.hunks[nextfileno][nexthunkno].invalid = true
all_ok = false
state = 'hunkskip'
end
-- check exit conditions
if hunkactual.linessrc > hunkinfo.linessrc or
hunkactual.linestgt > hunkinfo.linestgt
then
warning(format("extra hunk no.%d lines at %d for target %s",
nexthunkno, lineno, files.target[nextfileno]))
-- add hunk status node
table.insert(files.hunks[nextfileno], table_copy(hunkinfo))
files.hunks[nextfileno][nexthunkno].invalid = true
state = 'hunkskip'
elseif hunkinfo.linessrc == hunkactual.linessrc and
hunkinfo.linestgt == hunkactual.linestgt
then
table.insert(files.hunks[nextfileno], table_copy(hunkinfo))
state = 'hunkskip'
-- detect mixed window/unix line ends
local ends = files.hunkends[nextfileno]
if (ends.cr~=0 and 1 or 0) + (ends.crlf~=0 and 1 or 0) +
(ends.lf~=0 and 1 or 0) > 1
then
warning(format("inconsistent line ends in patch hunks for %s",
files.source[nextfileno]))
end
if debugmode then
local debuglines = {crlf=ends.crlf, lf=ends.lf, cr=ends.cr,
file=files.target[nextfileno], hunk=nexthunkno}
debug(format("crlf: %(crlf)d lf: %(lf)d cr: %(cr)d\t " ..
"- file: %(file)s hunk: %(hunk)d", debuglines))
end
end
-- state is 'hunkbody' or 'hunkskip'
end
if state == 'hunkskip' then
if match_linerange(line) then
state = 'hunkhead'
elseif startswith(line, "--- ") then
state = 'filenames'
if debugmode and #files.source > 0 then
debug(format("- %2d hunks for %s", #files.hunks[nextfileno],
files.source[nextfileno]))
end
end
-- state is 'hunkskip', 'hunkhead', or 'filenames'
end
local advance
if state == 'filenames' then
if startswith(line, "--- ") then
if util.array_contains(files.source, nextfileno) then
all_ok = false
warning(format("skipping invalid patch for %s",
files.source[nextfileno+1]))
table.remove(files.source, nextfileno+1)
-- double source filename line is encountered
-- attempt to restart from this second line
end
-- Accept a space as a terminator, like GNU patch does.
-- Breaks patches containing filenames with spaces...
-- FIXME Figure out what does GNU patch do in those cases.
local match = line:match("^%-%-%- ([^ \t\r\n]+)")
if not match then
all_ok = false
warning(format("skipping invalid filename at line %d", lineno+1))
state = 'header'
else
table.insert(files.source, match)
end
elseif not startswith(line, "+++ ") then
if util.array_contains(files.source, nextfileno) then
all_ok = false
warning(format("skipping invalid patch with no target for %s",
files.source[nextfileno+1]))
table.remove(files.source, nextfileno+1)
else
-- this should be unreachable
warning("skipping invalid target patch")
end
state = 'header'
else
if util.array_contains(files.target, nextfileno) then
all_ok = false
warning(format("skipping invalid patch - double target at line %d",
lineno+1))
table.remove(files.source, nextfileno+1)
table.remove(files.target, nextfileno+1)
nextfileno = nextfileno - 1
-- double target filename line is encountered
-- switch back to header state
state = 'header'
else
-- Accept a space as a terminator, like GNU patch does.
-- Breaks patches containing filenames with spaces...
-- FIXME Figure out what does GNU patch do in those cases.
local re_filename = "^%+%+%+ ([^ \t\r\n]+)"
local match = line:match(re_filename)
if not match then
all_ok = false
warning(format(
"skipping invalid patch - no target filename at line %d",
lineno+1))
state = 'header'
else
table.insert(files.target, match)
nextfileno = nextfileno + 1
nexthunkno = 0
table.insert(files.hunks, {})
table.insert(files.hunkends, table_copy(lineends))
table.insert(files.fileends, table_copy(lineends))
state = 'hunkhead'
advance = true
end
end
end
-- state is 'filenames', 'header', or ('hunkhead' with advance)
end
if not advance and state == 'hunkhead' then
local m1, m2, m3, m4 = match_linerange(line)
if not m1 then
if not util.array_contains(files.hunks, nextfileno-1) then
all_ok = false
warning(format("skipping invalid patch with no hunks for file %s",
files.target[nextfileno]))
end
state = 'header'
else
hunkinfo.startsrc = tonumber(m1)
hunkinfo.linessrc = tonumber(m2 or 1)
hunkinfo.starttgt = tonumber(m3)
hunkinfo.linestgt = tonumber(m4 or 1)
hunkinfo.invalid = false
hunkinfo.text = {}
hunkactual.linessrc = 0
hunkactual.linestgt = 0
state = 'hunkbody'
nexthunkno = nexthunkno + 1
end
-- state is 'header' or 'hunkbody'
end
end
if state ~= 'hunkskip' then
warning(format("patch file incomplete - %s", filename))
all_ok = false
-- os.exit(?)
else
-- duplicated message when an eof is reached
if debugmode and #files.source > 0 then
debug(format("- %2d hunks for %s", #files.hunks[nextfileno],
files.source[nextfileno]))
end
end
local sum = 0; for _,hset in ipairs(files.hunks) do sum = sum + #hset end
info(format("total files: %d total hunks: %d", #files.source, sum))
fp:close()
return files, all_ok
end
local function find_hunk(file, h, hno)
for fuzz=0,2 do
local lineno = h.startsrc
for i=0,#file do
local found = true
local location = lineno
for l, hline in ipairs(h.text) do
if l > fuzz then
-- todo: \ No newline at the end of file
if startswith(hline, " ") or startswith(hline, "-") then
local line = file[lineno]
lineno = lineno + 1
if not line or #line == 0 then
found = false
break
end
if endlstrip(line) ~= endlstrip(hline:sub(2)) then
found = false
break
end
end
end
end
if found then
local offset = location - h.startsrc - fuzz
if offset ~= 0 then
warning(format("Hunk %d found at offset %d%s...", hno, offset, fuzz == 0 and "" or format(" (fuzz %d)", fuzz)))
end
h.startsrc = location
h.starttgt = h.starttgt + offset
for _=1,fuzz do
table.remove(h.text, 1)
table.remove(h.text, #h.text)
end
return true
end
lineno = i
end
end
return false
end
local function load_file(filename)
local fp = assert(io.open(filename))
local file = {}
local readline = file_lines(fp)
while true do
local line = readline()
if not line then break end
table.insert(file, line)
end
fp:close()
return file
end
local function find_hunks(file, hunks)
for hno, h in ipairs(hunks) do
find_hunk(file, h, hno)
end
end
local function check_patched(file, hunks)
local lineno = 1
local ok, err = pcall(function()
if #file == 0 then
error('nomatch', 0)
end
for hno, h in ipairs(hunks) do
-- skip to line just before hunk starts
if #file < h.starttgt then
error('nomatch', 0)
end
lineno = h.starttgt
for _, hline in ipairs(h.text) do
-- todo: \ No newline at the end of file
if not startswith(hline, "-") and not startswith(hline, "\\") then
local line = file[lineno]
lineno = lineno + 1
if #line == 0 then
error('nomatch', 0)
end
if endlstrip(line) ~= endlstrip(hline:sub(2)) then
warning(format("file is not patched - failed hunk: %d", hno))
error('nomatch', 0)
end
end
end
end
end)
-- todo: display failed hunk, i.e. expected/found
return err ~= 'nomatch'
end
local function patch_hunks(srcname, tgtname, hunks)
local src = assert(io.open(srcname, "rb"))
local tgt = assert(io.open(tgtname, "wb"))
local src_readline = file_lines(src)
-- todo: detect linefeeds early - in apply_files routine
-- to handle cases when patch starts right from the first
-- line and no lines are processed. At the moment substituted
-- lineends may not be the same at the start and at the end
-- of patching. Also issue a warning about mixed lineends
local srclineno = 1
local lineends = {['\n']=0, ['\r\n']=0, ['\r']=0}
for hno, h in ipairs(hunks) do
debug(format("processing hunk %d for file %s", hno, tgtname))
-- skip to line just before hunk starts
while srclineno < h.startsrc do
local line = src_readline()
-- Python 'U' mode works only with text files
if endswith(line, "\r\n") then
lineends["\r\n"] = lineends["\r\n"] + 1
elseif endswith(line, "\n") then
lineends["\n"] = lineends["\n"] + 1
elseif endswith(line, "\r") then
lineends["\r"] = lineends["\r"] + 1
end
tgt:write(line)
srclineno = srclineno + 1
end
for _,hline in ipairs(h.text) do
-- todo: check \ No newline at the end of file
if startswith(hline, "-") or startswith(hline, "\\") then
src_readline()
srclineno = srclineno + 1
else
if not startswith(hline, "+") then
src_readline()
srclineno = srclineno + 1
end
local line2write = hline:sub(2)
-- detect if line ends are consistent in source file
local sum = 0
for _,v in pairs(lineends) do if v > 0 then sum=sum+1 end end
if sum == 1 then
local newline
for k,v in pairs(lineends) do if v ~= 0 then newline = k end end
tgt:write(endlstrip(line2write) .. newline)
else -- newlines are mixed or unknown
tgt:write(line2write)
end
end
end
end
for line in src_readline do
tgt:write(line)
end
tgt:close()
src:close()
return true
end
local function strip_dirs(filename, strip)
if strip == nil then return filename end
for _=1,strip do
filename=filename:gsub("^[^/]*/", "")
end
return filename
end
function patch.apply_patch(the_patch, strip)
local all_ok = true
local total = #the_patch.source
for fileno, filename in ipairs(the_patch.source) do
filename = strip_dirs(filename, strip)
local continue
local f2patch = filename
if not exists(f2patch) then
f2patch = strip_dirs(the_patch.target[fileno], strip)
f2patch = fs.absolute_name(f2patch)
if not exists(f2patch) then --FIX:if f2patch nil
warning(format("source/target file does not exist\n--- %s\n+++ %s",
filename, f2patch))
all_ok = false
continue = true
end
end
if not continue and not isfile(f2patch) then
warning(format("not a file - %s", f2patch))
all_ok = false
continue = true
end
if not continue then
filename = f2patch
info(format("processing %d/%d:\t %s", fileno, total, filename))
-- validate before patching
local hunks = the_patch.hunks[fileno]
local file = load_file(filename)
local hunkno = 1
local hunk = hunks[hunkno]
local hunkfind = {}
local validhunks = 0
local canpatch = false
local hunklineno
local isbreak
local lineno = 0
find_hunks(file, hunks)
for _, line in ipairs(file) do
lineno = lineno + 1
local continue
if not hunk or lineno < hunk.startsrc then
continue = true
elseif lineno == hunk.startsrc then
hunkfind = {}
for _,x in ipairs(hunk.text) do
if x:sub(1,1) == ' ' or x:sub(1,1) == '-' then
hunkfind[#hunkfind+1] = endlstrip(x:sub(2))
end
end
hunklineno = 1
-- todo \ No newline at end of file
end
-- check hunks in source file
if not continue and lineno < hunk.startsrc + #hunkfind - 1 then
if endlstrip(line) == hunkfind[hunklineno] then
hunklineno = hunklineno + 1
else
debug(format("hunk no.%d doesn't match source file %s",
hunkno, filename))
-- file may be already patched, but check other hunks anyway
hunkno = hunkno + 1
if hunkno <= #hunks then
hunk = hunks[hunkno]
continue = true
else
isbreak = true; break
end
end
end
-- check if processed line is the last line
if not continue and lineno == hunk.startsrc + #hunkfind - 1 then
debug(format("file %s hunk no.%d -- is ready to be patched",
filename, hunkno))
hunkno = hunkno + 1
validhunks = validhunks + 1
if hunkno <= #hunks then
hunk = hunks[hunkno]
else
if validhunks == #hunks then
-- patch file
canpatch = true
isbreak = true; break
end
end
end
end
if not isbreak then
if hunkno <= #hunks then
warning(format("premature end of source file %s at hunk %d",
filename, hunkno))
all_ok = false
end
end
if validhunks < #hunks then
if check_patched(file, hunks) then
warning(format("already patched %s", filename))
else
warning(format("source file is different - %s", filename))
all_ok = false
end
end
if canpatch then
local backupname = filename .. ".orig"
if exists(backupname) then
warning(format("can't backup original file to %s - aborting",
backupname))
all_ok = false
else
assert(os.rename(filename, backupname))
if patch_hunks(backupname, filename, hunks) then
warning(format("successfully patched %s", filename))
assert(os.remove(backupname))
else
warning(format("error patching file %s", filename))
assert(file_copy(filename, filename .. ".invalid"))
warning(format("invalid version is saved to %s",
filename .. ".invalid"))
-- todo: proper rejects
assert(os.rename(backupname, filename))
all_ok = false
end
end
end
end -- if not continue
end -- for
-- todo: check for premature eof
return all_ok
end
return patch
luarocks-2.4.2+dfsg/src/luarocks/tools/tar.lua 0000664 0000000 0000000 00000011304 13030154704 0021320 0 ustar 00root root 0000000 0000000
--- A pure-Lua implementation of untar (unpacking .tar archives)
local tar = {}
local fs = require("luarocks.fs")
local dir = require("luarocks.dir")
local util = require("luarocks.util")
local blocksize = 512
local function get_typeflag(flag)
if flag == "0" or flag == "\0" then return "file"
elseif flag == "1" then return "link"
elseif flag == "2" then return "symlink" -- "reserved" in POSIX, "symlink" in GNU
elseif flag == "3" then return "character"
elseif flag == "4" then return "block"
elseif flag == "5" then return "directory"
elseif flag == "6" then return "fifo"
elseif flag == "7" then return "contiguous" -- "reserved" in POSIX, "contiguous" in GNU
elseif flag == "x" then return "next file"
elseif flag == "g" then return "global extended header"
elseif flag == "L" then return "long name"
elseif flag == "K" then return "long link name"
end
return "unknown"
end
local function octal_to_number(octal)
local exp = 0
local number = 0
for i = #octal,1,-1 do
local digit = tonumber(octal:sub(i,i))
if digit then
number = number + (digit * 8^exp)
exp = exp + 1
end
end
return number
end
local function checksum_header(block)
local sum = 256
for i = 1,148 do
sum = sum + block:byte(i)
end
for i = 157,500 do
sum = sum + block:byte(i)
end
return sum
end
local function nullterm(s)
return s:match("^[^%z]*")
end
local function read_header_block(block)
local header = {}
header.name = nullterm(block:sub(1,100))
header.mode = nullterm(block:sub(101,108))
header.uid = octal_to_number(nullterm(block:sub(109,116)))
header.gid = octal_to_number(nullterm(block:sub(117,124)))
header.size = octal_to_number(nullterm(block:sub(125,136)))
header.mtime = octal_to_number(nullterm(block:sub(137,148)))
header.chksum = octal_to_number(nullterm(block:sub(149,156)))
header.typeflag = get_typeflag(block:sub(157,157))
header.linkname = nullterm(block:sub(158,257))
header.magic = block:sub(258,263)
header.version = block:sub(264,265)
header.uname = nullterm(block:sub(266,297))
header.gname = nullterm(block:sub(298,329))
header.devmajor = octal_to_number(nullterm(block:sub(330,337)))
header.devminor = octal_to_number(nullterm(block:sub(338,345)))
header.prefix = block:sub(346,500)
if header.magic ~= "ustar " and header.magic ~= "ustar\0" then
return false, "Invalid header magic "..header.magic
end
if header.version ~= "00" and header.version ~= " \0" then
return false, "Unknown version "..header.version
end
if not checksum_header(block) == header.chksum then
return false, "Failed header checksum"
end
return header
end
function tar.untar(filename, destdir)
assert(type(filename) == "string")
assert(type(destdir) == "string")
local tar_handle = io.open(filename, "r")
if not tar_handle then return nil, "Error opening file "..filename end
local long_name, long_link_name
while true do
local block
repeat
block = tar_handle:read(blocksize)
until (not block) or checksum_header(block) > 256
if not block then break end
local header, err = read_header_block(block)
if not header then
util.printerr(err)
end
local file_data = tar_handle:read(math.ceil(header.size / blocksize) * blocksize):sub(1,header.size)
if header.typeflag == "long name" then
long_name = nullterm(file_data)
elseif header.typeflag == "long link name" then
long_link_name = nullterm(file_data)
else
if long_name then
header.name = long_name
long_name = nil
end
if long_link_name then
header.name = long_link_name
long_link_name = nil
end
end
local pathname = dir.path(destdir, header.name)
if header.typeflag == "directory" then
local ok, err = fs.make_dir(pathname)
if not ok then return nil, err end
elseif header.typeflag == "file" then
local dirname = dir.dir_name(pathname)
if dirname ~= "" then
local ok, err = fs.make_dir(dirname)
if not ok then return nil, err end
end
local file_handle = io.open(pathname, "wb")
file_handle:write(file_data)
file_handle:close()
fs.set_time(pathname, header.mtime)
if fs.chmod then
fs.chmod(pathname, header.mode)
end
end
--[[
for k,v in pairs(header) do
util.printout("[\""..tostring(k).."\"] = "..(type(v)=="number" and v or "\""..v:gsub("%z", "\\0").."\""))
end
util.printout()
--]]
end
tar_handle:close()
return true
end
return tar
luarocks-2.4.2+dfsg/src/luarocks/tools/zip.lua 0000664 0000000 0000000 00000020753 13030154704 0021344 0 ustar 00root root 0000000 0000000
--- A Lua implementation of .zip file archiving (used for creating .rock files),
-- using only lzlib or lua-lzib.
local zip = {}
local zlib = require("zlib")
local fs = require("luarocks.fs")
local dir = require("luarocks.dir")
-- zlib module can be provided by both lzlib and lua-lzib packages.
-- Create a compatibility layer.
local zlib_compress, zlib_crc32
if zlib._VERSION:match "^lua%-zlib" then
function zlib_compress(data)
return (zlib.deflate()(data, "finish"))
end
function zlib_crc32(data)
return zlib.crc32()(data)
end
elseif zlib._VERSION:match "^lzlib" then
function zlib_compress(data)
return zlib.compress(data)
end
function zlib_crc32(data)
return zlib.crc32(zlib.crc32(), data)
end
else
error("unknown zlib library", 0)
end
local function number_to_bytestring(number, nbytes)
local out = {}
for _ = 1, nbytes do
local byte = number % 256
table.insert(out, string.char(byte))
number = (number - byte) / 256
end
return table.concat(out)
end
--- Begin a new file to be stored inside the zipfile.
-- @param self handle of the zipfile being written.
-- @param filename filenome of the file to be added to the zipfile.
-- @return true if succeeded, nil in case of failure.
local function zipwriter_open_new_file_in_zip(self, filename)
if self.in_open_file then
self:close_file_in_zip()
return nil
end
local lfh = {}
self.local_file_header = lfh
lfh.last_mod_file_time = 0 -- TODO
lfh.last_mod_file_date = 0 -- TODO
lfh.file_name_length = #filename
lfh.extra_field_length = 0
lfh.file_name = filename:gsub("\\", "/")
lfh.external_attr = 0 -- TODO properly store permissions
self.in_open_file = true
return true
end
--- Write data to the file currently being stored in the zipfile.
-- @param self handle of the zipfile being written.
-- @param data string containing full contents of the file.
-- @return true if succeeded, nil in case of failure.
local function zipwriter_write_file_in_zip(self, data)
if not self.in_open_file then
return nil
end
local lfh = self.local_file_header
local compressed = zlib_compress(data):sub(3, -5)
lfh.crc32 = zlib_crc32(data)
lfh.compressed_size = #compressed
lfh.uncompressed_size = #data
self.data = compressed
return true
end
--- Complete the writing of a file stored in the zipfile.
-- @param self handle of the zipfile being written.
-- @return true if succeeded, nil in case of failure.
local function zipwriter_close_file_in_zip(self)
local zh = self.ziphandle
if not self.in_open_file then
return nil
end
-- Local file header
local lfh = self.local_file_header
lfh.offset = zh:seek()
zh:write(number_to_bytestring(0x04034b50, 4)) -- signature
zh:write(number_to_bytestring(20, 2)) -- version needed to extract: 2.0
zh:write(number_to_bytestring(0, 2)) -- general purpose bit flag
zh:write(number_to_bytestring(8, 2)) -- compression method: deflate
zh:write(number_to_bytestring(lfh.last_mod_file_time, 2))
zh:write(number_to_bytestring(lfh.last_mod_file_date, 2))
zh:write(number_to_bytestring(lfh.crc32, 4))
zh:write(number_to_bytestring(lfh.compressed_size, 4))
zh:write(number_to_bytestring(lfh.uncompressed_size, 4))
zh:write(number_to_bytestring(lfh.file_name_length, 2))
zh:write(number_to_bytestring(lfh.extra_field_length, 2))
zh:write(lfh.file_name)
-- File data
zh:write(self.data)
-- Data descriptor
zh:write(number_to_bytestring(lfh.crc32, 4))
zh:write(number_to_bytestring(lfh.compressed_size, 4))
zh:write(number_to_bytestring(lfh.uncompressed_size, 4))
table.insert(self.files, lfh)
self.in_open_file = false
return true
end
-- @return boolean or (boolean, string): true on success,
-- false and an error message on failure.
local function zipwriter_add(self, file)
local fin
local ok, err = self:open_new_file_in_zip(file)
if not ok then
err = "error in opening "..file.." in zipfile"
else
fin = io.open(fs.absolute_name(file), "rb")
if not fin then
ok = false
err = "error opening "..file.." for reading"
end
end
if ok then
local data = fin:read("*a")
if not data then
err = "error reading "..file
ok = false
else
ok = self:write_file_in_zip(data)
if not ok then
err = "error in writing "..file.." in the zipfile"
end
end
end
if fin then
fin:close()
end
if ok then
ok = self:close_file_in_zip()
if not ok then
err = "error in writing "..file.." in the zipfile"
end
end
return ok == true, err
end
--- Complete the writing of the zipfile.
-- @param self handle of the zipfile being written.
-- @return true if succeeded, nil in case of failure.
local function zipwriter_close(self)
local zh = self.ziphandle
local central_directory_offset = zh:seek()
local size_of_central_directory = 0
-- Central directory structure
for _, lfh in ipairs(self.files) do
zh:write(number_to_bytestring(0x02014b50, 4)) -- signature
zh:write(number_to_bytestring(3, 2)) -- version made by: UNIX
zh:write(number_to_bytestring(20, 2)) -- version needed to extract: 2.0
zh:write(number_to_bytestring(0, 2)) -- general purpose bit flag
zh:write(number_to_bytestring(8, 2)) -- compression method: deflate
zh:write(number_to_bytestring(lfh.last_mod_file_time, 2))
zh:write(number_to_bytestring(lfh.last_mod_file_date, 2))
zh:write(number_to_bytestring(lfh.crc32, 4))
zh:write(number_to_bytestring(lfh.compressed_size, 4))
zh:write(number_to_bytestring(lfh.uncompressed_size, 4))
zh:write(number_to_bytestring(lfh.file_name_length, 2))
zh:write(number_to_bytestring(lfh.extra_field_length, 2))
zh:write(number_to_bytestring(0, 2)) -- file comment length
zh:write(number_to_bytestring(0, 2)) -- disk number start
zh:write(number_to_bytestring(0, 2)) -- internal file attributes
zh:write(number_to_bytestring(lfh.external_attr, 4)) -- external file attributes
zh:write(number_to_bytestring(lfh.offset, 4)) -- relative offset of local header
zh:write(lfh.file_name)
size_of_central_directory = size_of_central_directory + 46 + lfh.file_name_length
end
-- End of central directory record
zh:write(number_to_bytestring(0x06054b50, 4)) -- signature
zh:write(number_to_bytestring(0, 2)) -- number of this disk
zh:write(number_to_bytestring(0, 2)) -- number of disk with start of central directory
zh:write(number_to_bytestring(#self.files, 2)) -- total number of entries in the central dir on this disk
zh:write(number_to_bytestring(#self.files, 2)) -- total number of entries in the central dir
zh:write(number_to_bytestring(size_of_central_directory, 4))
zh:write(number_to_bytestring(central_directory_offset, 4))
zh:write(number_to_bytestring(0, 2)) -- zip file comment length
zh:close()
return true
end
--- Return a zip handle open for writing.
-- @param name filename of the zipfile to be created.
-- @return a zip handle, or nil in case of error.
function zip.new_zipwriter(name)
local zw = {}
zw.ziphandle = io.open(fs.absolute_name(name), "wb")
if not zw.ziphandle then
return nil
end
zw.files = {}
zw.in_open_file = false
zw.add = zipwriter_add
zw.close = zipwriter_close
zw.open_new_file_in_zip = zipwriter_open_new_file_in_zip
zw.write_file_in_zip = zipwriter_write_file_in_zip
zw.close_file_in_zip = zipwriter_close_file_in_zip
return zw
end
--- Compress files in a .zip archive.
-- @param zipfile string: pathname of .zip archive to be created.
-- @param ... Filenames to be stored in the archive are given as
-- additional arguments.
-- @return boolean or (boolean, string): true on success,
-- false and an error message on failure.
function zip.zip(zipfile, ...)
local zw = zip.new_zipwriter(zipfile)
if not zw then
return nil, "error opening "..zipfile
end
local ok, err
for _, file in pairs({...}) do
if fs.is_dir(file) then
for _, entry in pairs(fs.find(file)) do
local fullname = dir.path(file, entry)
if fs.is_file(fullname) then
ok, err = zw:add(fullname)
if not ok then break end
end
end
else
ok, err = zw:add(file)
if not ok then break end
end
end
ok = zw:close()
if not ok then
return false, "error closing "..zipfile
end
return ok, err
end
return zip
luarocks-2.4.2+dfsg/src/luarocks/type_check.lua 0000664 0000000 0000000 00000026367 13030154704 0021527 0 ustar 00root root 0000000 0000000 --- Type-checking functions.
-- Functions and definitions for doing a basic lint check on files
-- loaded by LuaRocks.
local type_check = {}
package.loaded["luarocks.type_check"] = type_check
local cfg = require("luarocks.cfg")
local deps = require("luarocks.deps")
type_check.rockspec_format = "1.1"
local string_1 = { _type = "string" }
local number_1 = { _type = "number" }
local mandatory_string_1 = { _type = "string", _mandatory = true }
-- Syntax for type-checking tables:
--
-- A type-checking table describes typing data for a value.
-- Any key starting with an underscore has a special meaning:
-- _type (string) is the Lua type of the value. Default is "table".
-- _version (string) is the minimum rockspec_version that supports this value. Default is "1.0".
-- _mandatory (boolean) indicates if the value is a mandatory key in its container table. Default is false.
-- For "string" types only:
-- _pattern (string) is the string-matching pattern, valid for string types only. Default is ".*".
-- For "table" types only:
-- _any (table) is the type-checking table for unspecified keys, recursively checked.
-- _more (boolean) indicates that the table accepts unspecified keys and does not type-check them.
-- Any other string keys that don't start with an underscore represent known keys and are type-checking tables, recursively checked.
local rockspec_types = {
rockspec_format = string_1,
package = mandatory_string_1,
version = { _type = "string", _pattern = "[%w.]+-[%d]+", _mandatory = true },
description = {
summary = string_1,
detailed = string_1,
homepage = string_1,
license = string_1,
maintainer = string_1,
},
dependencies = {
platforms = {}, -- recursively defined below
_any = string_1,
},
supported_platforms = {
_any = string_1,
},
external_dependencies = {
platforms = {}, -- recursively defined below
_any = {
program = string_1,
header = string_1,
library = string_1,
}
},
source = {
_mandatory = true,
platforms = {}, -- recursively defined below
url = mandatory_string_1,
md5 = string_1,
file = string_1,
dir = string_1,
tag = string_1,
branch = string_1,
module = string_1,
cvs_tag = string_1,
cvs_module = string_1,
},
build = {
platforms = {}, -- recursively defined below
type = string_1,
install = {
lua = {
_more = true
},
lib = {
_more = true
},
conf = {
_more = true
},
bin = {
_more = true
}
},
copy_directories = {
_any = string_1,
},
_more = true,
_mandatory = true
},
hooks = {
platforms = {}, -- recursively defined below
post_install = string_1,
},
deploy = {
_version = "1.1",
wrap_bin_scripts = { _type = "boolean", _version = "1.1" },
}
}
type_check.rockspec_order = {"rockspec_format", "package", "version",
{ "source", { "url", "tag", "branch", "md5" } },
{ "description", {"summary", "detailed", "homepage", "license" } },
"supported_platforms", "dependencies", "external_dependencies",
{ "build", {"type", "modules", "copy_directories", "platforms"} },
"hooks"}
rockspec_types.build.platforms._any = rockspec_types.build
rockspec_types.dependencies.platforms._any = rockspec_types.dependencies
rockspec_types.external_dependencies.platforms._any = rockspec_types.external_dependencies
rockspec_types.source.platforms._any = rockspec_types.source
rockspec_types.hooks.platforms._any = rockspec_types.hooks
local manifest_types = {
repository = {
_mandatory = true,
-- packages
_any = {
-- versions
_any = {
-- items
_any = {
arch = mandatory_string_1,
modules = { _any = string_1 },
commands = { _any = string_1 },
dependencies = { _any = string_1 },
-- TODO: to be extended with more metadata.
}
}
}
},
modules = {
_mandatory = true,
-- modules
_any = {
-- providers
_any = string_1
}
},
commands = {
_mandatory = true,
-- modules
_any = {
-- commands
_any = string_1
}
},
dependencies = {
-- each module
_any = {
-- each version
_any = {
-- each dependency
_any = {
name = string_1,
constraints = {
_any = {
no_upgrade = { _type = "boolean" },
op = string_1,
version = {
string = string_1,
_any = number_1,
}
}
}
}
}
}
}
}
local function check_version(version, typetbl, context)
local typetbl_version = typetbl._version or "1.0"
if deps.compare_versions(typetbl_version, version) then
if context == "" then
return nil, "Invalid rockspec_format version number in rockspec? Please fix rockspec accordingly."
else
return nil, context.." is not supported in rockspec format "..version.." (requires version "..typetbl_version.."), please fix the rockspec_format field accordingly."
end
end
return true
end
local type_check_table
--- Type check an object.
-- The object is compared against an archetypical value
-- matching the expected type -- the actual values don't matter,
-- only their types. Tables are type checked recursively.
-- @param version string: The version of the item.
-- @param item any: The object being checked.
-- @param typetbl any: The type-checking table for the object.
-- @param context string: A string indicating the "context" where the
-- error occurred (the full table path), for error messages.
-- @return boolean or (nil, string): true if type checking
-- succeeded, or nil and an error message if it failed.
-- @see type_check_table
local function type_check_item(version, item, typetbl, context)
assert(type(version) == "string")
local ok, err = check_version(version, typetbl, context)
if not ok then
return nil, err
end
local item_type = type(item) or "nil"
local expected_type = typetbl._type or "table"
if expected_type == "number" then
if not tonumber(item) then
return nil, "Type mismatch on field "..context..": expected a number"
end
elseif expected_type == "string" then
if item_type ~= "string" then
return nil, "Type mismatch on field "..context..": expected a string, got "..item_type
end
if typetbl._pattern then
if not item:match("^"..typetbl._pattern.."$") then
return nil, "Type mismatch on field "..context..": invalid value "..item.." does not match '"..typetbl._pattern.."'"
end
end
elseif expected_type == "table" then
if item_type ~= expected_type then
return nil, "Type mismatch on field "..context..": expected a table"
else
return type_check_table(version, item, typetbl, context)
end
elseif item_type ~= expected_type then
return nil, "Type mismatch on field "..context..": expected "..expected_type
end
return true
end
local function mkfield(context, field)
if context == "" then
return tostring(field)
elseif type(field) == "string" then
return context.."."..field
else
return context.."["..tostring(field).."]"
end
end
--- Type check the contents of a table.
-- The table's contents are compared against a reference table,
-- which contains the recognized fields, with archetypical values
-- matching the expected types -- the actual values of items in the
-- reference table don't matter, only their types (ie, for field x
-- in tbl that is correctly typed, type(tbl.x) == type(types.x)).
-- If the reference table contains a field called MORE, then
-- unknown fields in the checked table are accepted.
-- If it contains a field called ANY, then its type will be
-- used to check any unknown fields. If a field is prefixed
-- with MUST_, it is mandatory; its absence from the table is
-- a type error.
-- Tables are type checked recursively.
-- @param version string: The version of tbl.
-- @param tbl table: The table to be type checked.
-- @param typetbl table: The type-checking table, containing
-- values for recognized fields in the checked table.
-- @param context string: A string indicating the "context" where the
-- error occurred (such as the name of the table the item is a part of),
-- to be used by error messages.
-- @return boolean or (nil, string): true if type checking
-- succeeded, or nil and an error message if it failed.
type_check_table = function(version, tbl, typetbl, context)
assert(type(version) == "string")
assert(type(tbl) == "table")
assert(type(typetbl) == "table")
local ok, err = check_version(version, typetbl, context)
if not ok then
return nil, err
end
for k, v in pairs(tbl) do
local t = typetbl[k] or typetbl._any
if t then
local ok, err = type_check_item(version, v, t, mkfield(context, k))
if not ok then return nil, err end
elseif typetbl._more then
-- Accept unknown field
else
if not cfg.accept_unknown_fields then
return nil, "Unknown field "..k
end
end
end
for k, v in pairs(typetbl) do
if k:sub(1,1) ~= "_" and v._mandatory then
if not tbl[k] then
return nil, "Mandatory field "..mkfield(context, k).." is missing."
end
end
end
return true
end
local function check_undeclared_globals(globals, typetbl)
local undeclared = {}
for glob, _ in pairs(globals) do
if not (typetbl[glob] or typetbl["MUST_"..glob]) then
table.insert(undeclared, glob)
end
end
if #undeclared == 1 then
return nil, "Unknown variable: "..undeclared[1]
elseif #undeclared > 1 then
return nil, "Unknown variables: "..table.concat(undeclared, ", ")
end
return true
end
--- Type check a rockspec table.
-- Verify the correctness of elements from a
-- rockspec table, reporting on unknown fields and type
-- mismatches.
-- @return boolean or (nil, string): true if type checking
-- succeeded, or nil and an error message if it failed.
function type_check.type_check_rockspec(rockspec, globals)
assert(type(rockspec) == "table")
if not rockspec.rockspec_format then
rockspec.rockspec_format = "1.0"
end
local ok, err = check_undeclared_globals(globals, rockspec_types)
if not ok then return nil, err end
return type_check_table(rockspec.rockspec_format, rockspec, rockspec_types, "")
end
--- Type check a manifest table.
-- Verify the correctness of elements from a
-- manifest table, reporting on unknown fields and type
-- mismatches.
-- @return boolean or (nil, string): true if type checking
-- succeeded, or nil and an error message if it failed.
function type_check.type_check_manifest(manifest, globals)
assert(type(manifest) == "table")
local ok, err = check_undeclared_globals(globals, manifest_types)
if not ok then return nil, err end
return type_check_table("1.0", manifest, manifest_types, "")
end
return type_check
luarocks-2.4.2+dfsg/src/luarocks/unpack.lua 0000664 0000000 0000000 00000013767 13030154704 0020672 0 ustar 00root root 0000000 0000000
--- Module implementing the LuaRocks "unpack" command.
-- Unpack the contents of a rock.
local unpack = {}
package.loaded["luarocks.unpack"] = unpack
local fetch = require("luarocks.fetch")
local fs = require("luarocks.fs")
local util = require("luarocks.util")
local build = require("luarocks.build")
local dir = require("luarocks.dir")
local cfg = require("luarocks.cfg")
util.add_run_function(unpack)
unpack.help_summary = "Unpack the contents of a rock."
unpack.help_arguments = "[--force] {| []}"
unpack.help = [[
Unpacks the contents of a rock in a newly created directory.
Argument may be a rock file, or the name of a rock in a rocks server.
In the latter case, the app version may be given as a second argument.
--force Unpack files even if the output directory already exists.
]]
--- Load a rockspec file to the given directory, fetches the source
-- files specified in the rockspec, and unpack them inside the directory.
-- @param rockspec_file string: The URL for a rockspec file.
-- @param dir_name string: The directory where to store and unpack files.
-- @return table or (nil, string): the loaded rockspec table or
-- nil and an error message.
local function unpack_rockspec(rockspec_file, dir_name)
assert(type(rockspec_file) == "string")
assert(type(dir_name) == "string")
local rockspec, err = fetch.load_rockspec(rockspec_file)
if not rockspec then
return nil, "Failed loading rockspec "..rockspec_file..": "..err
end
local ok, err = fs.change_dir(dir_name)
if not ok then return nil, err end
local ok, sources_dir = fetch.fetch_sources(rockspec, true, ".")
if not ok then
return nil, sources_dir
end
ok, err = fs.change_dir(sources_dir)
if not ok then return nil, err end
ok, err = build.apply_patches(rockspec)
fs.pop_dir()
if not ok then return nil, err end
return rockspec
end
--- Load a .rock file to the given directory and unpack it inside it.
-- @param rock_file string: The URL for a .rock file.
-- @param dir_name string: The directory where to unpack.
-- @param kind string: the kind of rock file, as in the second-level
-- extension in the rock filename (eg. "src", "all", "linux-x86")
-- @return table or (nil, string): the loaded rockspec table or
-- nil and an error message.
local function unpack_rock(rock_file, dir_name, kind)
assert(type(rock_file) == "string")
assert(type(dir_name) == "string")
local ok, err, errcode = fetch.fetch_and_unpack_rock(rock_file, dir_name)
if not ok then
return nil, "Failed unzipping rock "..rock_file, errcode
end
ok, err = fs.change_dir(dir_name)
if not ok then return nil, err end
local rockspec_file = dir_name..".rockspec"
local rockspec, err = fetch.load_rockspec(rockspec_file)
if not rockspec then
return nil, "Failed loading rockspec "..rockspec_file..": "..err
end
if kind == "src" then
if rockspec.source.file then
local ok, err = fs.unpack_archive(rockspec.source.file)
if not ok then
return nil, err
end
ok, err = fs.change_dir(rockspec.source.dir)
if not ok then return nil, err end
ok, err = build.apply_patches(rockspec)
fs.pop_dir()
if not ok then return nil, err end
end
end
return rockspec
end
--- Create a directory and perform the necessary actions so that
-- the sources for the rock and its rockspec are unpacked inside it,
-- laid out properly so that the 'make' command is able to build the module.
-- @param file string: A rockspec or .rock URL.
-- @return boolean or (nil, string): true if successful or nil followed
-- by an error message.
local function run_unpacker(file, force)
assert(type(file) == "string")
local base_name = dir.base_name(file)
local dir_name, kind, extension = base_name:match("(.*)%.([^.]+)%.(rock)$")
if not extension then
dir_name, extension = base_name:match("(.*)%.(rockspec)$")
kind = "rockspec"
end
if not extension then
return nil, file.." does not seem to be a valid filename."
end
local exists = fs.exists(dir_name)
if exists and not force then
return nil, "Directory "..dir_name.." already exists."
end
if not exists then
local ok, err = fs.make_dir(dir_name)
if not ok then return nil, err end
end
local rollback = util.schedule_function(fs.delete, fs.absolute_name(dir_name))
local rockspec, err
if extension == "rock" then
rockspec, err = unpack_rock(file, dir_name, kind)
elseif extension == "rockspec" then
rockspec, err = unpack_rockspec(file, dir_name)
end
if not rockspec then
return nil, err
end
if kind == "src" or kind == "rockspec" then
if rockspec.source.dir ~= "." then
local ok = fs.copy(rockspec.local_filename, rockspec.source.dir, cfg.perm_read)
if not ok then
return nil, "Failed copying unpacked rockspec into unpacked source directory."
end
end
util.printout()
util.printout("Done. You may now enter directory ")
util.printout(dir.path(dir_name, rockspec.source.dir))
util.printout("and type 'luarocks make' to build.")
end
util.remove_scheduled_function(rollback)
return true
end
--- Driver function for the "unpack" command.
-- @param name string: may be a rock filename, for unpacking a
-- rock file or the name of a rock to be fetched and unpacked.
-- @param version string or nil: if the name of a package is given, a
-- version may also be passed.
-- @return boolean or (nil, string): true if successful or nil followed
-- by an error message.
function unpack.command(flags, name, version)
assert(type(version) == "string" or not version)
if type(name) ~= "string" then
return nil, "Argument missing. "..util.see_help("unpack")
end
if name:match(".*%.rock") or name:match(".*%.rockspec") then
return run_unpacker(name, flags["force"])
else
local search = require("luarocks.search")
return search.act_on_src_or_rockspec(run_unpacker, name:lower(), version)
end
end
return unpack
luarocks-2.4.2+dfsg/src/luarocks/upload.lua 0000664 0000000 0000000 00000005706 13030154704 0020667 0 ustar 00root root 0000000 0000000
local upload = {}
local util = require("luarocks.util")
local fetch = require("luarocks.fetch")
local pack = require("luarocks.pack")
local cfg = require("luarocks.cfg")
local Api = require("luarocks.upload.api")
util.add_run_function(upload)
upload.help_summary = "Upload a rockspec to the public rocks repository."
upload.help_arguments = "[--skip-pack] [--api-key=] [--force] "
upload.help = [[
Pack a source rock file (.src.rock extension),
upload rockspec and source rock to server.
--skip-pack Do not pack and send source rock.
--api-key= Give it an API key. It will be stored for subsequent uses.
--force Replace existing rockspec if the same revision of
a module already exists. This should be used only
in case of upload mistakes: when updating a rockspec,
increment the revision number instead.
]]
function upload.command(flags, fname)
if not fname then
return nil, "Missing rockspec. "..util.see_help("upload")
end
local api, err = Api.new(flags)
if not api then
return nil, err
end
if cfg.verbose then
api.debug = true
end
local rockspec, err, errcode = fetch.load_rockspec(fname)
if err then
return nil, err, errcode
end
util.printout("Sending " .. tostring(fname) .. " ...")
local res, err = api:method("check_rockspec", {
package = rockspec.package,
version = rockspec.version
})
if not res then return nil, err end
if not res.module then
util.printout("Will create new module (" .. tostring(rockspec.package) .. ")")
end
if res.version and not flags["force"] then
return nil, "Revision "..rockspec.version.." already exists on the server. "..util.see_help("upload")
end
local rock_fname
if not flags["skip-pack"] and not rockspec.version:match("^scm") then
util.printout("Packing " .. tostring(rockspec.package))
rock_fname, err = pack.pack_source_rock(fname)
if not rock_fname then
return nil, err
end
end
local multipart = require("luarocks.upload.multipart")
res, err = api:method("upload", nil, {
rockspec_file = multipart.new_file(fname)
})
if not res then return nil, err end
if res.is_new and #res.manifests == 0 then
util.printerr("Warning: module not added to root manifest due to name taken.")
end
local module_url = res.module_url
if rock_fname then
if (not res.version) or (not res.version.id) then
return nil, "Invalid response from server."
end
util.printout(("Sending " .. tostring(rock_fname) .. " ..."))
res, err = api:method("upload_rock/" .. ("%d"):format(res.version.id), nil, {
rock_file = multipart.new_file(rock_fname)
})
if not res then return nil, err end
end
util.printout()
util.printout("Done: " .. tostring(module_url))
util.printout()
return true
end
return upload
luarocks-2.4.2+dfsg/src/luarocks/upload/ 0000775 0000000 0000000 00000000000 13030154704 0020154 5 ustar 00root root 0000000 0000000 luarocks-2.4.2+dfsg/src/luarocks/upload/api.lua 0000664 0000000 0000000 00000020525 13030154704 0021434 0 ustar 00root root 0000000 0000000
local api = {}
local cfg = require("luarocks.cfg")
local fs = require("luarocks.fs")
local util = require("luarocks.util")
local persist = require("luarocks.persist")
local multipart = require("luarocks.upload.multipart")
local Api = {}
local function upload_config_file()
local conf = cfg.which_config()
if not conf.user.file then
return nil
end
return (conf.user.file:gsub("/[^/]+$", "/upload_config.lua"))
end
function Api:load_config()
local upload_conf = upload_config_file()
if not upload_conf then return nil end
local cfg, err = persist.load_into_table(upload_conf)
return cfg
end
function Api:save_config()
-- Test configuration before saving it.
local res, err = self:raw_method("status")
if not res then
return nil, err
end
if res.errors then
util.printerr("Server says: " .. tostring(res.errors[1]))
return
end
local upload_conf = upload_config_file()
if not upload_conf then return nil end
persist.save_from_table(upload_conf, self.config)
fs.chmod(upload_conf, "0600")
end
function Api:check_version()
if not self._server_tool_version then
local tool_version = cfg.upload.tool_version
local res, err = self:request(tostring(self.config.server) .. "/api/tool_version", {
current = tool_version
})
if not res then
return nil, err
end
if not res.version then
return nil, "failed to fetch tool version"
end
self._server_tool_version = res.version
if res.force_update then
return nil, "Your upload client is too out of date to continue, please upgrade LuaRocks."
end
if res.version ~= tool_version then
util.printerr("Warning: Your LuaRocks is out of date, consider upgrading.")
end
end
return true
end
function Api:method(...)
local res, err = self:raw_method(...)
if not res then
return nil, err
end
if res.errors then
if res.errors[1] == "Invalid key" then
return nil, res.errors[1] .. " (use the --api-key flag to change)"
end
local msg = table.concat(res.errors, ", ")
return nil, "API Failed: " .. msg
end
return res
end
function Api:raw_method(path, ...)
self:check_version()
local url = tostring(self.config.server) .. "/api/" .. tostring(cfg.upload.api_version) .. "/" .. tostring(self.config.key) .. "/" .. tostring(path)
return self:request(url, ...)
end
local function encode_query_string(t, sep)
if sep == nil then
sep = "&"
end
local i = 0
local buf = { }
for k, v in pairs(t) do
if type(k) == "number" and type(v) == "table" then
k, v = v[1], v[2]
end
buf[i + 1] = multipart.url_escape(k)
buf[i + 2] = "="
buf[i + 3] = multipart.url_escape(v)
buf[i + 4] = sep
i = i + 4
end
buf[i] = nil
return table.concat(buf)
end
-- An ode to the multitude of JSON libraries out there...
local function require_json()
local list = { "cjson", "dkjson", "json" }
for _, lib in ipairs(list) do
local json_ok, json = pcall(require, lib)
if json_ok then
pcall(json.use_lpeg) -- optional feature in dkjson
return json_ok, json
end
end
local errmsg = "Failed loading "
for i, name in ipairs(list) do
if i == #list then
errmsg = errmsg .."and '"..name.."'. Use 'luarocks search ' to search for a library and 'luarocks install ' to install one."
else
errmsg = errmsg .."'"..name.."', "
end
end
return nil, errmsg
end
local function redact_api_url(url)
url = tostring(url)
return (url:gsub(".*/api/[^/]+/[^/]+", "")) or ""
end
local ltn12_ok, ltn12 = pcall(require, "ltn12")
if not ltn12_ok then -- If not using LuaSocket and/or LuaSec...
function Api:request(url, params, post_params)
local vars = cfg.variables
local json_ok, json = require_json()
if not json_ok then return nil, "A JSON library is required for this command. "..json end
if cfg.downloader == "wget" then
local curl_ok, err = fs.is_tool_available(vars.CURL, "curl")
if not curl_ok then
return nil, err
end
end
if not self.config.key then
return nil, "Must have API key before performing any actions."
end
if params and next(params) then
url = url .. ("?" .. encode_query_string(params))
end
local method = "GET"
local out
local tmpfile = fs.tmpname()
if post_params then
method = "POST"
local curl_cmd = fs.Q(vars.CURL).." -f -k -L --silent --user-agent \""..cfg.user_agent.." via curl\" "
for k,v in pairs(post_params) do
local var = v
if type(v) == "table" then
var = "@"..v.fname
end
curl_cmd = curl_cmd .. "--form \""..k.."="..var.."\" "
end
if cfg.connection_timeout and cfg.connection_timeout > 0 then
curl_cmd = curl_cmd .. "--connect-timeout "..tonumber(cfg.connection_timeout).." "
end
local ok = fs.execute_string(curl_cmd..fs.Q(url).." -o "..fs.Q(tmpfile))
if not ok then
return nil, "API failure: " .. redact_api_url(url)
end
else
local ok, err = fs.download(url, tmpfile)
if not ok then
return nil, "API failure: " .. tostring(err) .. " - " .. redact_api_url(url)
end
end
local tmpfd = io.open(tmpfile)
if not tmpfd then
os.remove(tmpfile)
return nil, "API failure reading temporary file - " .. redact_api_url(url)
end
out = tmpfd:read("*a")
tmpfd:close()
os.remove(tmpfile)
if self.debug then
util.printout("[" .. tostring(method) .. " via curl] " .. redact_api_url(url) .. " ... ")
end
return json.decode(out)
end
else -- use LuaSocket and LuaSec
local warned_luasec = false
function Api:request(url, params, post_params)
local json_ok, json = require_json()
if not json_ok then return nil, "A JSON library is required for this command. "..json end
local server = tostring(self.config.server)
local http_ok, http
local via = "luasocket"
if server:match("^https://") then
http_ok, http = pcall(require, "ssl.https")
if http_ok then
via = "luasec"
else
if not warned_luasec then
util.printerr("LuaSec is not available; using plain HTTP. Install 'luasec' to enable HTTPS.")
warned_luasec = true
end
http_ok, http = pcall(require, "socket.http")
url = url:gsub("^https", "http")
via = "luasocket"
end
else
http_ok, http = pcall(require, "socket.http")
end
if not http_ok then
return nil, "Failed loading socket library!"
end
if not self.config.key then
return nil, "Must have API key before performing any actions."
end
local body
local headers = {}
if params and next(params) then
url = url .. ("?" .. encode_query_string(params))
end
if post_params then
local boundary
body, boundary = multipart.encode(post_params)
headers["Content-length"] = #body
headers["Content-type"] = "multipart/form-data; boundary=" .. tostring(boundary)
end
local method = post_params and "POST" or "GET"
if self.debug then
util.printout("[" .. tostring(method) .. " via "..via.."] " .. redact_api_url(url) .. " ... ")
end
local out = {}
local _, status = http.request({
url = url,
headers = headers,
method = method,
sink = ltn12.sink.table(out),
source = body and ltn12.source.string(body)
})
if self.debug then
util.printout(tostring(status))
end
if status ~= 200 then
return nil, "API returned " .. tostring(status) .. " - " .. redact_api_url(url)
end
return json.decode(table.concat(out))
end
end
function api.new(flags)
local self = {}
setmetatable(self, { __index = Api })
self.config = self:load_config() or {}
self.config.server = flags["server"] or self.config.server or cfg.upload.server
self.config.version = self.config.version or cfg.upload.version
self.config.key = flags["api-key"] or self.config.key
self.debug = flags["debug"]
if not self.config.key then
return nil, "You need an API key to upload rocks.\n" ..
"Navigate to "..self.config.server.."/settings to get a key\n" ..
"and then pass it through the --api-key= flag."
end
if flags["api-key"] then
self:save_config()
end
return self
end
return api
luarocks-2.4.2+dfsg/src/luarocks/upload/multipart.lua 0000664 0000000 0000000 00000005360 13030154704 0022704 0 ustar 00root root 0000000 0000000
local multipart = {}
local File = {}
local unpack = unpack or table.unpack
math.randomseed(os.time())
-- socket.url.escape(s) from LuaSocket 3.0rc1
function multipart.url_escape(s)
return (string.gsub(s, "([^A-Za-z0-9_])", function(c)
return string.format("%%%02x", string.byte(c))
end))
end
function File:mime()
if not self.mimetype then
local mimetypes_ok, mimetypes = pcall(require, "mimetypes")
if mimetypes_ok then
self.mimetype = mimetypes.guess(self.fname)
end
self.mimetype = self.mimetype or "application/octet-stream"
end
return self.mimetype
end
function File:content()
local fd = io.open(self.fname, "rb")
if not fd then
return nil, "Failed to open file: "..self.fname
end
local data = fd:read("*a")
fd:close()
return data
end
local function rand_string(len)
local shuffled = {}
for i = 1, len do
local r = math.random(97, 122)
if math.random() >= 0.5 then
r = r - 32
end
shuffled[i] = r
end
return string.char(unpack(shuffled))
end
-- multipart encodes params
-- returns encoded string,boundary
-- params is an a table of tuple tables:
-- params = {
-- {key1, value2},
-- {key2, value2},
-- key3: value3
-- }
function multipart.encode(params)
local tuples = { }
for i = 1, #params do
tuples[i] = params[i]
end
for k,v in pairs(params) do
if type(k) == "string" then
table.insert(tuples, {k, v})
end
end
local chunks = {}
for _, tuple in ipairs(tuples) do
local k,v = unpack(tuple)
k = multipart.url_escape(k)
local buffer = { 'Content-Disposition: form-data; name="' .. k .. '"' }
local content
if type(v) == "table" and v.__class == File then
buffer[1] = buffer[1] .. ('; filename="' .. v.fname:gsub(".*/", "") .. '"')
table.insert(buffer, "Content-type: " .. v:mime())
content = v:content()
else
content = v
end
table.insert(buffer, "")
table.insert(buffer, content)
table.insert(chunks, table.concat(buffer, "\r\n"))
end
local boundary
while not boundary do
boundary = "Boundary" .. rand_string(16)
for _, chunk in ipairs(chunks) do
if chunk:find(boundary) then
boundary = nil
break
end
end
end
local inner = "\r\n--" .. boundary .. "\r\n"
return table.concat({ "--", boundary, "\r\n",
table.concat(chunks, inner),
"\r\n", "--", boundary, "--", "\r\n" }), boundary
end
function multipart.new_file(fname, mime)
local self = {}
setmetatable(self, { __index = File })
self.__class = File
self.fname = fname
self.mimetype = mime
return self
end
return multipart
luarocks-2.4.2+dfsg/src/luarocks/util.lua 0000664 0000000 0000000 00000055516 13030154704 0020364 0 ustar 00root root 0000000 0000000
--- Assorted utilities for managing tables, plus a scheduler for rollback functions.
-- Does not requires modules directly (only as locals
-- inside specific functions) to avoid interdependencies,
-- as this is used in the bootstrapping stage of luarocks.cfg.
local util = {}
local unpack = unpack or table.unpack
local scheduled_functions = {}
local debug = require("debug")
--- Schedule a function to be executed upon program termination.
-- This is useful for actions such as deleting temporary directories
-- or failure rollbacks.
-- @param f function: Function to be executed.
-- @param ... arguments to be passed to function.
-- @return table: A token representing the scheduled execution,
-- which can be used to remove the item later from the list.
function util.schedule_function(f, ...)
assert(type(f) == "function")
local item = { fn = f, args = {...} }
table.insert(scheduled_functions, item)
return item
end
--- Unschedule a function.
-- This is useful for cancelling a rollback of a completed operation.
-- @param item table: The token representing the scheduled function that was
-- returned from the schedule_function call.
function util.remove_scheduled_function(item)
for k, v in pairs(scheduled_functions) do
if v == item then
table.remove(scheduled_functions, k)
return
end
end
end
--- Execute scheduled functions.
-- Some calls create temporary files and/or directories and register
-- corresponding cleanup functions. Calling this function will run
-- these function, erasing temporaries.
-- Functions are executed in the inverse order they were scheduled.
function util.run_scheduled_functions()
local fs = require("luarocks.fs")
fs.change_dir_to_root()
for i = #scheduled_functions, 1, -1 do
local item = scheduled_functions[i]
item.fn(unpack(item.args))
end
end
--- Produce a Lua pattern that matches precisely the given string
-- (this is suitable to be concatenating to other patterns,
-- so it does not include beginning- and end-of-string markers (^$)
-- @param s string: The input string
-- @return string: The equivalent pattern
function util.matchquote(s)
return (s:gsub("[?%-+*%[%].%%()$^]","%%%1"))
end
--- List of supported arguments.
-- Arguments that take no parameters are marked with the boolean true.
-- Arguments that take a parameter are marked with a descriptive string.
-- Arguments that may take an empty string are described in quotes,
-- (as in the value for --detailed="").
-- For all other string values, it means the parameter is mandatory.
local supported_flags = {
["all"] = true,
["api-key"] = "",
["append"] = true,
["arch"] = "",
["bin"] = true,
["binary"] = true,
["branch"] = "",
["debug"] = true,
["deps"] = true,
["deps-mode"] = "",
["detailed"] = "\"\"",
["force"] = true,
["force-fast"] = true,
["from"] = "",
["help"] = true,
["home"] = true,
["homepage"] = "\"\"",
["keep"] = true,
["lib"] = "",
["license"] = "\"\"",
["list"] = true,
["local"] = true,
["local-tree"] = true,
["lr-bin"] = true,
["lr-cpath"] = true,
["lr-path"] = true,
["lua-version"] = "",
["lua-ver"] = true,
["lua-incdir"] = true,
["lua-libdir"] = true,
["modules"] = true,
["mversion"] = true,
["no-refresh"] = true,
["nodeps"] = true,
["old-versions"] = true,
["only-deps"] = true,
["only-from"] = "",
["only-server"] = "",
["only-sources"] = "",
["only-sources-from"] = "",
["outdated"] = true,
["output"] = "",
["pack-binary-rock"] = true,
["porcelain"] = true,
["quick"] = true,
["rock-dir"] = true,
["rock-tree"] = true,
["rock-trees"] = true,
["rockspec"] = true,
["rockspec-format"] = "",
["server"] = "",
["skip-pack"] = true,
["source"] = true,
["summary"] = "\"\"",
["system-config"] = true,
["tag"] = "",
["timeout"] = "",
["to"] = "",
["tree"] = "",
["user-config"] = true,
["verbose"] = true,
["version"] = true,
}
--- Extract flags from an arguments list.
-- Given string arguments, extract flag arguments into a flags set.
-- For example, given "foo", "--tux=beep", "--bla", "bar", "--baz",
-- it would return the following:
-- {["bla"] = true, ["tux"] = "beep", ["baz"] = true}, "foo", "bar".
function util.parse_flags(...)
local args = {...}
local flags = {}
local i = 1
local out = {}
local ignore_flags = false
while i <= #args do
local flag = args[i]:match("^%-%-(.*)")
if flag == "--" then
ignore_flags = true
end
if flag and not ignore_flags then
local var,val = flag:match("([a-z_%-]*)=(.*)")
if val then
local vartype = supported_flags[var]
if type(vartype) == "string" then
if val == "" and vartype:sub(1,1) ~= '"' then
return { ERROR = "Invalid argument: parameter to flag --"..var.."="..vartype.." cannot be empty." }
end
flags[var] = val
else
if vartype then
return { ERROR = "Invalid argument: flag --"..var.." does not take an parameter." }
else
return { ERROR = "Invalid argument: unknown flag --"..var.."." }
end
end
else
local var = flag
local vartype = supported_flags[var]
if type(vartype) == "string" then
i = i + 1
local val = args[i]
if not val then
return { ERROR = "Invalid argument: flag --"..var.."="..vartype.." expects a parameter." }
end
if val:match("^%-%-.*") then
return { ERROR = "Invalid argument: flag --"..var.."="..vartype.." expects a parameter (if you really want to pass "..val.." as an argument to --"..var..", use --"..var.."="..val..")." }
else
if val == "" and vartype:sub(1,1) ~= '"' then
return { ERROR = "Invalid argument: parameter to flag --"..var.."="..vartype.." cannot be empty." }
end
flags[var] = val
end
elseif vartype == true then
flags[var] = true
else
return { ERROR = "Invalid argument: unknown flag --"..var.."." }
end
end
else
table.insert(out, args[i])
end
i = i + 1
end
return flags, unpack(out)
end
-- Adds legacy 'run' function to a command module.
-- @param command table: command module with 'command' function,
-- the added 'run' function calls it after parseing command-line arguments.
function util.add_run_function(command)
command.run = function(...) return command.command(util.parse_flags(...)) end
end
--- Merges contents of src on top of dst's contents.
-- @param dst Destination table, which will receive src's contents.
-- @param src Table which provides new contents to dst.
-- @see platform_overrides
function util.deep_merge(dst, src)
for k, v in pairs(src) do
if type(v) == "table" then
if not dst[k] then
dst[k] = {}
end
if type(dst[k]) == "table" then
util.deep_merge(dst[k], v)
else
dst[k] = v
end
else
dst[k] = v
end
end
end
--- Perform platform-specific overrides on a table.
-- Overrides values of table with the contents of the appropriate
-- subset of its "platforms" field. The "platforms" field should
-- be a table containing subtables keyed with strings representing
-- platform names. Names that match the contents of the global
-- cfg.platforms setting are used. For example, if
-- cfg.platforms= {"foo"}, then the fields of
-- tbl.platforms.foo will overwrite those of tbl with the same
-- names. For table values, the operation is performed recursively
-- (tbl.platforms.foo.x.y.z overrides tbl.x.y.z; other contents of
-- tbl.x are preserved).
-- @param tbl table or nil: Table which may contain a "platforms" field;
-- if it doesn't (or if nil is passed), this function does nothing.
function util.platform_overrides(tbl)
assert(type(tbl) == "table" or not tbl)
local cfg = require("luarocks.cfg")
if not tbl then return end
if tbl.platforms then
for _, platform in ipairs(cfg.platforms) do
local platform_tbl = tbl.platforms[platform]
if platform_tbl then
util.deep_merge(tbl, platform_tbl)
end
end
end
tbl.platforms = nil
end
local var_format_pattern = "%$%((%a[%a%d_]+)%)"
--- Create a new shallow copy of a table: a new table with
-- the same keys and values. Keys point to the same objects as
-- the original table (ie, does not copy recursively).
-- @param tbl table: the input table
-- @return table: a new table with the same contents.
function util.make_shallow_copy(tbl)
local copy = {}
for k,v in pairs(tbl) do
copy[k] = v
end
return copy
end
-- Check if a set of needed variables are referenced
-- somewhere in a list of definitions, warning the user
-- about any unused ones. Each key in needed_set should
-- appear as a $(XYZ) variable at least once as a
-- substring of some value of var_defs.
-- @param var_defs: a table with string keys and string
-- values, containing variable definitions.
-- @param needed_set: a set where keys are the names of
-- needed variables.
-- @param msg string: the warning message to display.
function util.warn_if_not_used(var_defs, needed_set, msg)
needed_set = util.make_shallow_copy(needed_set)
for _, val in pairs(var_defs) do
for used in val:gmatch(var_format_pattern) do
needed_set[used] = nil
end
end
for var, _ in pairs(needed_set) do
util.warning(msg:format(var))
end
end
-- Output any entries that might remain in $(XYZ) format,
-- warning the user that substitutions have failed.
-- @param line string: the input string
local function warn_failed_matches(line)
local any_failed = false
if line:match(var_format_pattern) then
for unmatched in line:gmatch(var_format_pattern) do
util.warning("unmatched variable " .. unmatched)
any_failed = true
end
end
return any_failed
end
--- Perform make-style variable substitutions on string values of a table.
-- For every string value tbl.x which contains a substring of the format
-- "$(XYZ)" will have this substring replaced by vars["XYZ"], if that field
-- exists in vars. Only string values are processed; this function
-- does not scan subtables recursively.
-- @param tbl table: Table to have its string values modified.
-- @param vars table: Table containing string-string key-value pairs
-- representing variables to replace in the strings values of tbl.
function util.variable_substitutions(tbl, vars)
assert(type(tbl) == "table")
assert(type(vars) == "table")
local updated = {}
for k, v in pairs(tbl) do
if type(v) == "string" then
updated[k] = v:gsub(var_format_pattern, vars)
if warn_failed_matches(updated[k]) then
updated[k] = updated[k]:gsub(var_format_pattern, "")
end
end
end
for k, v in pairs(updated) do
tbl[k] = v
end
end
--- Return an array of keys of a table.
-- @param tbl table: The input table.
-- @return table: The array of keys.
function util.keys(tbl)
local ks = {}
for k,_ in pairs(tbl) do
table.insert(ks, k)
end
return ks
end
local function default_sort(a, b)
local ta = type(a)
local tb = type(b)
if ta == "number" and tb == "number" then
return a < b
elseif ta == "number" then
return true
elseif tb == "number" then
return false
else
return tostring(a) < tostring(b)
end
end
--- A table iterator generator that returns elements sorted by key,
-- to be used in "for" loops.
-- @param tbl table: The table to be iterated.
-- @param sort_function function or table or nil: An optional comparison function
-- to be used by table.sort when sorting keys, or an array listing an explicit order
-- for keys. If a value itself is an array, it is taken so that the first element
-- is a string representing the field name, and the second element is a priority table
-- for that key, which is returned by the iterator as the third value after the key
-- and the value.
-- @return function: the iterator function.
function util.sortedpairs(tbl, sort_function)
sort_function = sort_function or default_sort
local keys = util.keys(tbl)
local sub_orders = {}
if type(sort_function) == "function" then
table.sort(keys, sort_function)
else
local order = sort_function
local ordered_keys = {}
local all_keys = keys
keys = {}
for _, order_entry in ipairs(order) do
local key, sub_order
if type(order_entry) == "table" then
key = order_entry[1]
sub_order = order_entry[2]
else
key = order_entry
end
if tbl[key] then
ordered_keys[key] = true
sub_orders[key] = sub_order
table.insert(keys, key)
end
end
table.sort(all_keys, default_sort)
for _, key in ipairs(all_keys) do
if not ordered_keys[key] then
table.insert(keys, key)
end
end
end
local i = 1
return function()
local key = keys[i]
i = i + 1
return key, tbl[key], sub_orders[key]
end
end
function util.lua_versions()
local versions = { "5.1", "5.2", "5.3" }
local i = 0
return function()
i = i + 1
return versions[i]
end
end
function util.starts_with(s, prefix)
return s:sub(1,#prefix) == prefix
end
--- Print a line to standard output
function util.printout(...)
io.stdout:write(table.concat({...},"\t"))
io.stdout:write("\n")
end
--- Print a line to standard error
function util.printerr(...)
io.stderr:write(table.concat({...},"\t"))
io.stderr:write("\n")
end
--- Display a warning message.
-- @param msg string: the warning message
function util.warning(msg)
util.printerr("Warning: "..msg)
end
function util.title(msg, porcelain, underline)
if porcelain then return end
util.printout()
util.printout(msg)
util.printout((underline or "-"):rep(#msg))
util.printout()
end
function util.this_program(default)
local i = 1
local last, cur = default, default
while i do
local dbg = debug.getinfo(i,"S")
if not dbg then break end
last = cur
cur = dbg.source
i=i+1
end
return last:sub(2)
end
function util.deps_mode_help(program)
local cfg = require("luarocks.cfg")
return [[
--deps-mode= How to handle dependencies. Four modes are supported:
* all - use all trees from the rocks_trees list
for finding dependencies
* one - use only the current tree (possibly set
with --tree)
* order - use trees based on order (use the current
tree and all trees below it on the rocks_trees list)
* none - ignore dependencies altogether.
The default mode may be set with the deps_mode entry
in the configuration file.
The current default is "]]..cfg.deps_mode..[[".
Type ']]..util.this_program(program or "luarocks")..[[' with no arguments to see
your list of rocks trees.
]]
end
function util.see_help(command, program)
return "See '"..util.this_program(program or "luarocks")..' help'..(command and " "..command or "").."'."
end
function util.announce_install(rockspec)
local cfg = require("luarocks.cfg")
local path = require("luarocks.path")
local suffix = ""
if rockspec.description and rockspec.description.license then
suffix = " (license: "..rockspec.description.license..")"
end
local root_dir = path.root_dir(cfg.rocks_dir)
util.printout(rockspec.name.." "..rockspec.version.." is now installed in "..root_dir..suffix)
util.printout()
end
--- Collect rockspecs located in a subdirectory.
-- @param versions table: A table mapping rock names to newest rockspec versions.
-- @param paths table: A table mapping rock names to newest rockspec paths.
-- @param unnamed_paths table: An array of rockspec paths that don't contain rock
-- name and version in regular format.
-- @param subdir string: path to subdirectory.
local function collect_rockspecs(versions, paths, unnamed_paths, subdir)
local fs = require("luarocks.fs")
local dir = require("luarocks.dir")
local path = require("luarocks.path")
local deps = require("luarocks.deps")
if fs.is_dir(subdir) then
for file in fs.dir(subdir) do
file = dir.path(subdir, file)
if file:match("rockspec$") and fs.is_file(file) then
local rock, version = path.parse_name(file)
if rock then
if not versions[rock] or deps.compare_versions(version, versions[rock]) then
versions[rock] = version
paths[rock] = file
end
else
table.insert(unnamed_paths, file)
end
end
end
end
end
--- Get default rockspec name for commands that take optional rockspec name.
-- @return string or (nil, string): path to the rockspec or nil and error message.
function util.get_default_rockspec()
local versions, paths, unnamed_paths = {}, {}, {}
-- Look for rockspecs in some common locations.
collect_rockspecs(versions, paths, unnamed_paths, ".")
collect_rockspecs(versions, paths, unnamed_paths, "rockspec")
collect_rockspecs(versions, paths, unnamed_paths, "rockspecs")
if #unnamed_paths > 0 then
-- There are rockspecs not following "name-version.rockspec" format.
-- More than one are ambiguous.
if #unnamed_paths > 1 then
return nil, "Please specify which rockspec file to use."
else
return unnamed_paths[1]
end
else
local rock = next(versions)
if rock then
-- If there are rockspecs for multiple rocks it's ambiguous.
if next(versions, rock) then
return nil, "Please specify which rockspec file to use."
else
return paths[rock]
end
else
return nil, "Argument missing: please specify a rockspec to use on current directory."
end
end
end
-- from http://lua-users.org/wiki/SplitJoin
-- by PhilippeLhoste
function util.split_string(str, delim, maxNb)
-- Eliminate bad cases...
if string.find(str, delim) == nil then
return { str }
end
if maxNb == nil or maxNb < 1 then
maxNb = 0 -- No limit
end
local result = {}
local pat = "(.-)" .. delim .. "()"
local nb = 0
local lastPos
for part, pos in string.gmatch(str, pat) do
nb = nb + 1
result[nb] = part
lastPos = pos
if nb == maxNb then break end
end
-- Handle the last field
if nb ~= maxNb then
result[nb + 1] = string.sub(str, lastPos)
end
return result
end
--- Remove repeated entries from a path-style string.
-- Example: given ("a;b;c;a;b;d", ";"), returns "a;b;c;d".
-- @param list string: A path string (from $PATH or package.path)
-- @param sep string: The separator
function util.remove_path_dupes(list, sep)
assert(type(list) == "string")
assert(type(sep) == "string")
local parts = util.split_string(list, sep)
local final, entries = {}, {}
for _, part in ipairs(parts) do
part = part:gsub("//", "/")
if not entries[part] then
table.insert(final, part)
entries[part] = true
end
end
return table.concat(final, sep)
end
---
-- Formats tables with cycles recursively to any depth.
-- References to other tables are shown as values.
-- Self references are indicated.
-- The string returned is "Lua code", which can be procesed
-- (in the case in which indent is composed by spaces or "--").
-- Userdata and function keys and values are shown as strings,
-- which logically are exactly not equivalent to the original code.
-- This routine can serve for pretty formating tables with
-- proper indentations, apart from printing them:
-- io.write(table.show(t, "t")) -- a typical use
-- Written by Julio Manuel Fernandez-Diaz,
-- Heavily based on "Saving tables with cycles", PIL2, p. 113.
-- @param t table: is the table.
-- @param name string: is the name of the table (optional)
-- @param indent string: is a first indentation (optional).
-- @return string: the pretty-printed table
function util.show_table(t, name, indent)
local cart -- a container
local autoref -- for self references
local function isemptytable(t) return next(t) == nil end
local function basicSerialize (o)
local so = tostring(o)
if type(o) == "function" then
local info = debug.getinfo(o, "S")
-- info.name is nil because o is not a calling level
if info.what == "C" then
return ("%q"):format(so .. ", C function")
else
-- the information is defined through lines
return ("%q"):format(so .. ", defined in (" .. info.linedefined .. "-" .. info.lastlinedefined .. ")" .. info.source)
end
elseif type(o) == "number" then
return so
else
return ("%q"):format(so)
end
end
local function addtocart (value, name, indent, saved, field)
indent = indent or ""
saved = saved or {}
field = field or name
cart = cart .. indent .. field
if type(value) ~= "table" then
cart = cart .. " = " .. basicSerialize(value) .. ";\n"
else
if saved[value] then
cart = cart .. " = {}; -- " .. saved[value] .. " (self reference)\n"
autoref = autoref .. name .. " = " .. saved[value] .. ";\n"
else
saved[value] = name
--if tablecount(value) == 0 then
if isemptytable(value) then
cart = cart .. " = {};\n"
else
cart = cart .. " = {\n"
for k, v in pairs(value) do
k = basicSerialize(k)
local fname = ("%s[%s]"):format(name, k)
field = ("[%s]"):format(k)
-- three spaces between levels
addtocart(v, fname, indent .. " ", saved, field)
end
cart = cart .. indent .. "};\n"
end
end
end
end
name = name or "__unnamed__"
if type(t) ~= "table" then
return name .. " = " .. basicSerialize(t)
end
cart, autoref = "", ""
addtocart(t, name, indent)
return cart .. autoref
end
function util.array_contains(tbl, value)
for _, v in ipairs(tbl) do
if v == value then
return true
end
end
return false
end
-- Quote Lua string, analogous to fs.Q.
-- @param s A string, such as "hello"
-- @return string: A quoted string, such as '"hello"'
function util.LQ(s)
return ("%q"):format(s)
end
return util
luarocks-2.4.2+dfsg/src/luarocks/validate.lua 0000664 0000000 0000000 00000011016 13030154704 0021163 0 ustar 00root root 0000000 0000000
--- Sandboxed test of build/install of all packages in a repository (unfinished and disabled).
local validate = {}
package.loaded["luarocks.validate"] = validate
local fs = require("luarocks.fs")
local dir = require("luarocks.dir")
local path = require("luarocks.path")
local cfg = require("luarocks.cfg")
local build = require("luarocks.build")
local install = require("luarocks.install")
local util = require("luarocks.util")
util.add_run_function(validate)
validate.help_summary = "Sandboxed test of build/install of all packages in a repository."
validate.help = [[
, if given, is a local repository pathname.
]]
local function save_settings(repo)
local protocol, path = dir.split_url(repo)
table.insert(cfg.rocks_servers, 1, protocol.."://"..path)
return {
root_dir = cfg.root_dir,
rocks_dir = cfg.rocks_dir,
deploy_bin_dir = cfg.deploy_bin_dir,
deploy_lua_dir = cfg.deploy_lua_dir,
deploy_lib_dir = cfg.deploy_lib_dir,
}
end
local function restore_settings(settings)
cfg.root_dir = settings.root_dir
cfg.rocks_dir = settings.rocks_dir
cfg.deploy_bin_dir = settings.deploy_bin_dir
cfg.deploy_lua_dir = settings.deploy_lua_dir
cfg.deploy_lib_dir = settings.deploy_lib_dir
cfg.variables.ROCKS_TREE = settings.rocks_dir
cfg.variables.SCRIPTS_DIR = settings.deploy_bin_dir
table.remove(cfg.rocks_servers, 1)
end
local function prepare_sandbox(file)
local root_dir = fs.make_temp_dir(file):gsub("/+$", "")
cfg.root_dir = root_dir
cfg.rocks_dir = path.rocks_dir(root_dir)
cfg.deploy_bin_dir = path.deploy_bin_dir(root_dir)
cfg.variables.ROCKS_TREE = cfg.rocks_dir
cfg.variables.SCRIPTS_DIR = cfg.deploy_bin_dir
return root_dir
end
local function validate_rockspec(file)
local ok, err, errcode = build.build_rockspec(file, true, "one")
if not ok then
util.printerr(err)
end
return ok, err, errcode
end
local function validate_src_rock(file)
local ok, err, errcode = build.build_rock(file, false, "one")
if not ok then
util.printerr(err)
end
return ok, err, errcode
end
local function validate_rock(file)
local ok, err, errcode = install.install_binary_rock(file, "one")
if not ok then
util.printerr(err)
end
return ok, err, errcode
end
function validate.command(flags, repo)
repo = repo or cfg.rocks_dir
util.printout("Verifying contents of "..repo)
local results = {
ok = {}
}
local settings = save_settings(repo)
local sandbox
if flags["quick"] then
sandbox = prepare_sandbox("luarocks_validate")
end
if not fs.exists(repo) then
return nil, repo.." is not a local repository."
end
for file in fs.dir(repo) do for _=1,1 do
if file == "manifest" or file == "index.html" then
break -- continue for
end
local pathname = fs.absolute_name(dir.path(repo, file))
if not flags["quick"] then
sandbox = prepare_sandbox(file)
end
local ok, err, errcode
util.printout()
util.printout("Verifying "..pathname)
if file:match("%.rockspec$") then
ok, err, errcode = validate_rockspec(pathname, "one")
elseif file:match("%.src%.rock$") then
ok, err, errcode = validate_src_rock(pathname)
elseif file:match("%.rock$") then
ok, err, errcode = validate_rock(pathname)
end
if ok then
table.insert(results.ok, {file=file} )
else
if not errcode then
errcode = "misc"
end
if not results[errcode] then
results[errcode] = {}
end
table.insert(results[errcode], {file=file, err=err} )
end
util.run_scheduled_functions()
if not flags["quick"] then
fs.delete(sandbox)
end
repeat until not fs.pop_dir()
end end
if flags["quick"] then
fs.delete(sandbox)
end
restore_settings(settings)
util.title("Results:")
util.printout("OK: "..tostring(#results.ok))
for _, entry in ipairs(results.ok) do
util.printout(entry.file)
end
for errcode, errors in pairs(results) do
if errcode ~= "ok" then
util.printout()
util.printout(errcode.." errors: "..tostring(#errors))
for _, entry in ipairs(errors) do
util.printout(entry.file, entry.err)
end
end
end
util.title("Summary:")
local total = 0
for errcode, errors in pairs(results) do
util.printout(errcode..": "..tostring(#errors))
total = total + #errors
end
util.printout("Total: "..total)
return true
end
return validate
luarocks-2.4.2+dfsg/src/luarocks/write_rockspec.lua 0000664 0000000 0000000 00000027774 13030154704 0022437 0 ustar 00root root 0000000 0000000
local write_rockspec = {}
package.loaded["luarocks.write_rockspec"] = write_rockspec
local cfg = require("luarocks.cfg")
local dir = require("luarocks.dir")
local fetch = require("luarocks.fetch")
local fs = require("luarocks.fs")
local path = require("luarocks.path")
local persist = require("luarocks.persist")
local type_check = require("luarocks.type_check")
local util = require("luarocks.util")
util.add_run_function(write_rockspec)
write_rockspec.help_summary = "Write a template for a rockspec file."
write_rockspec.help_arguments = "[--output= ...] [] [] [|]"
write_rockspec.help = [[
This command writes an initial version of a rockspec file,
based on a name, a version, and a location (an URL or a local path).
If only two arguments are given, the first one is considered the name and the
second one is the location.
If only one argument is given, it must be the location.
If no arguments are given, current directory is used as location.
LuaRocks will attempt to infer name and version if not given,
using 'scm' as default version.
Note that the generated file is a _starting point_ for writing a
rockspec, and is not guaranteed to be complete or correct.
--output= Write the rockspec with the given filename.
If not given, a file is written in the current
directory with a filename based on given name and version.
--license="" A license string, such as "MIT/X11" or "GNU GPL v3".
--summary="" A short one-line description summary.
--detailed="" A longer description string.
--homepage= Project homepage.
--lua-version= Supported Lua versions. Accepted values are "5.1", "5.2",
"5.3", "5.1,5.2", "5.2,5.3", or "5.1,5.2,5.3".
--rockspec-format= Rockspec format version, such as "1.0" or "1.1".
--tag= Tag to use. Will attempt to extract version number from it.
--lib=[,] A comma-separated list of libraries that C files need to
link to.
]]
local function open_file(name)
return io.open(dir.path(fs.current_dir(), name), "r")
end
local function get_url(rockspec)
local file, temp_dir, err_code, err_file, err_temp_dir = fetch.fetch_sources(rockspec, false)
if err_code == "source.dir" then
file, temp_dir = err_file, err_temp_dir
elseif not file then
util.warning("Could not fetch sources - "..temp_dir)
return false
end
util.printout("File successfully downloaded. Making checksum and checking base dir...")
if fetch.is_basic_protocol(rockspec.source.protocol) then
rockspec.source.md5 = fs.get_md5(file)
end
local inferred_dir, found_dir = fetch.find_base_dir(file, temp_dir, rockspec.source.url)
return true, found_dir or inferred_dir, temp_dir
end
local function configure_lua_version(rockspec, luaver)
if luaver == "5.1" then
table.insert(rockspec.dependencies, "lua ~> 5.1")
elseif luaver == "5.2" then
table.insert(rockspec.dependencies, "lua ~> 5.2")
elseif luaver == "5.3" then
table.insert(rockspec.dependencies, "lua ~> 5.3")
elseif luaver == "5.1,5.2" then
table.insert(rockspec.dependencies, "lua >= 5.1, < 5.3")
elseif luaver == "5.2,5.3" then
table.insert(rockspec.dependencies, "lua >= 5.2, < 5.4")
elseif luaver == "5.1,5.2,5.3" then
table.insert(rockspec.dependencies, "lua >= 5.1, < 5.4")
else
util.warning("Please specify supported Lua version with --lua-version=. "..util.see_help("write_rockspec"))
end
end
local function detect_description()
local fd = open_file("README.md") or open_file("README")
if not fd then return end
local data = fd:read("*a")
fd:close()
local paragraph = data:match("\n\n([^%[].-)\n\n")
if not paragraph then paragraph = data:match("\n\n(.*)") end
local summary, detailed
if paragraph then
detailed = paragraph
if #paragraph < 80 then
summary = paragraph:gsub("\n", "")
else
summary = paragraph:gsub("\n", " "):match("([^.]*%.) ")
end
end
return summary, detailed
end
local function detect_mit_license(data)
local strip_copyright = (data:gsub("Copyright [^\n]*\n", ""))
local sum = 0
for i = 1, #strip_copyright do
local num = string.byte(strip_copyright:sub(i,i))
if num > 32 and num <= 128 then
sum = sum + num
end
end
return sum == 78656
end
local simple_scm_protocols = {
git = true, ["git+http"] = true, ["git+https"] = true,
hg = true, ["hg+http"] = true, ["hg+https"] = true
}
local function detect_url_from_command(program, args, directory)
local command = fs.Q(cfg.variables[program:upper()]).. " "..args
local pipe = io.popen(fs.command_at(directory, fs.quiet_stderr(command)))
if not pipe then return nil end
local url = pipe:read("*a"):match("^([^\r\n]+)")
pipe:close()
if not url then return nil end
if not util.starts_with(url, program.."://") then
url = program.."+"..url
end
if simple_scm_protocols[dir.split_url(url)] then
return url
end
end
local function detect_scm_url(directory)
return detect_url_from_command("git", "config --get remote.origin.url", directory) or
detect_url_from_command("hg", "paths default", directory)
end
local function show_license(rockspec)
local fd = open_file("COPYING") or open_file("LICENSE") or open_file("MIT-LICENSE.txt")
if not fd then return nil end
local data = fd:read("*a")
fd:close()
local is_mit = detect_mit_license(data)
util.title("License for "..rockspec.package..":")
util.printout(data)
util.printout()
return is_mit
end
local function get_cmod_name(file)
local fd = open_file(file)
if not fd then return nil end
local data = fd:read("*a")
fd:close()
return (data:match("int%s+luaopen_([a-zA-Z0-9_]+)"))
end
local luamod_blacklist = {
test = true,
tests = true,
}
local function fill_as_builtin(rockspec, libs)
rockspec.build.type = "builtin"
rockspec.build.modules = {}
local prefix = ""
for _, parent in ipairs({"src", "lua"}) do
if fs.is_dir(parent) then
fs.change_dir(parent)
prefix = parent.."/"
break
end
end
local incdirs, libdirs
if libs then
incdirs, libdirs = {}, {}
for _, lib in ipairs(libs) do
local upper = lib:upper()
incdirs[#incdirs+1] = "$("..upper.."_INCDIR)"
libdirs[#libdirs+1] = "$("..upper.."_LIBDIR)"
end
end
for _, file in ipairs(fs.find()) do
local luamod = file:match("(.*)%.lua$")
if luamod and not luamod_blacklist[luamod] then
rockspec.build.modules[path.path_to_module(file)] = prefix..file
else
local cmod = file:match("(.*)%.c$")
if cmod then
local modname = get_cmod_name(file) or path.path_to_module(file:gsub("%.c$", ".lua"))
rockspec.build.modules[modname] = {
sources = prefix..file,
libraries = libs,
incdirs = incdirs,
libdirs = libdirs,
}
end
end
end
for _, directory in ipairs({ "doc", "docs", "samples", "tests" }) do
if fs.is_dir(directory) then
if not rockspec.build.copy_directories then
rockspec.build.copy_directories = {}
end
table.insert(rockspec.build.copy_directories, directory)
end
end
if prefix ~= "" then
fs.pop_dir()
end
end
local function rockspec_cleanup(rockspec)
rockspec.source.file = nil
rockspec.source.protocol = nil
rockspec.variables = nil
rockspec.name = nil
end
function write_rockspec.command(flags, name, version, url_or_dir)
if not name then
url_or_dir = "."
elseif not version then
url_or_dir = name
name = nil
elseif not url_or_dir then
url_or_dir = version
version = nil
end
if flags["tag"] then
if not version then
version = flags["tag"]:gsub("^v", "")
end
end
local protocol, pathname = dir.split_url(url_or_dir)
if protocol == "file" then
if pathname == "." then
name = name or dir.base_name(fs.current_dir())
end
elseif fetch.is_basic_protocol(protocol) then
local filename = dir.base_name(url_or_dir)
local newname, newversion = filename:match("(.*)-([^-]+)")
if newname then
name = name or newname
version = version or newversion:gsub("%.[a-z]+$", ""):gsub("%.tar$", "")
end
else
name = name or dir.base_name(url_or_dir):gsub("%.[^.]+$", "")
end
if not name then
return nil, "Could not infer rock name. "..util.see_help("write_rockspec")
end
version = version or "scm"
local filename = flags["output"] or dir.path(fs.current_dir(), name:lower().."-"..version.."-1.rockspec")
local rockspec = {
rockspec_format = flags["rockspec-format"],
package = name,
name = name:lower(),
version = version.."-1",
source = {
url = "*** please add URL for source tarball, zip or repository here ***",
tag = flags["tag"],
},
description = {
summary = flags["summary"] or "*** please specify description summary ***",
detailed = flags["detailed"] or "*** please enter a detailed description ***",
homepage = flags["homepage"] or "*** please enter a project homepage ***",
license = flags["license"] or "*** please specify a license ***",
},
dependencies = {},
build = {},
}
path.configure_paths(rockspec)
rockspec.source.protocol = protocol
configure_lua_version(rockspec, flags["lua-version"])
local local_dir = url_or_dir
if url_or_dir:match("://") then
rockspec.source.url = url_or_dir
rockspec.source.file = dir.base_name(url_or_dir)
rockspec.source.dir = "dummy"
if not fetch.is_basic_protocol(rockspec.source.protocol) then
if version ~= "scm" then
rockspec.source.tag = flags["tag"] or "v" .. version
end
end
rockspec.source.dir = nil
local ok, base_dir, temp_dir = get_url(rockspec)
if ok then
if base_dir ~= dir.base_name(url_or_dir) then
rockspec.source.dir = base_dir
end
end
if base_dir then
local_dir = dir.path(temp_dir, base_dir)
else
local_dir = nil
end
else
rockspec.source.url = detect_scm_url(local_dir) or rockspec.source.url
end
if not local_dir then
local_dir = "."
end
if not flags["homepage"] then
local url_protocol, url_path = dir.split_url(rockspec.source.url)
if simple_scm_protocols[url_protocol] then
for _, domain in ipairs({"github.com", "bitbucket.org", "gitlab.com"}) do
if util.starts_with(url_path, domain) then
rockspec.description.homepage = "https://"..url_path:gsub("%.git$", "")
break
end
end
end
end
local libs = nil
if flags["lib"] then
libs = {}
rockspec.external_dependencies = {}
for lib in flags["lib"]:gmatch("([^,]+)") do
table.insert(libs, lib)
rockspec.external_dependencies[lib:upper()] = {
library = lib
}
end
end
local ok, err = fs.change_dir(local_dir)
if not ok then return nil, "Failed reaching files from project - error entering directory "..local_dir end
if (not flags["summary"]) or (not flags["detailed"]) then
local summary, detailed = detect_description()
rockspec.description.summary = flags["summary"] or summary
rockspec.description.detailed = flags["detailed"] or detailed
end
local is_mit = show_license(rockspec)
if is_mit and not flags["license"] then
rockspec.description.license = "MIT"
end
fill_as_builtin(rockspec, libs)
rockspec_cleanup(rockspec)
persist.save_from_table(filename, rockspec, type_check.rockspec_order)
util.printout()
util.printout("Wrote template at "..filename.." -- you should now edit and finish it.")
util.printout()
return true
end
return write_rockspec
luarocks-2.4.2+dfsg/test/ 0000775 0000000 0000000 00000000000 13030154704 0015235 5 ustar 00root root 0000000 0000000 luarocks-2.4.2+dfsg/test/README.md 0000664 0000000 0000000 00000004315 13030154704 0016517 0 ustar 00root root 0000000 0000000 #LuaRocks testsuite
##Overview
Test suite for LuaRocks project with Busted unit testing framework(http://olivinelabs.com/busted/).
* Contains white-box & black-box tests
* Easy setup for your purpose on command line or from configuration file
## Dependencies
* Lua >= 5.1
* Busted with dependencies
##Usage
Running of tests is based on basic Busted usage. *-Xhelper* flag is mandatory for inserting arguments into testing (primary black-box). Flag *--tags=* or *-t* is mandatory for specifying which tests will run. Start tests inside LuaRocks folder or specify with *-C* flag.
**Arguments for Busted helper script**
```
lua=, !mandatory! type your full version of Lua (e.g. lua=5.2.4)
OR
luajit=, !mandatory! type your full version of LuaJIT (e.g. luajit=5.2.4)
env=, (default:"minimal") type what kind of environment to use ["minimal", "full"]
noreset, Don't reset environment after each test
clean, remove existing testing environment
appveyor, add just if running on TravisCI
travis, add just if running on TravisCI
os=, type your OS ["linux", "os x", "windows"]
```
---------------------------------------------------------------------------------------------
####_**Tags** of tests are required and are in this format:_
**whitebox** - run all whitebox tests
**blackbox** - run all blackbox tests
**ssh** - run all tests which require ssh
**mock** - run all tests which require mock LuaRocks server (upload tests)
**unix** - run all tests which are UNIX based, won't work on Windows systems
**w**\_*name-of-command* - whitebox testing of command
**b**\_*name-of-command* - blackbox testing of command
for example: `b_install` or `w_help`
###Examples
To run all tests:
`busted`
To run white-box tests in LuaRocks directory type :
`busted -t "whitebox"`
To run black-box tests just of *install* command (we defined our OS, so OS check is skipped.):
`busted -Xhelper lua=5.2.4,os=linux -t "b_install"`
To run black-box tests of *install* command, whitebox of *help* command (using *full* type of environment):
`busted -Xhelper lua=5.2.4,env=full -t "b_install", "w_help"`
To run black-box tests without tests, which use ssh:
`busted -Xhelper lua=5.2.4 -t "blackbox" --exclude-tags=ssh` luarocks-2.4.2+dfsg/test/luarocks_site.lua 0000664 0000000 0000000 00000000214 13030154704 0020604 0 ustar 00root root 0000000 0000000 -- Config file of LuaRocks site for tests
upload = {
server = "http://localhost:8080",
tool_version = "1.0.0",
api_version = "1",
} luarocks-2.4.2+dfsg/test/mock-server.lua 0000664 0000000 0000000 00000004023 13030154704 0020174 0 ustar 00root root 0000000 0000000 #!/usr/bin/env lua
--- A simple LuaRocks mock-server for testing.
local restserver = require("restserver")
local server = restserver:new():port(8080)
server:add_resource("api/tool_version", {
{
method = "GET",
path = "/",
produces = "application/json",
handler = function(query)
local json = { version = query.current }
return restserver.response():status(200):entity(json)
end
}
})
server:add_resource("api/1/{id:[0-9]+}/status", {
{
method = "GET",
path = "/",
produces = "application/json",
handler = function(query)
local json = { user_id = "123", created_at = "29.1.1993" }
return restserver.response():status(200):entity(json)
end
}
})
server:add_resource("/api/1/{id:[0-9]+}/check_rockspec", {
{
method = "GET",
path = "/",
produces = "application/json",
handler = function(query)
local json = {}
return restserver.response():status(200):entity(json)
end
}
})
server:add_resource("/api/1/{id:[0-9]+}/upload", {
{
method = "POST",
path = "/",
produces = "application/json",
handler = function(query)
local json = {module = "luasocket", version = {id = "1.0"}, module_url = "http://localhost/luasocket", manifests = "root", is_new = "is_new"}
return restserver.response():status(200):entity(json)
end
}
})
server:add_resource("/api/1/{id:[0-9]+}/upload_rock/{id:[0-9]+}", {
{
method = "POST",
path = "/",
produces = "application/json",
handler = function(query)
local json = {"rock","module_url"}
return restserver.response():status(200):entity(json)
end
}
})
-- SHUTDOWN this mock-server
server:add_resource("/shutdown", {
{
method = "GET",
path = "/",
handler = function(query)
os.exit()
return restserver.response():status(200):entity()
end
}
})
-- This loads the restserver.xavante plugin
server:enable("restserver.xavante"):start() luarocks-2.4.2+dfsg/test/test_environment.lua 0000664 0000000 0000000 00000065533 13030154704 0021357 0 ustar 00root root 0000000 0000000 local lfs = require("lfs")
local test_env = {}
local help_message = [[
LuaRocks test-suite
INFORMATION
New test-suite for LuaRocks project, using unit testing framework Busted.
REQUIREMENTS
Be sure sshd is running on your system, or use '--exclude-tags=ssh',
to not execute tests which require sshd.
USAGE
busted [-Xhelper ]
ARGUMENTS
env= Set type of environment to use ("minimal" or "full",
default: "minimal").
noreset Don't reset environment after each test
clean Remove existing testing environment.
travis Add if running on TravisCI.
appveyor Add if running on Appveyor.
os= Set OS ("linux", "osx", or "windows").
]]
local function help()
print(help_message)
os.exit(1)
end
local function title(str)
print()
print(("-"):rep(#str))
print(str)
print(("-"):rep(#str))
end
local function exists(path)
return lfs.attributes(path, "mode") ~= nil
end
--- Quote argument for shell processing. Fixes paths on Windows.
-- Adds double quotes and escapes. Based on function in fs/win32.lua.
-- @param arg string: Unquoted argument.
-- @return string: Quoted argument.
local function Q(arg)
if test_env.TEST_TARGET_OS == "windows" then
local drive_letter = "[%.a-zA-Z]?:?[\\/]"
-- Quote DIR for Windows
if arg:match("^"..drive_letter) then
arg = arg:gsub("/", "\\")
end
if arg == "\\" then
return '\\' -- CHDIR needs special handling for root dir
end
return '"' .. arg .. '"'
else
return "'" .. arg:gsub("'", "'\\''") .. "'"
end
end
function test_env.quiet(command)
if not test_env.VERBOSE then
if test_env.TEST_TARGET_OS == "windows" then
return command .. " 1> NUL 2> NUL"
else
return command .. " 1> /dev/null 2> /dev/null"
end
else
return command
end
end
function test_env.copy(source, destination)
local r_source, err = io.open(source, "r")
local r_destination, err = io.open(destination, "w")
while true do
local block = r_source:read(8192)
if not block then break end
r_destination:write(block)
end
r_source:close()
r_destination:close()
end
--- Helper function for execute_bool and execute_output
-- @param command string: command to execute
-- @param print_command boolean: print command if 'true'
-- @param env_variables table: table of environment variables to export {FOO="bar", BAR="foo"}
-- @return final_command string: concatenated command to execution
function test_env.execute_helper(command, print_command, env_variables)
local final_command = ""
if print_command then
print("\n[EXECUTING]: " .. command)
end
if env_variables then
if test_env.TEST_TARGET_OS == "windows" then
for k,v in pairs(env_variables) do
final_command = final_command .. "set " .. k .. "=" .. v .. "&"
end
final_command = final_command:sub(1, -2) .. "&"
else
final_command = "export "
for k,v in pairs(env_variables) do
final_command = final_command .. k .. "='" .. v .. "' "
end
-- remove last space and add ';' to separate exporting variables from command
final_command = final_command:sub(1, -2) .. "; "
end
end
final_command = final_command .. command .. " 2>&1"
return final_command
end
--- Execute command and returns true/false
-- @return true/false boolean: status of the command execution
local function execute_bool(command, print_command, env_variables)
command = test_env.execute_helper(command, print_command, env_variables)
local redirect_filename
local redirect = ""
if print_command ~= nil then
redirect_filename = test_env.testing_paths.luarocks_tmp.."/output.txt"
redirect = " > "..redirect_filename
end
local ok = os.execute(command .. redirect)
ok = (ok == true or ok == 0) -- normalize Lua 5.1 output to boolean
if redirect ~= "" then
if not ok then
local fd = io.open(redirect_filename, "r")
if fd then
print(fd:read("*a"))
fd:close()
end
end
os.remove(redirect_filename)
end
return ok
end
--- Execute command and returns output of command
-- @return output string: output the command execution
local function execute_output(command, print_command, env_variables)
command = test_env.execute_helper(command, print_command, env_variables)
local file = assert(io.popen(command))
local output = file:read('*all')
file:close()
return output:gsub("\n","") -- output adding new line, need to be removed
end
--- Set test_env.LUA_V or test_env.LUAJIT_V based
-- on version of Lua used to run this script.
function test_env.set_lua_version()
if _G.jit then
test_env.LUAJIT_V = _G.jit.version:match("(2%.%d)%.%d")
else
test_env.LUA_V = _VERSION:match("5%.%d")
end
end
--- Set all arguments from input into global variables
function test_env.set_args()
-- if at least Lua/LuaJIT version argument was found on input start to parse other arguments to env. variables
test_env.TYPE_TEST_ENV = "minimal"
test_env.OPENSSL_DIRS = ""
test_env.RESET_ENV = true
for _, argument in ipairs(arg) do
if argument:find("^env=") then
test_env.TYPE_TEST_ENV = argument:match("^env=(.*)$")
elseif argument == "noreset" then
test_env.RESET_ENV = false
elseif argument == "clean" then
test_env.TEST_ENV_CLEAN = true
elseif argument == "verbose" then
test_env.VERBOSE = true
elseif argument == "travis" then
test_env.TRAVIS = true
elseif argument == "appveyor" then
test_env.APPVEYOR = true
test_env.OPENSSL_DIRS = "OPENSSL_LIBDIR=C:\\OpenSSL-Win32\\lib OPENSSL_INCDIR=C:\\OpenSSL-Win32\\include"
elseif argument:find("^os=") then
test_env.TEST_TARGET_OS = argument:match("^os=(.*)$")
elseif argument == "mingw" then
test_env.MINGW = true
elseif argument == "vs" then
test_env.MINGW = false
else
help()
end
end
if not test_env.TEST_TARGET_OS then
title("OS CHECK")
if execute_bool("sw_vers") then
test_env.TEST_TARGET_OS = "osx"
if test_env.TRAVIS then
test_env.OPENSSL_DIRS = "OPENSSL_LIBDIR=/usr/local/opt/openssl/lib OPENSSL_INCDIR=/usr/local/opt/openssl/include"
end
elseif execute_output("uname -s") == "Linux" then
test_env.TEST_TARGET_OS = "linux"
else
test_env.TEST_TARGET_OS = "windows"
end
end
return true
end
function test_env.copy_dir(source_path, target_path)
local testing_paths = test_env.testing_paths
if test_env.TEST_TARGET_OS == "windows" then
execute_bool(testing_paths.win_tools .. "/cp -R ".. source_path .. "/. " .. target_path)
else
execute_bool("cp -a ".. source_path .. "/. " .. target_path)
end
end
--- Remove directory recursively
-- @param path string: directory path to delete
function test_env.remove_dir(path)
if exists(path) then
for file in lfs.dir(path) do
if file ~= "." and file ~= ".." then
local full_path = path..'/'..file
if lfs.attributes(full_path, "mode") == "directory" then
test_env.remove_dir(full_path)
else
os.remove(full_path)
end
end
end
end
lfs.rmdir(path)
end
--- Remove subdirectories of a directory that match a pattern
-- @param path string: path to directory
-- @param pattern string: pattern matching basenames of subdirectories to be removed
function test_env.remove_subdirs(path, pattern)
if exists(path) then
for file in lfs.dir(path) do
if file ~= "." and file ~= ".." then
local full_path = path..'/'..file
if lfs.attributes(full_path, "mode") == "directory" and file:find(pattern) then
test_env.remove_dir(full_path)
end
end
end
end
end
--- Remove files matching a pattern
-- @param path string: directory where to delete files
-- @param pattern string: pattern matching basenames of files to be deleted
-- @return result_check boolean: true if one or more files deleted
function test_env.remove_files(path, pattern)
local result_check = false
if exists(path) then
for file in lfs.dir(path) do
if file ~= "." and file ~= ".." then
if file:find(pattern) then
if os.remove(path .. "/" .. file) then
result_check = true
end
end
end
end
end
return result_check
end
--- Function for downloading rocks and rockspecs
-- @param urls table: array of full names of rocks/rockspecs to download
-- @param save_path string: path to directory, where to download rocks/rockspecs
-- @return make_manifest boolean: true if new rocks downloaded
local function download_rocks(urls, save_path)
local luarocks_repo = "https://www.luarocks.org"
local make_manifest = false
for _, url in ipairs(urls) do
-- check if already downloaded
if not exists(save_path .. url) then
if test_env.TEST_TARGET_OS == "windows" then
execute_bool(test_env.testing_paths.win_tools .. "/wget -cP " .. save_path .. " " .. luarocks_repo .. url .. " --no-check-certificate")
else
execute_bool("wget -cP " .. save_path .. " " .. luarocks_repo .. url)
end
make_manifest = true
end
end
return make_manifest
end
--- Create a file containing a string.
-- @param path string: path to file.
-- @param str string: content of the file.
local function write_file(path, str)
local file = assert(io.open(path, "w"))
file:write(str)
file:close()
end
--- Create md5sum of directory structure recursively, based on filename and size
-- @param path string: path to directory for generate md5sum
-- @return md5sum string: md5sum of directory
local function hash_environment(path)
if test_env.TEST_TARGET_OS == "linux" then
return execute_output("find " .. path .. " -printf \"%s %p\n\" | md5sum")
elseif test_env.TEST_TARGET_OS == "osx" then
return execute_output("find " .. path .. " -type f -exec stat -f \"%z %N\" {} \\; | md5")
elseif test_env.TEST_TARGET_OS == "windows" then
return execute_output("\"" .. Q(test_env.testing_paths.win_tools .. "/find") .. " " .. Q(path)
.. " -printf \"%s %p\"\" > temp_sum.txt && certUtil -hashfile temp_sum.txt && del temp_sum.txt")
end
end
--- Create environment variables needed for tests
-- @param testing_paths table: table with paths to testing directory
-- @return env_variables table: table with created environment variables
local function create_env(testing_paths)
local luaversion_short = _VERSION:gsub("Lua ", "")
if test_env.LUAJIT_V then
luaversion_short="5.1"
end
local env_variables = {}
env_variables.LUA_VERSION = luaversion_short
env_variables.LUAROCKS_CONFIG = testing_paths.testing_dir .. "/testing_config.lua"
env_variables.LUA_PATH = testing_paths.testing_tree .. "/share/lua/" .. luaversion_short .. "/?.lua;"
env_variables.LUA_PATH = env_variables.LUA_PATH .. testing_paths.testing_tree .. "/share/lua/".. luaversion_short .. "/?/init.lua;"
env_variables.LUA_PATH = env_variables.LUA_PATH .. testing_paths.testing_sys_tree .. "/share/lua/" .. luaversion_short .. "/?.lua;"
env_variables.LUA_PATH = env_variables.LUA_PATH .. testing_paths.testing_sys_tree .. "/share/lua/".. luaversion_short .. "/?/init.lua;"
env_variables.LUA_PATH = env_variables.LUA_PATH .. testing_paths.src_dir .. "/?.lua;"
env_variables.LUA_CPATH = testing_paths.testing_tree .. "/lib/lua/" .. luaversion_short .. "/?.so;"
.. testing_paths.testing_sys_tree .. "/lib/lua/" .. luaversion_short .. "/?.so;"
env_variables.PATH = os.getenv("PATH") .. ";" .. testing_paths.testing_tree .. "/bin;" .. testing_paths.testing_sys_tree .. "/bin;"
return env_variables
end
--- Create md5sums of origin system and system-copy testing directory
-- @param testing_paths table: table with paths to testing directory
-- @return md5sums table: table of md5sums of system and system-copy testing directory
local function create_md5sums(testing_paths)
local md5sums = {}
md5sums.testing_tree_copy_md5 = hash_environment(testing_paths.testing_tree_copy)
md5sums.testing_sys_tree_copy_md5 = hash_environment(testing_paths.testing_sys_tree_copy)
return md5sums
end
local function make_run_function(cmd_name, exec_function, with_coverage, do_print)
local cmd_prefix = Q(test_env.testing_paths.lua) .. " "
if with_coverage then
cmd_prefix = cmd_prefix .. "-e \"require('luacov.runner')('" .. test_env.testing_paths.testing_dir .. "/luacov.config')\" "
end
if test_env.TEST_TARGET_OS == "windows" then
cmd_prefix = cmd_prefix .. Q(test_env.testing_paths.testing_lrprefix .. "/" .. cmd_name .. ".lua") .. " "
else
cmd_prefix = cmd_prefix .. test_env.testing_paths.src_dir .. "/bin/" .. cmd_name .. " "
end
return function(cmd, new_vars)
local temp_vars = {}
for k, v in pairs(test_env.env_variables) do
temp_vars[k] = v
end
if new_vars then
for k, v in pairs(new_vars) do
temp_vars[k] = v
end
end
return exec_function(cmd_prefix .. cmd, do_print, temp_vars)
end
end
local function make_run_functions()
return {
luarocks = make_run_function("luarocks", execute_output, true, true),
luarocks_bool = make_run_function("luarocks", execute_bool, true, true),
luarocks_noprint = make_run_function("luarocks", execute_bool, true, false),
luarocks_nocov = make_run_function("luarocks", execute_bool, false, true),
luarocks_noprint_nocov = make_run_function("luarocks", execute_bool, false, false),
luarocks_admin = make_run_function("luarocks-admin", execute_output, true, true),
luarocks_admin_bool = make_run_function("luarocks-admin", execute_bool, true, true),
luarocks_admin_nocov = make_run_function("luarocks-admin", execute_bool, false, false)
}
end
--- Rebuild environment.
-- Remove old installed rocks and install new ones,
-- updating manifests and tree copies.
local function build_environment(rocks, env_variables)
title("BUILDING ENVIRONMENT")
local testing_paths = test_env.testing_paths
test_env.remove_dir(testing_paths.testing_tree)
test_env.remove_dir(testing_paths.testing_sys_tree)
test_env.remove_dir(testing_paths.testing_tree_copy)
test_env.remove_dir(testing_paths.testing_sys_tree_copy)
lfs.mkdir(testing_paths.testing_tree)
lfs.mkdir(testing_paths.testing_sys_tree)
test_env.run.luarocks_admin_nocov("make_manifest " .. Q(testing_paths.testing_server))
test_env.run.luarocks_admin_nocov("make_manifest " .. Q(testing_paths.testing_cache))
for _, rock in ipairs(rocks) do
if not test_env.run.luarocks_nocov("install --only-server=" .. testing_paths.testing_cache .. " --tree=" .. testing_paths.testing_sys_tree .. " " .. Q(rock), env_variables) then
test_env.run.luarocks_nocov("build --tree=" .. Q(testing_paths.testing_sys_tree) .. " " .. Q(rock) .. "", env_variables)
test_env.run.luarocks_nocov("pack --tree=" .. Q(testing_paths.testing_sys_tree) .. " " .. Q(rock), env_variables)
if test_env.TEST_TARGET_OS == "windows" then
execute_bool(testing_paths.win_tools .. "/mv " .. rock .. "-*.rock " .. testing_paths.testing_cache)
else
execute_bool("mv " .. rock .. "-*.rock " .. testing_paths.testing_cache)
end
end
end
test_env.copy_dir(testing_paths.testing_tree, testing_paths.testing_tree_copy)
test_env.copy_dir(testing_paths.testing_sys_tree, testing_paths.testing_sys_tree_copy)
end
--- Reset testing environment
local function reset_environment(testing_paths, md5sums)
local testing_tree_md5 = hash_environment(testing_paths.testing_tree)
local testing_sys_tree_md5 = hash_environment(testing_paths.testing_sys_tree)
if testing_tree_md5 ~= md5sums.testing_tree_copy_md5 then
test_env.remove_dir(testing_paths.testing_tree)
test_env.copy_dir(testing_paths.testing_tree_copy, testing_paths.testing_tree)
end
if testing_sys_tree_md5 ~= md5sums.testing_sys_tree_copy_md5 then
test_env.remove_dir(testing_paths.testing_sys_tree)
test_env.copy_dir(testing_paths.testing_sys_tree_copy, testing_paths.testing_sys_tree)
end
print("\n[ENVIRONMENT RESET]")
end
local function create_paths(luaversion_full)
local cfg = require("luarocks.cfg")
local testing_paths = {}
testing_paths.luadir = cfg.variables.LUA_BINDIR:gsub("/bin/?$", "")
testing_paths.lua = cfg.variables.LUA_BINDIR .. "/" .. cfg.lua_interpreter
if test_env.TEST_TARGET_OS == "windows" then
testing_paths.luarocks_tmp = os.getenv("TEMP")
else
testing_paths.luarocks_tmp = "/tmp/luarocks_testing"
end
testing_paths.luarocks_dir = lfs.currentdir()
if test_env.TEST_TARGET_OS == "windows" then
testing_paths.luarocks_dir = testing_paths.luarocks_dir:gsub("\\","/")
end
testing_paths.testing_dir = testing_paths.luarocks_dir .. "/test"
testing_paths.src_dir = testing_paths.luarocks_dir .. "/src"
testing_paths.testing_lrprefix = testing_paths.testing_dir .. "/testing_lrprefix-" .. luaversion_full
testing_paths.testing_tree = testing_paths.testing_dir .. "/testing-" .. luaversion_full
testing_paths.testing_tree_copy = testing_paths.testing_dir .. "/testing_copy-" .. luaversion_full
testing_paths.testing_sys_tree = testing_paths.testing_dir .. "/testing_sys-" .. luaversion_full
testing_paths.testing_sys_tree_copy = testing_paths.testing_dir .. "/testing_sys_copy-" .. luaversion_full
testing_paths.testing_cache = testing_paths.testing_dir .. "/testing_cache-" .. luaversion_full
testing_paths.testing_server = testing_paths.testing_dir .. "/testing_server-" .. luaversion_full
if test_env.TEST_TARGET_OS == "windows" then
testing_paths.win_tools = testing_paths.testing_lrprefix .. "/tools"
end
return testing_paths
end
--- Helper function to unload luarocks modules from global table package.loaded
-- Needed to load our local (testing) version of LuaRocks
function test_env.unload_luarocks()
for modname, _ in pairs(package.loaded) do
if modname:match("^luarocks%.") then
package.loaded[modname] = nil
end
end
end
--- Function for initially setup of environment, variables, md5sums for spec files
function test_env.setup_specs(extra_rocks)
-- if global variable about successful creation of testing environment doesn't exists, build environment
if not test_env.setup_done then
if test_env.TRAVIS then
if not exists(os.getenv("HOME") .. "/.ssh/id_rsa.pub") then
execute_bool("ssh-keygen -t rsa -P \"\" -f ~/.ssh/id_rsa")
execute_bool("cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys")
execute_bool("chmod og-wx ~/.ssh/authorized_keys")
execute_bool("ssh-keyscan localhost >> ~/.ssh/known_hosts")
end
end
test_env.main()
package.path = test_env.env_variables.LUA_PATH
test_env.platform = execute_output(test_env.testing_paths.lua .. " -e \"print(require('luarocks.cfg').arch)\"", false, test_env.env_variables)
test_env.lib_extension = execute_output(test_env.testing_paths.lua .. " -e \"print(require('luarocks.cfg').lib_extension)\"", false, test_env.env_variables)
test_env.wrapper_extension = test_env.TEST_TARGET_OS == "windows" and ".bat" or ""
test_env.md5sums = create_md5sums(test_env.testing_paths)
test_env.setup_done = true
title("RUNNING TESTS")
end
if extra_rocks then
local make_manifest = download_rocks(extra_rocks, test_env.testing_paths.testing_server)
if make_manifest then
test_env.run.luarocks_admin_nocov("make_manifest " .. test_env.testing_paths.testing_server)
end
end
if test_env.RESET_ENV then
reset_environment(test_env.testing_paths, test_env.md5sums, test_env.env_variables)
end
end
--- Test if required rock is installed if not, install it
function test_env.need_rock(rock)
print("Check if " .. rock .. " is installed")
if test_env.run.luarocks_noprint_nocov(test_env.quiet("show " .. rock)) then
return true
else
return test_env.run.luarocks_noprint_nocov(test_env.quiet("install " .. rock))
end
end
--- For each key-value pair in replacements table
-- replace %{key} in given string with value.
local function substitute(str, replacements)
return (str:gsub("%%%b{}", function(marker)
return replacements[marker:sub(3, -2)]
end))
end
--- Create configs for luacov and several versions of Luarocks
-- configs needed for some tests.
local function create_configs()
-- testing_config.lua and testing_config_show_downloads.lua
local config_content = substitute([[
rocks_trees = {
"%{testing_tree}",
{ name = "system", root = "%{testing_sys_tree}" },
}
rocks_servers = {
"%{testing_server}"
}
local_cache = "%{testing_cache}"
upload_server = "testing"
upload_user = "%{user}"
upload_servers = {
testing = {
rsync = "localhost/tmp/luarocks_testing",
},
}
external_deps_dirs = {
"/usr/local",
"/usr",
-- These are used for a test that fails, so it
-- can point to invalid paths:
{
prefix = "/opt",
bin = "bin",
include = "include",
lib = { "lib", "lib64" },
}
}
]], {
user = os.getenv("USER"),
testing_sys_tree = test_env.testing_paths.testing_sys_tree,
testing_tree = test_env.testing_paths.testing_tree,
testing_server = test_env.testing_paths.testing_server,
testing_cache = test_env.testing_paths.testing_cache
})
write_file(test_env.testing_paths.testing_dir .. "/testing_config.lua", config_content .. " \nweb_browser = \"true\"")
write_file(test_env.testing_paths.testing_dir .. "/testing_config_show_downloads.lua", config_content
.. "show_downloads = true \n rocks_servers={\"http://luarocks.org/repositories/rocks\"}")
-- testing_config_sftp.lua
config_content = substitute([[
rocks_trees = {
"%{testing_tree}",
"%{testing_sys_tree}",
}
local_cache = "%{testing_cache}"
upload_server = "testing"
upload_user = "%{user}"
upload_servers = {
testing = {
sftp = "localhost/tmp/luarocks_testing",
},
}
]], {
user = os.getenv("USER"),
testing_sys_tree = test_env.testing_paths.testing_sys_tree,
testing_tree = test_env.testing_paths.testing_tree,
testing_cache = test_env.testing_paths.testing_cache
})
write_file(test_env.testing_paths.testing_dir .. "/testing_config_sftp.lua", config_content)
-- luacov.config
config_content = substitute([[
return {
statsfile = "%{testing_dir}/luacov.stats.out",
reportfile = "%{testing_dir}/luacov.report.out",
modules = {
["luarocks"] = "src/bin/luarocks",
["luarocks-admin"] = "src/bin/luarocks-admin",
["luarocks.*"] = "src",
["luarocks.*.*"] = "src",
["luarocks.*.*.*"] = "src"
}
}
]], {
testing_dir = test_env.testing_paths.testing_dir
})
write_file(test_env.testing_paths.testing_dir .. "/luacov.config", config_content)
end
--- Remove testing directories.
local function clean()
print("Cleaning testing directory...")
test_env.remove_dir(test_env.testing_paths.luarocks_tmp)
test_env.remove_subdirs(test_env.testing_paths.testing_dir, "testing[_%-]")
test_env.remove_files(test_env.testing_paths.testing_dir, "testing_")
test_env.remove_files(test_env.testing_paths.testing_dir, "luacov")
test_env.remove_files(test_env.testing_paths.testing_dir, "upload_config")
print("Cleaning done!")
end
--- Install luarocks into testing prefix.
local function install_luarocks(install_env_vars)
local testing_paths = test_env.testing_paths
title("Installing LuaRocks")
if test_env.TEST_TARGET_OS == "windows" then
local compiler_flag = test_env.MINGW and "/MW" or ""
assert(execute_bool("install.bat /LUA " .. testing_paths.luadir .. " " .. compiler_flag .. " /P " .. testing_paths.testing_lrprefix .. " /NOREG /NOADMIN /F /Q /CONFIG " .. testing_paths.testing_lrprefix .. "/etc/luarocks", false, install_env_vars))
assert(execute_bool(testing_paths.win_tools .. "/cp " .. testing_paths.testing_lrprefix .. "/lua/luarocks/site_config* " .. testing_paths.src_dir .. "/luarocks/site_config.lua"))
else
local configure_cmd = "./configure --with-lua=" .. testing_paths.luadir .. " --prefix=" .. testing_paths.testing_lrprefix
assert(execute_bool(configure_cmd, false, install_env_vars))
assert(execute_bool("make clean", false, install_env_vars))
assert(execute_bool("make src/luarocks/site_config.lua", false, install_env_vars))
assert(execute_bool("make dev", false, install_env_vars))
end
print("LuaRocks installed correctly!")
end
---
-- Main function to create config files and testing environment
function test_env.main()
local testing_paths = test_env.testing_paths
if test_env.TEST_ENV_CLEAN then
clean()
end
lfs.mkdir(testing_paths.testing_cache)
lfs.mkdir(testing_paths.luarocks_tmp)
create_configs()
local install_env_vars = {
LUAROCKS_CONFIG = test_env.testing_paths.testing_dir .. "/testing_config.lua"
}
install_luarocks(install_env_vars)
-- Preparation of rocks for building environment
local rocks = {} -- names of rocks, required for building environment
local urls = {} -- names of rock and rockspec files to be downloaded
table.insert(urls, "/luacov-0.11.0-1.rockspec")
table.insert(urls, "/luacov-0.11.0-1.src.rock")
if test_env.TYPE_TEST_ENV == "full" then
table.insert(urls, "/luafilesystem-1.6.3-1.src.rock")
table.insert(urls, "/luasocket-3.0rc1-1.src.rock")
table.insert(urls, "/luasocket-3.0rc1-1.rockspec")
table.insert(urls, "/luaposix-33.2.1-1.src.rock")
table.insert(urls, "/md5-1.2-1.src.rock")
table.insert(urls, "/lzlib-0.4.1.53-1.src.rock")
rocks = {"luafilesystem", "luasocket", "luaposix", "md5", "lzlib"}
if test_env.LUA_V ~= "5.1" then
table.insert(urls, "/luabitop-1.0.2-1.rockspec")
table.insert(urls, "/luabitop-1.0.2-1.src.rock")
table.insert(rocks, "luabitop")
end
end
table.insert(rocks, "luacov") -- luacov is needed for minimal or full environment
-- Download rocks needed for LuaRocks testing environment
lfs.mkdir(testing_paths.testing_server)
download_rocks(urls, testing_paths.testing_server)
build_environment(rocks, install_env_vars)
end
test_env.set_lua_version()
test_env.set_args()
test_env.testing_paths = create_paths(test_env.LUA_V or test_env.LUAJIT_V)
test_env.env_variables = create_env(test_env.testing_paths)
test_env.run = make_run_functions()
return test_env
luarocks-2.4.2+dfsg/test/testfiles/ 0000775 0000000 0000000 00000000000 13030154704 0017237 5 ustar 00root root 0000000 0000000 luarocks-2.4.2+dfsg/test/testfiles/invalid_patch-0.1-1.rockspec 0000664 0000000 0000000 00000001330 13030154704 0024226 0 ustar 00root root 0000000 0000000 package = "invalid_patch"
version = "0.1-1"
source = {
-- any valid URL
url = "https://raw.github.com/keplerproject/luarocks/master/src/luarocks/build.lua"
}
description = {
summary = "A rockspec with an invalid patch",
}
dependencies = {
"lua >= 5.1"
}
build = {
type = "builtin",
modules = {
build = "build.lua"
},
patches = {
["I_am_an_invalid_patch.patch"] =
[[
diff -Naur luadoc-3.0.1/src/luadoc/doclet/html.lua luadoc-3.0.1-new/src/luadoc/doclet/html.lua
--- luadoc-3.0.1/src/luadoc/doclet/html.lua2007-12-21 15:50:48.000000000 -0200
+++ luadoc-3.0.1-new/src/luadoc/doclet/html.lua2008-02-28 01:59:53.000000000 -0300
@@ -18,6 +18,7 @@
- gabba gabba gabba
+ gobo gobo gobo
]]
}
}
luarocks-2.4.2+dfsg/test/testfiles/invalid_validate-args-1.5.4-1.rockspec 0000664 0000000 0000000 00000001451 13030154704 0026025 0 ustar 00root root 0000000 0000000 package = 'validate-args'
version = '1.5.4-1'
source = {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{++{
url = "https://bitbucket.org/djerius/validate.args/downloads/validate-args-1.5.4.tar.gz"
}
description = {
summary = "Function argument validation",
detailed = [[
validate.args is a Lua module that provides a framework for
validation of arguments to Lua functions as well as complex data
structures. The included validate.inplace module provides "live"
validation during assignment of values to elements in tables. ]],
license = "GPL-3",
}
dependencies = {
"lua >= 5.1"
}
build = {
type = "builtin",
modules = {
["validate.args"] = "validate/args.lua",
["validate.inplace"] = "validate/inplace.lua",
},
copy_directories = {
"doc", "tests"
}
}
luarocks-2.4.2+dfsg/test/testfiles/missing_external-0.1-1.rockspec 0000664 0000000 0000000 00000000722 13030154704 0025000 0 ustar 00root root 0000000 0000000 package = "missing_external"
version = "0.1-1"
source = {
-- any valid URL
url = "https://raw.github.com/keplerproject/luarocks/master/src/luarocks/build.lua"
}
description = {
summary = "Missing external dependency",
}
external_dependencies = {
INEXISTENT = {
library = "inexistentlib*",
header = "inexistentheader*.h",
}
}
dependencies = {
"lua >= 5.1"
}
build = {
type = "builtin",
modules = {
build = "build.lua"
}
}
luarocks-2.4.2+dfsg/test/testfiles/mixed_deploy_type/ 0000775 0000000 0000000 00000000000 13030154704 0022762 5 ustar 00root root 0000000 0000000 luarocks-2.4.2+dfsg/test/testfiles/mixed_deploy_type/mdt.c 0000664 0000000 0000000 00000000140 13030154704 0023705 0 ustar 00root root 0000000 0000000 #include "lua.h"
int luaopen_mdt(lua_State *L) {
lua_pushstring(L, "mdt.c");
return 1;
}
luarocks-2.4.2+dfsg/test/testfiles/mixed_deploy_type/mdt.lua 0000664 0000000 0000000 00000000021 13030154704 0024242 0 ustar 00root root 0000000 0000000 return "mdt.lua"
luarocks-2.4.2+dfsg/test/testfiles/mixed_deploy_type/mdt_file 0000664 0000000 0000000 00000000022 13030154704 0024462 0 ustar 00root root 0000000 0000000 return "mdt_file"
luarocks-2.4.2+dfsg/test/testfiles/mixed_deploy_type/mixed_deploy_type-0.1.0-1.rockspec 0000664 0000000 0000000 00000000562 13030154704 0031033 0 ustar 00root root 0000000 0000000 package = "mixed_deploy_type"
version = "0.1.0-1"
source = {
url = "http://example.com"
}
description = {
homepage = "http://example.com",
license = "*** please specify a license ***"
}
dependencies = {}
build = {
type = "builtin",
modules = {
mdt = "mdt/mdt.lua"
},
install = {
lua = {
mdt_file = "mdt/mdt_file"
}
}
}
luarocks-2.4.2+dfsg/test/testfiles/mixed_deploy_type/mixed_deploy_type-0.2.0-1.rockspec 0000664 0000000 0000000 00000000560 13030154704 0031032 0 ustar 00root root 0000000 0000000 package = "mixed_deploy_type"
version = "0.2.0-1"
source = {
url = "http://example.com"
}
description = {
homepage = "http://example.com",
license = "*** please specify a license ***"
}
dependencies = {}
build = {
type = "builtin",
modules = {
mdt = "mdt/mdt.c"
},
install = {
lib = {
mdt_file = "mdt/mdt_file"
}
}
}
luarocks-2.4.2+dfsg/test/testfiles/no_build_table-0.1-1.rockspec 0000664 0000000 0000000 00000000411 13030154704 0024362 0 ustar 00root root 0000000 0000000 package = "no_build_table"
version = "0.1-1"
source = {
-- any valid URL
url = "https://raw.github.com/keplerproject/luarocks/master/src/luarocks/build.lua"
}
description = {
summary = "A rockspec with no build field",
}
dependencies = {
"lua >= 5.1"
}
luarocks-2.4.2+dfsg/test/testfiles/not_a_zipfile-1.0-1.src.rock 0000664 0000000 0000000 00000000026 13030154704 0024157 0 ustar 00root root 0000000 0000000 I am not a .zip file!
luarocks-2.4.2+dfsg/test/testfiles/type_mismatch_string-1.0-1.rockspec 0000664 0000000 0000000 00000000056 13030154704 0025661 0 ustar 00root root 0000000 0000000
package="type_mismatch_version"
version=1.0
luarocks-2.4.2+dfsg/test/testfiles/type_mismatch_table-1.0-1.rockspec 0000664 0000000 0000000 00000000107 13030154704 0025437 0 ustar 00root root 0000000 0000000
package="type_mismatch_table"
version="1.0-1"
source = "not a table"
luarocks-2.4.2+dfsg/test/testfiles/type_mismatch_version-1.0-1.rockspec 0000664 0000000 0000000 00000000060 13030154704 0026033 0 ustar 00root root 0000000 0000000
package="type_mismatch_version"
version="1.0"