Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/has_cxxtypes.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file has_cxxtypes.lua
--
-- imports
import("lib.detect.check_cxsnippets")
-- has the given c++ types?
--
-- @param types the types
-- @param opt the argument options
-- e.g.
-- { verbose = false, target = [target|option], includes = .., configs = {defines = .., ..}}
--
-- @return true or false
--
-- @code
-- local ok = has_cxxtypes("wchar_t")
-- local ok = has_cxxtypes({"char*", "wchar_t"}, {includes = "stdio.h"})
-- @endcode
--
function main(types, opt)
-- init options
opt = opt or {}
-- init types
opt.sourcekind = "cxx"
opt.types = types
-- has types?
local name = opt.name or "has_cxxtypes"
return check_cxsnippets({[name] = ""}, opt)
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/check_cxsnippets.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file check_cxsnippets.lua
--
-- imports
import("core.base.option")
import("core.tool.linker")
import("core.tool.compiler")
import("core.language.language")
-- get function name
--
-- sigsetjmp
-- sigsetjmp((void*)0, 0)
-- sigsetjmp{sigsetjmp((void*)0, 0);}
-- sigsetjmp{int a = 0; sigsetjmp((void*)a, a);}
--
function _funcname(funcinfo)
-- parse function name
local name = string.match(funcinfo, "(.+){.+}")
if name == nil then
local pos = funcinfo:find("%(")
if pos then
name = funcinfo:sub(1, pos - 1)
else
name = funcinfo
end
end
-- ok
return name:trim()
end
-- get function code
--
-- sigsetjmp
-- sigsetjmp((void*)0, 0)
-- sigsetjmp{sigsetjmp((void*)0, 0);}
-- sigsetjmp{int a = 0; sigsetjmp((void*)a, a);}
--
function _funccode(funcinfo)
local code = string.match(funcinfo, ".+{(.+)}")
if code == nil then
local pos = funcinfo:find("%(")
if pos then
code = funcinfo
else
code = string.format("volatile void* p%s = (void*)&%s; if (p%s) {}", funcinfo, funcinfo, funcinfo)
end
end
return code
end
-- make source code
function _sourcecode(snippets, opt)
-- has main()?
local has_main = false
for _, snippet in pairs(snippets) do
-- find int main(int argc, char** argv) {}
if snippet:find("int%s+main%s*%(.-%)%s*{") then
has_main = true
break
end
end
-- add includes
local sourcecode = ""
local includes = table.wrap(opt.includes)
if not has_main and opt.tryrun and opt.output then
table.insert(includes, "stdio.h")
end
for _, include in ipairs(includes) do
sourcecode = format("%s\n#include <%s>", sourcecode, include)
end
sourcecode = sourcecode .. "\n"
-- add types
for _, typename in ipairs(opt.types) do
sourcecode = format("%s\ntypedef %s __type_%s;", sourcecode, typename, typename:gsub("[^%a]", "_"))
end
sourcecode = sourcecode .. "\n"
-- we just add all snippets if has main function
-- @see https://github.com/xmake-io/xmake/issues/3527
if has_main then
for _, snippet in pairs(snippets) do
sourcecode = sourcecode .. "\n" .. snippet
end
sourcecode = sourcecode .. "\n"
return sourcecode
end
-- add snippets (build only)
if not opt.tryrun then
for _, snippet in pairs(snippets) do
sourcecode = sourcecode .. "\n" .. snippet
end
sourcecode = sourcecode .. "\n"
end
-- enter main function
sourcecode = sourcecode .. "int main(int argc, char** argv)\n{\n"
-- add funcs
for _, funcinfo in ipairs(opt.funcs) do
sourcecode = format("%s\n %s;", sourcecode, _funccode(funcinfo))
end
-- add snippets (tryrun)
if opt.tryrun then
for _, snippet in pairs(snippets) do
sourcecode = sourcecode .. "\n" .. snippet
end
if opt.output then
sourcecode = sourcecode .. "\nfflush(stdout);\n"
end
sourcecode = sourcecode .. "\n}\n" -- we need return exit code in snippet
else
-- leave main function
sourcecode = sourcecode .. "\n return 0;\n}\n"
end
return sourcecode
end
-- check the given c/c++ snippets?
--
-- @param snippets the snippets
-- @param opt the argument options
-- e.g.
-- { verbose = false, target = [target|option], sourcekind = "[cc|cxx|mm|mxx]"
-- , types = {"wchar_t", "char*"}, includes = "stdio.h", funcs = {"sigsetjmp", "sigsetjmp((void*)0, 0)"}
-- , configs = {defines = "xx", cxflags = ""}
-- , tryrun = true, output = true}
--
-- funcs:
-- sigsetjmp
-- sigsetjmp((void*)0, 0)
-- sigsetjmp{sigsetjmp((void*)0, 0);}
-- sigsetjmp{int a = 0; sigsetjmp((void*)a, a);}
--
-- @return true or false
--
-- @code
-- local ok, output_or_errors = check_cxsnippets("void test() {}")
-- local ok, output_or_errors = check_cxsnippets({"void test(){}", "#define TEST 1"}, {types = "wchar_t", includes = "stdio.h"})
-- local ok, output_or_errors = check_cxsnippets({snippet_name = "void test(){}", "#define TEST 1"}, {types = "wchar_t", includes = "stdio.h"})
-- local ok, output_or_errors = check_cxsnippets([[
-- int test() {
-- return (sizeof(int) == 4)? 0 : -1;
-- }
-- int main(int argc, char** argv) {
-- return test();
-- }]], {tryrun = true})
-- @endcode
--
function main(snippets, opt)
-- init options
opt = opt or {}
-- init snippets
snippets = snippets or {}
-- get configs
local configs = opt.configs or opt.config
-- get links
local links = {}
local target = opt.target
if configs and configs.links then
table.join2(links, configs.links)
end
if target and target:type() ~= "package" then
table.join2(links, target:get("links"))
end
if configs and configs.syslinks then
table.join2(links, configs.syslinks)
end
if target and target:type() ~= "package" then
table.join2(links, opt.target:get("syslinks"))
end
-- get types
local types = table.wrap(opt.types)
-- get includes
local includes = table.wrap(opt.includes)
-- get funcs
local funcs = {}
for _, funcinfo in ipairs(opt.funcs) do
table.insert(funcs, _funcname(funcinfo))
end
-- make source code
local sourcecode = _sourcecode(snippets, opt)
-- get c/c++ extension
local extension = ".c"
local sourcekind = opt.sourcekind
if sourcekind then
extension = table.wrap(language.sourcekinds()[sourcekind])[1] or ".c"
end
-- make the source file
-- @note we use fixed temporary filenames in order to better cache the compilation results for build_cache.
local tmpfile = os.tmpfile(sourcecode)
local sourcefile = tmpfile .. extension
local objectfile = os.tmpfile() .. ".o"
local binaryfile = objectfile:gsub("%.o$", ".b")
if not os.isfile(sourcefile) then
io.writefile(sourcefile, sourcecode)
end
-- @note cannot cache result, all conditions will be changed
-- attempt to compile it
local errors = nil
local ok, output = try
{
function ()
if option.get("diagnosis") then
cprint("${dim}> %s", compiler.compcmd(sourcefile, objectfile, opt))
end
opt = table.clone(opt)
opt.build_warnings = false
compiler.compile(sourcefile, objectfile, opt)
if #links > 0 or opt.tryrun or opt.binary_match then
if option.get("diagnosis") then
cprint("${dim}> %s", linker.linkcmd("binary", {"cc", "cxx"}, objectfile, binaryfile, opt))
end
linker.link("binary", {"cc", "cxx"}, objectfile, binaryfile, opt)
end
if opt.tryrun then
if opt.output then
local output = os.iorun(binaryfile)
if output then
output = output:trim()
end
return true, output
else
os.vrun(binaryfile)
end
end
local binary_match = opt.binary_match
if binary_match then
local content = io.readfile(binaryfile, {encoding = "binary"})
local match = type(binary_match) == "function" and binary_match(content) or content:match(binary_match)
if match ~= nil then
return true, match
end
end
return true
end,
catch { function (errs) errors = errs end }
}
-- remove some files
os.tryrm(objectfile)
os.tryrm(binaryfile)
-- trace
if opt.verbose or option.get("verbose") or option.get("diagnosis") then
local kind = "c"
if sourcekind == "cxx" then
kind = "c++"
elseif sourcekind == "mxx" then
kind = "objc++"
elseif sourcekind == "cc" then
kind = "c"
elseif sourcekind == "mm" then
kind = "objc"
end
if #includes > 0 then
cprint("${dim}> checking for %s includes(%s)", kind, table.concat(includes, ", "))
end
if #types > 0 then
cprint("${dim}> checking for %s types(%s)", kind, table.concat(types, ", "))
end
if #funcs > 0 then
cprint("${dim}> checking for %s funcs(%s)", kind, table.concat(funcs, ", "))
end
if #links > 0 then
cprint("${dim}> checking for %s links(%s)", kind, table.concat(links, ", "))
end
for idx_or_name, snippet in pairs(snippets) do
local name = idx_or_name
if type(name) == "number" then
name = snippet:sub(1, 16)
end
cprint("${dim}> checking for %s snippet(%s)", kind, name)
end
end
if errors and option.get("diagnosis") and #tostring(errors) > 0 then
cprint("${color.warning}checkinfo:${clear dim} %s", errors)
end
return ok, ok and output or errors
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/features.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file features.lua
--
-- imports
import("lib.detect.find_tool")
import("core.base.scheduler")
-- get all features of the current tool
--
-- @param name the tool name
-- @param opt the argument options, e.g. {program = "", flags = {}}
--
-- @return the features dictionary
--
-- @code
-- local features = features("clang")
-- local features = features("clang", {flags = "-O0", program = "xcrun -sdk macosx clang"})
-- local features = features("clang", {flags = {"-g", "-O0"}, envs = {PATH = ""}})
-- @endcode
--
function main(name, opt)
-- init options
opt = opt or {}
-- find tool program and version first
opt.version = true
local tool = find_tool(name, opt)
if not tool then
return {}
end
-- init tool
opt.toolname = tool.name
opt.program = tool.program
opt.programver = tool.version
-- init cache and key
local key = tool.program .. "_" .. (tool.version or "") .. "_" .. table.concat(table.wrap(opt.flags), ",")
_g._RESULTS = _g._RESULTS or {}
local results = _g._RESULTS
-- @see https://github.com/xmake-io/xmake/issues/4645
-- @note avoid detect the same program in the same time leading to deadlock if running in the coroutine (e.g. ccache)
scheduler.co_lock(key)
-- get result from the cache first
local result = results[key]
if result ~= nil then
scheduler.co_unlock(key)
return result
end
-- detect.tools.xxx.features(opt)?
local features = import("detect.tools." .. tool.name .. ".features", {try = true})
if features then
result = features(opt)
end
result = result or {}
results[key] = result
scheduler.co_unlock(key)
return result
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/check_msnippets.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file check_msnippets.lua
--
-- imports
import("lib.detect.check_cxsnippets")
-- check the given c snippets?
--
-- @param snippets the snippets
-- @param opt the argument options
-- e.g.
-- { verbose = false, target = [target|option]
-- , types = {"wchar_t", "char*"}, includes = "stdio.h", funcs = {"sigsetjmp", "sigsetjmp((void*)0, 0)"}
-- , configs = {defines = "xx", mxflags = ""}}
--
-- funcs:
-- sigsetjmp
-- sigsetjmp((void*)0, 0)
-- sigsetjmp{sigsetjmp((void*)0, 0);}
-- sigsetjmp{int a = 0; sigsetjmp((void*)a, a);}
--
-- @return true or false
--
-- @code
-- local ok = check_msnippets("void test() {}")
-- local ok = check_msnippets({"void test(){}", "#define TEST 1"}, {types = "wchar_t", includes = "stdio.h"})
-- local ok = check_msnippets({snippet_name = "void test(){}", "#define TEST 1"}, {types = "wchar_t", includes = "stdio.h"})
-- @endcode
--
function main(snippets, opt)
return check_cxsnippets(snippets, table.join(table.wrap(opt), {sourcekind = "mm"}))
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/find_cudadevices.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author OpportunityLiu
-- @file find_cudadevices.lua
--
-- imports
import("core.base.option")
import("core.platform.platform")
import("core.project.config")
import("core.cache.detectcache")
import("lib.detect.find_tool")
-- a magic string to filter output
local _PRINT_SUFFIX = "<find_cudadevices>"
-- filter stdout and stderr with _PRINT_SUFFIX
function _get_lines(str)
local result = {}
for _, l in ipairs(str:split("\n")) do
if l:startswith(_PRINT_SUFFIX) then
table.insert(result, l:sub(#_PRINT_SUFFIX + 1))
end
end
return result
end
-- parse a single value
--
-- format:
-- 1. a number: `2048`
-- 2. an array: `(65536, 2048, 2048)`
-- 3. bool value: `true` or `false`
-- 4. string: `"string"`
--
function _parse_value(value)
local num = tonumber(value)
if num then return num end
if value:lower() == "true" then return true end
if value:lower() == "false" then return false end
if value:startswith('"') and value:endswith('"') then
return value:sub(2, -2)
end
if value:startswith("(") and value:endswith(")") then
local values = value:sub(2, -2):split(",")
local result = {}
for _, v in ipairs(values) do
table.insert(result, _parse_value(v:trim()))
end
return result
end
raise("don't know how to parse value: %s", value)
end
-- parse single line
--
-- format:
-- key = value
--
function _parse_line(line, device)
local key = line:match("%s+(%g+) = .+")
local value = line:match("%s+%g+ = (.+)")
if key and value then
key = key:trim()
value = value:trim()
assert(not device[key], "duplicate key: " .. key)
device[key] = _parse_value(value)
end
end
-- parse filtered lines
function _parse_result(lines, verbose)
if #lines == 0 then
-- not a failure, returns {} rather than nil
utils.warning("no cuda devices was found")
return {}
end
local devices = {}
local currentDevice = nil
for _, l in ipairs(lines) do
if verbose then
cprint("${dim}> %s", l)
end
local devId = tonumber(l:match("%s*DEVICE #(%d+)"))
if devId then
currentDevice = { ["$id"] = devId }
table.insert(devices, currentDevice)
elseif currentDevice then
_parse_line(l, currentDevice)
end
end
return devices
end
-- find devices
function _find_devices(verbose, opt)
-- find nvcc
local nvcc = assert(find_tool("nvcc"), "nvcc not found")
-- trace
if verbose then
cprint("${dim}checking for cuda devices")
end
-- get cuda devices
local sourcefile = path.join(os.programdir(), "scripts", "find_cudadevices.cpp")
local outfile = os.tmpfile({ramdisk = false}) -- no execution permision in docker's /shm
local compile_errors = nil
local results, errors = try
{
function ()
local args = { sourcefile, "-run", "-o", outfile , '-DPRINT_SUFFIX="' .. _PRINT_SUFFIX .. '"' }
if opt.arch == "x86" then
table.insert(args, "-m32")
elseif opt.arch == "x64" or opt.arch == "x86_64" then
table.insert(args, "-m64")
end
return os.iorunv(nvcc.program, args, {envs = opt.envs})
end,
catch
{
function (errs)
compile_errors = tostring(errs)
end
}
}
if compile_errors then
if not option.get("diagnosis") then
compile_errors = compile_errors:split('\n')[1]
end
utils.warning("failed to find cuda devices: " .. compile_errors)
return nil
end
-- clean up
os.tryrm(outfile)
os.tryrm(outfile .. ".*")
-- get results
local results_lines = _get_lines(results)
local errors_lines = _get_lines(errors)
if #errors_lines ~= 0 then
utils.warning("failed to find cuda devices: " .. table.concat(errors_lines, "\n"))
return nil
end
-- print raw result only with -D flags
local devices = _parse_result(results_lines, option.get("diagnosis"))
if verbose then
for _, v in ipairs(devices) do
cprint("${dim}> found device #%d: ${green bright}%s${reset dim} with compute ${bright}%d.%d${reset dim} capability", v["$id"], v.name, v.major, v.minor)
end
end
return devices
end
-- get devices array form cache or via _find_devices
function _get_devices(opt)
-- init cachekey
local cachekey = "find_cudadevices"
if opt.cachekey then
cachekey = cachekey .. "_" .. opt.cachekey
end
-- check cache
local cachedata = detectcache:get(cachekey) or {}
if cachedata.succeed and not opt.force then
return cachedata.data
end
local verbose = opt.verbose or option.get("verbose") or option.get("diagnosis")
local devices = _find_devices(verbose, opt)
if devices then
cachedata = { succeed = true, data = devices }
else
cachedata = { succeed = false }
devices = {}
end
-- fill cache
detectcache:set(cachekey, cachedata)
detectcache:save()
return devices
end
function _skip_compute_mode_prohibited(devices)
local results = {}
local cuda_compute_mode_prohibited = 2
for _, dev in ipairs(devices) do
if dev.computeMode ~= cuda_compute_mode_prohibited then
table.insert(results, dev)
end
end
return results
end
function _min_sm_arch(devices, min_sm_arch)
local results = {}
for _, dev in ipairs(devices) do
if dev.major * 10 + dev.minor >= min_sm_arch then
table.insert(results, dev)
end
end
return results
end
function _order_by_flops(devices)
local ngpu_arch_cores_per_sm =
{
[30] = 192
, [32] = 192
, [35] = 192
, [37] = 192
, [50] = 128
, [52] = 128
, [53] = 128
, [60] = 64
, [61] = 128
, [62] = 128
, [70] = 64
, [72] = 64
, [75] = 64
, [80] = 64
, [86] = 128
, [87] = 128
}
for _, dev in ipairs(devices) do
local sm_per_multiproc = 0
if dev.major == 9999 and dev.minor == 9999 then
sm_per_multiproc = 1
else
sm_per_multiproc = ngpu_arch_cores_per_sm[dev.major * 10 + dev.minor] or 64;
end
dev["$flops"] = dev.multiProcessorCount * sm_per_multiproc * dev.clockRate
end
table.sort(devices, function (a,b) return a["$flops"] > b["$flops"] end)
return devices
end
-- find cuda devices of the host
--
-- @param opt the options
-- e.g. { verbose = false, force = false, cachekey = "xxxx", min_sm_arch = 35, skip_compute_mode_prohibited = false, order_by_flops = true }
--
-- @return { { ["$id"] = 0, name = "GeForce GTX 960M", major = 5, minor = 0, ... }, ... }
-- for all keys, see https://docs.nvidia.com/cuda/cuda-runtime-api/structcudaDeviceProp.html#structcudaDeviceProp
-- keys might be differ as your cuda version varies
--
function main(opt)
-- init options
opt = opt or {}
-- get devices
local devices = _get_devices(opt)
-- apply filters
if opt.min_sm_arch then
devices = _min_sm_arch(devices, opt.min_sm_arch)
end
if opt.skip_compute_mode_prohibited then
devices = _skip_compute_mode_prohibited(devices)
end
if opt.order_by_flops then
devices = _order_by_flops(devices)
end
return devices
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/pkgconfig.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file pkgconfig.lua
--
-- imports
import("core.base.global")
import("core.project.target")
import("core.project.config")
import("lib.detect.find_file")
import("lib.detect.find_library")
import("lib.detect.find_tool")
-- get pkgconfig
function _get_pkgconfig()
local pkgconfig = find_tool("pkg-config") or find_tool("pkgconf")
if pkgconfig then
return pkgconfig.program
end
end
-- get version
--
-- @param name the package name
-- @param opt the argument options, {configdirs = {"/xxxx/pkgconfig/"}}
--
function version(name, opt)
-- attempt to add search paths from pkg-config
local pkgconfig = _get_pkgconfig()
if not pkgconfig then
return
end
-- init options
opt = opt or {}
-- init PKG_CONFIG_PATH
local configdirs_old = os.getenv("PKG_CONFIG_PATH")
local configdirs = table.wrap(opt.configdirs)
if #configdirs > 0 then
os.setenv("PKG_CONFIG_PATH", table.unpack(configdirs))
end
-- get version
local version = try { function() return os.iorunv(pkgconfig, {"--modversion", name}) end }
if version then
version = version:trim()
end
-- restore PKG_CONFIG_PATH
if configdirs_old then
os.setenv("PKG_CONFIG_PATH", configdirs_old)
end
-- ok?
return version
end
-- get variables
--
-- @param name the package name
-- @param variables the variables
-- @param opt the argument options, {configdirs = {"/xxxx/pkgconfig/"}}
--
function variables(name, variables, opt)
opt = opt or {}
local pkgconfig = _get_pkgconfig()
if not pkgconfig then
return
end
local result = nil
local envs = {PKG_CONFIG_PATH = opt.configdirs}
if variables then
for _, variable in ipairs(table.wrap(variables)) do
local value = try { function ()
return os.iorunv(pkgconfig, {"--variable=" .. variable, name}, {envs = envs})
end }
if value ~= nil then
result = result or {}
result[variable] = value:trim()
end
end
end
return result
end
-- get pcfile path
--
-- @param name the package name
-- @param opt the argument options, {configdirs = {"/xxxx/pkgconfig/"}}
--
function pcfile(name, opt)
opt = opt or {}
local pkgconfig = _get_pkgconfig()
if not pkgconfig then
return
end
local envs = {PKG_CONFIG_PATH = opt.configdirs}
local result = try { function ()
return os.iorunv(pkgconfig, {"--path", name}, {envs = envs})
end }
if result then
result = result:trim()
end
return result
end
-- get library info
--
-- @param name the package name
-- @param opt the argument options, {version = true, variables = "includedir", configdirs = {"/xxxx/pkgconfig/"}}
--
-- @return {links = {"ssl", "crypto", "z"}, linkdirs = {""}, includedirs = {""}, version = ""}
--
-- @code
--
-- local libinfo = pkgconfig.libinfo("openssl")
--
-- @endcode
--
function libinfo(name, opt)
opt = opt or {}
local pkgconfig = _get_pkgconfig()
if not pkgconfig then
return
end
-- get cflags
local found
local result = {}
local envs = {PKG_CONFIG_PATH = opt.configdirs}
local cflags = try {function ()
return os.iorunv(pkgconfig, {"--cflags", name}, {envs = envs})
end, catch {function (errs)
found = false
end}}
if cflags then
for _, flag in ipairs(os.argv(cflags)) do
if flag:startswith("-I") and #flag > 2 then
local includedir = flag:sub(3)
if includedir and os.isdir(includedir) then
result.includedirs = result.includedirs or {}
table.insert(result.includedirs, includedir)
end
elseif flag:startswith("-D") and #flag > 2 then
local define = flag:sub(3)
result.defines = result.defines or {}
table.insert(result.defines, define)
elseif flag:startswith("-") and #flag > 1 then
result.cxflags = result.cxflags or {}
table.insert(result.cxflags, flag)
end
end
end
-- libinfo may be empty body, but it's also valid
-- @see https://github.com/xmake-io/xmake/issues/3777#issuecomment-1568453316
if found == false then
return
end
-- get libs and ldflags
local ldflags = try { function () return os.iorunv(pkgconfig, {"--libs", name}, {envs = envs}) end }
if ldflags then
for _, flag in ipairs(os.argv(ldflags)) do
if flag:startswith("-L") and #flag > 2 then
local linkdir = flag:sub(3)
if linkdir and os.isdir(linkdir) then
result.linkdirs = result.linkdirs or {}
table.insert(result.linkdirs, linkdir)
end
elseif flag:startswith("-l") and #flag > 2 then
-- https://github.com/xmake-io/xmake/issues/4292
local link = flag:startswith("-l:") and flag:sub(4) or flag:sub(3)
result.links = result.links or {}
table.insert(result.links, link)
elseif flag:startswith("-") and #flag > 1 then
result.ldflags = result.ldflags or {}
result.shflags = result.shflags or {}
table.insert(result.ldflags, flag)
table.insert(result.shflags, flag)
end
end
end
-- get version
local version = try { function() return os.iorunv(pkgconfig, {"--modversion", name}, {envs = envs}) end }
if version then
result.version = version:trim()
end
return result
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_package.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("core.cache.detectcache")
import("package.manager.find_package")
-- concat packages
function _concat_packages(a, b)
local result = table.copy(a)
for k, v in pairs(b) do
local o = result[k]
if o ~= nil then
v = table.join(o, v)
end
result[k] = v
end
for k, v in pairs(result) do
if k == "links" or k == "syslinks" or k == "frameworks" or k == "ldflags" or k == "shflags" then
if type(v) == "table" and #v > 1 then
-- we need to ensure link orders when removing repeat values
v = table.reverse_unique(v)
end
else
v = table.unique(v)
end
result[k] = v
end
return result
end
-- find package using the package manager
--
-- @param name the package name
-- e.g. zlib 1.12.x (try all), xmake::zlib 1.12.x, brew::zlib, brew::pcre/libpcre16, vcpkg::zlib, conan::OpenSSL/1.0.2n@conan/stable
-- @param opt the options
-- e.g. { verbose = false, force = false, plat = "iphoneos", arch = "arm64", mode = "debug", require_version = "1.0.x", version = true,
-- external = true, -- we use sysincludedirs instead of includedirs as results
-- linkdirs = {"/usr/lib"}, includedirs = "/usr/include", links = {"ssl"}, includes = {"ssl.h"}
-- packagedirs = {"/tmp/packages"}, system = true, cachekey = "xxxx"
-- pkgconfigs = {..}}
--
-- @return {links = {"ssl", "crypto", "z"}, linkdirs = {"/usr/local/lib"}, includedirs = {"/usr/local/include"}}
--
-- @code
--
-- local package = find_package("openssl")
-- local package = find_package("openssl", {require_version = "1.0.*", version = true})
-- local package = find_package("openssl", {plat = "iphoneos"})
-- local package = find_package("openssl", {linkdirs = {"/usr/lib", "/usr/local/lib"}, includedirs = "/usr/local/include", version = "1.0.1"})
-- local package = find_package("openssl", {linkdirs = {"/usr/lib", "/usr/local/lib", links = {"ssl", "crypto"}, includes = {"ssl.h"}})
--
-- @endcode
--
function main(name, opt)
-- get the copied options
opt = table.copy(opt)
opt.plat = opt.plat or config.get("plat") or os.host()
opt.arch = opt.arch or config.get("arch") or os.arch()
opt.mode = opt.mode or config.mode() or "release"
-- init cache key
local cachekey = "find_package_" .. opt.plat .. "_" .. opt.arch
if opt.cachekey then
cachekey = cachekey .. "_" .. opt.cachekey
end
-- init package key
local packagekey = name
if opt.buildhash then
packagekey = packagekey .. "_" .. opt.buildhash
end
if opt.mode then
packagekey = packagekey .. "_" .. opt.mode
end
if opt.require_version then
packagekey = packagekey .. "_" .. opt.require_version
end
if opt.external then
packagekey = packagekey .. "_external"
end
-- attempt to get result from cache first
local result = detectcache:get2(cachekey, packagekey)
if result == nil or opt.force then
-- find package
local found_manager_name, package_name
result, found_manager_name, package_name = find_package(name, opt)
-- use isystem?
if result and result.includedirs and opt.external then
result.sysincludedirs = result.includedirs
result.includedirs = nil
local components_base = result.components and result.components.__base
if components_base then
components_base.sysincludedirs = components_base.includedirs
components_base.includedirs = nil
end
end
-- cache result
detectcache:set2(cachekey, packagekey, result and result or false)
detectcache:save()
-- trace
if opt.verbose or option.get("verbose") then
if result then
-- only display manager of found package if the package we searched for
-- did not specify a package manager
local display_manager = name:find("::", 1, true) and "" or (found_manager_name or "") .. "::"
local display_name = display_manager .. package_name
cprint("checking for %s ... ${color.success}%s %s", name, display_name, result.version and result.version or "")
else
cprint("checking for %s ... ${color.nothing}${text.nothing}", name)
end
end
end
-- does not show version (default)? strip it
if not opt.version and result then
result.version = nil
end
-- register concat
if result and type(result) == "table" then
debug.setmetatable(result, {__concat = _concat_packages})
end
return result and result or nil
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/check_cxxsnippets.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file check_cxxsnippets.lua
--
-- imports
import("lib.detect.check_cxsnippets")
-- check the given c++ snippets?
--
-- @param snippets the snippets
-- @param opt the argument options
-- e.g.
-- { verbose = false, target = [target|option]
-- , types = {"wchar_t", "char*"}, includes = "stdio.h", funcs = {"sigsetjmp", "sigsetjmp((void*)0, 0)"}
-- , configs = {defines = "xx", cxflags = ""}}
--
-- funcs:
-- sigsetjmp
-- sigsetjmp((void*)0, 0)
-- sigsetjmp{sigsetjmp((void*)0, 0);}
-- sigsetjmp{int a = 0; sigsetjmp((void*)a, a);}
--
-- @return true or false
--
-- @code
-- local ok = check_cxxsnippets("void test() {}")
-- local ok = check_cxxsnippets({"void test(){}", "#define TEST 1"}, {types = "wchar_t", includes = "stdio.h"})
-- local ok = check_cxxsnippets({snippet_name = "void test(){}", "#define TEST 1"}, {types = "wchar_t", includes = "stdio.h"})
-- @endcode
--
function main(snippets, opt)
return check_cxsnippets(snippets, table.join(table.wrap(opt), {sourcekind = "cxx"}))
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/check_csnippets.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file check_csnippets.lua
--
-- imports
import("lib.detect.check_cxsnippets")
-- check the given c snippets?
--
-- @param snippets the snippets
-- @param opt the argument options
-- e.g.
-- { verbose = false, target = [target|option]
-- , types = {"wchar_t", "char*"}, includes = "stdio.h", funcs = {"sigsetjmp", "sigsetjmp((void*)0, 0)"}
-- , configs = {defines = "xx", cxflags = ""}}
--
-- funcs:
-- sigsetjmp
-- sigsetjmp((void*)0, 0)
-- sigsetjmp{sigsetjmp((void*)0, 0);}
-- sigsetjmp{int a = 0; sigsetjmp((void*)a, a);}
--
-- @return true or false
--
-- @code
-- local ok = check_csnippets("void test() {}")
-- local ok = check_csnippets({"void test(){}", "#define TEST 1"}, {types = "wchar_t", includes = "stdio.h"})
-- local ok = check_csnippets({snippet_name = "void test(){}", "#define TEST 1"}, {types = "wchar_t", includes = "stdio.h"})
-- @endcode
--
function main(snippets, opt)
return check_cxsnippets(snippets, table.join(table.wrap(opt), {sourcekind = "cc"}))
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/check_mxxsnippets.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file check_mxxsnippets.lua
--
-- imports
import("lib.detect.check_cxsnippets")
-- check the given c++ snippets?
--
-- @param snippets the snippets
-- @param opt the argument options
-- e.g.
-- { verbose = false, target = [target|option]
-- , types = {"wchar_t", "char*"}, includes = "stdio.h", funcs = {"sigsetjmp", "sigsetjmp((void*)0, 0)"}
-- , configs = {defines = "xx", mxflags = ""}}
--
-- funcs:
-- sigsetjmp
-- sigsetjmp((void*)0, 0)
-- sigsetjmp{sigsetjmp((void*)0, 0);}
-- sigsetjmp{int a = 0; sigsetjmp((void*)a, a);}
--
-- @return true or false
--
-- @code
-- local ok = check_mxxsnippets("void test() {}")
-- local ok = check_mxxsnippets({"void test(){}", "#define TEST 1"}, {types = "wchar_t", includes = "stdio.h"})
-- local ok = check_mxxsnippets({snippet_name = "void test(){}", "#define TEST 1"}, {types = "wchar_t", includes = "stdio.h"})
-- @endcode
--
function main(snippets, opt)
return check_cxsnippets(snippets, table.join(table.wrap(opt), {sourcekind = "mxx"}))
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/find_toolname.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_toolname.lua
--
-- imports
import("core.base.hashset")
import("core.sandbox.module")
-- remove some suffix
--
-- we just remove some known extension, because we need to reverse others, e.g. ld.lld, ld64.lld
--
function _remove_suffix(name)
local exts = hashset.of("exe", "bat", "sh", "ps1", "ps")
name = name:gsub("%.(%w+)", function (ext)
ext = ext:lower()
if exts:has(ext) then
return ""
end
end)
return name
end
-- find the the whole name
function _find_with_whole_name(program)
-- attempt to find it directly first
if module.find("detect.tools.find_" .. program) then
return program
end
-- find the the whole name with spaces, e.g. "zig cc" -> zig_cc
local partnames = {}
local names = path.filename(program):lower():split("%s")
for _, name in ipairs(names) do
-- remove suffix: ".exe", e.g. "zig.exe cc"
name = _remove_suffix(name)
-- "zig c++" -> zig_cxx
name = name:gsub("%+", "x")
-- skip -arguments
if not name:startswith("-") then
table.insert(partnames, name)
end
end
local toolname = table.concat(partnames, "_")
if module.find("detect.tools.find_" .. toolname) then
return toolname
end
end
-- find tool name from the given program
function _find(program)
-- find whole name first
local toolname = _find_with_whole_name(program)
if toolname then
return toolname
end
-- get file name first
local name = path.filename(program):lower()
-- remove arguments: " -xxx" or " --xxx"
name = name:gsub("%s%-+%w+", " ")
-- try the last name by ' ': xxx xxx toolname
local names = name:split("%s")
if #names > 0 then
name = names[#names]
end
-- remove suffix: ".xxx"
name = _remove_suffix(name)
toolname = name:gsub("[%+%-%.]", function (ch) return (ch == "+" and "x" or "_") end)
if module.find("detect.tools.find_" .. toolname) then
return toolname
end
-- try last valid name: xxx-xxx-toolname-5
--
-- e.g.
-- arm-none-eabi-gcc-ar -> gcc_ar
-- arm-none-eabi-gcc -> gcc
local partnames = {}
for partname in name:gmatch("([%a%+]+)") do
table.insert(partnames, partname)
end
while #partnames > 0 do
name = table.concat(partnames, "_")
table.remove(partnames, 1)
toolname = name:gsub("%+", "x")
if module.find("detect.tools.find_" .. toolname) then
return toolname
end
end
end
-- find tool name
--
-- e.g.
-- "xcrun -sdk macosx clang": clang
-- "zig cc": zig_cc
-- "zig.exe c++": zig_c++
-- "/usr/bin/arm-linux-gcc": gcc
-- "link.exe -lib": link
-- "gcc-5": gcc
-- "arm-android-clang++": clangxx
-- "pkg-config": pkg_config
--
-- @param program the program path or name
--
-- @return the tool name
--
function main(program)
-- init cache
local toolnames = _g._TOOLNAMES or {}
-- get it from the cache first
local toolname = toolnames[program]
if toolname ~= nil then
return toolname and toolname or nil
end
-- find the tool name
toolname = _find(program)
-- save result to cache
toolnames[program] = toolname and toolname or false
_g._TOOLNAMES = toolnames
return toolname
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/has_cincludes.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file has_cincludes.lua
--
-- imports
import("lib.detect.check_cxsnippets")
-- has the given c includes?
--
-- @param includes the includes
-- @param opt the argument options
-- e.g.
-- { verbose = false, target = [target|option], configs = {defines = "..", .. }}
--
-- @return true or false
--
-- @code
-- local ok = has_cincludes("stdio.h")
-- local ok = has_cincludes({"stdio.h", "stdlib.h"}, {target = target})
-- @endcode
--
function main(includes, opt)
-- init options
opt = opt or {}
-- init includes
opt.sourcekind = "cc"
opt.includes = includes
-- has includes?
local name = opt.name or "has_cincludes"
return check_cxsnippets({[name] = ""}, opt)
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/has_cxxfuncs.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file has_cxxfuncs.lua
--
-- imports
import("lib.detect.check_cxxsnippets")
-- has the given c++ funcs?
--
-- @param funcs the funcs
-- @param opt the argument options
-- e.g.
-- { verbose = false, target = [target|option], includes = "", configs = {linkdirs = .., links = .., defines = .., ..}}
--
-- funcs:
-- sigsetjmp
-- sigsetjmp((void*)0, 0)
-- sigsetjmp{sigsetjmp((void*)0, 0);}
-- sigsetjmp{int a = 0; sigsetjmp((void*)a, a);}
--
-- @return true or false
--
-- @code
-- local ok = has_cxxfuncs("setjmp")
-- local ok = has_cxxfuncs({"sigsetjmp((void*)0, 0)", "setjmp"}, {includes = "setjmp.h"})
-- @endcode
--
function main(funcs, opt)
-- init options
opt = opt or {}
opt.funcs = funcs
-- has funcs?
local name = opt.name or "has_cxxfuncs"
return check_cxxsnippets({[name] = ""}, opt)
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/has_features.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file has_features.lua
--
-- imports
import("core.base.option")
import("lib.detect.features", {alias = "get_features"})
-- has the given features for the current tool?
--
-- @param name the tool name
-- @param features the features
-- @param opt the argument options, e.g. {verbose = false, flags = {}, program = ""}}
--
-- @return true or false
--
-- @code
-- local features = has_features("clang", "cxx_constexpr")
-- local features = has_features("clang", {"cxx_constexpr", "c_static_assert"}, {flags = {"-g", "-O0"}, program = "xcrun -sdk macosx clang"})
-- local features = has_features("clang", {"cxx_constexpr", "c_static_assert"}, {flags = "-g"})
-- @endcode
--
function main(name, features, opt)
opt = opt or {}
local allfeatures = get_features(name, opt) or {}
local passed = 0
features = table.wrap(features)
for _, feature in ipairs(features) do
if allfeatures[feature] then
passed = passed + 1
end
end
return passed == #features
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/check_bigendian.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author CarbeneHu
-- @file check_bigendian.lua
--
-- imports
import("lib.detect.check_cxxsnippets")
local check_bigendian_template = [[
#include <inttypes.h>
/* A 16 bit integer is required. */
typedef uint16_t byteorder_int16_t;
/* On a little endian machine, these 16bit ints will give "THIS IS LITTLE ENDIAN."
On a big endian machine the characters will be exchanged pairwise. */
const byteorder_int16_t info_little[] = {0x4854, 0x5349, 0x4920, 0x2053, 0x494c, 0x5454, 0x454c, 0x4520, 0x444e, 0x4149, 0x2e4e, 0x0000};
/* on a big endian machine, these 16bit ints will give "THIS IS BIG ENDIAN."
On a little endian machine the characters will be exchanged pairwise. */
const byteorder_int16_t info_big[] = {0x5448, 0x4953, 0x2049, 0x5320, 0x4249, 0x4720, 0x454e, 0x4449, 0x414e, 0x2e2e, 0x0000};
int main(int argc, char *argv[])
{
int require = 0;
require += info_little[argc];
require += info_big[argc];
(void)argv;
return require;
}]]
local function _byteorder_binary_match(content)
local match = content:match("THIS IS BIG ENDIAN")
return match and true or false
end
-- check the endianness of the compiler
--
-- @param opt the argument options
-- e.g.
-- { verbose = false, target = [target|option], includes = "stdio.h"
-- , configs = {defines = "xx", cxflags = ""}}
--
-- @return Boolean value whether the compiler is big-endian
--
-- @code
-- local is_bigendian = check_bigendian()
-- @endcode
--
function main(opt)
local snippets = check_bigendian_template
local ok, is_bigendian = check_cxxsnippets(snippets, table.join(table.wrap(opt), {binary_match = _byteorder_binary_match}))
if ok then
return is_bigendian
end
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/has_flags.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file has_flags.lua
--
-- imports
import("core.base.option")
import("core.base.scheduler")
import("core.base.profiler")
import("core.project.config")
import("core.cache.detectcache")
import("lib.detect.find_tool")
-- has the given flags for the current tool?
--
-- @param name the tool name
-- @param flags the flags
-- @param opt the argument options, e.g. {force = true, verbose = false, program = "", sysflags = {}, flagkind = "cxflag", toolkind = "[cc|cxx|ld|ar|sh|gc|rc|dc|mm|mxx]", flagskey = "custom key" }
--
-- @return true or false
--
-- @code
-- local ok = has_flags("clang", "-g")
-- local ok = has_flags("clang", {"-g", "-O0"}, {program = "xcrun -sdk macosx clang"})
-- local ok = has_flags("clang", "-g", {toolkind = "cxx"})
-- local ok = has_flags("clang", "-g", {on_check = function (ok, errors) return ok, errors end})
-- @endcode
--
function main(name, flags, opt)
-- wrap flags first
flags = table.clone(flags)
table.wrap_unlock(flags)
flags = table.wrap(flags)
-- init options
opt = opt or {}
opt.flagskey = opt.flagskey or table.concat(flags, " ")
opt.sysflags = table.wrap(opt.sysflags)
-- find tool program and version first
opt.version = true
local tool = find_tool(name, opt)
if not tool then
return false
end
-- init tool
opt.toolname = tool.name
opt.program = tool.program
opt.programver = tool.version
-- get tool platform
local plat = opt.plat or config.get("plat") or os.host()
-- get tool architecture
--
-- some tools select arch by path environment, not be flags, e.g. cl.exe of msvc)
-- so, it will affect the cache result
--
local arch = opt.arch or config.get("arch") or os.arch()
-- init cache key
local key = plat .. "_" .. arch .. "_" .. tool.program .. "_"
.. (tool.version or "") .. "_" .. (opt.toolkind or "")
.. "_" .. (opt.flagkind or "") .. "_" .. table.concat(opt.sysflags, " ") .. "_" .. opt.flagskey
-- @see https://github.com/xmake-io/xmake/issues/4645
-- @note avoid detect the same program in the same time leading to deadlock if running in the coroutine (e.g. ccache)
scheduler.co_lock(key)
-- attempt to get result from cache first
local cacheinfo = detectcache:get("lib.detect.has_flags")
if not cacheinfo then
-- since has_flags may be switched to other concurrent processes during cache saving,
-- we need to commit the initialized cache to avoid multiple cache objects overwriting it.
cacheinfo = {}
detectcache:set("lib.detect.has_flags", cacheinfo)
end
local result = cacheinfo[key]
if result ~= nil and not opt.force then
scheduler.co_unlock(key)
return result
end
-- generate all checked flags
local checkflags = table.join(flags, opt.sysflags)
-- split flag group, e.g. "-I /xxx" => {"-I", "/xxx"}
local results = {}
for _, flag in ipairs(checkflags) do
flag = flag:trim()
if #flag > 0 then
if flag:find(" ", 1, true) then
table.join2(results, os.argv(flag))
else
table.insert(results, flag)
end
end
end
checkflags = results
-- start profile
profiler.enter("has_flags", tool.name, checkflags[1])
-- detect.tools.xxx.has_flags(flags, opt)?
local hasflags = import("detect.tools." .. tool.name .. ".has_flags", {try = true})
local errors = nil
if hasflags then
result, errors = hasflags(checkflags, opt)
else
result = try { function () os.runv(tool.program, checkflags, {envs = opt.envs}); return true end, catch { function (errs) errors = errs end }}
end
if opt.on_check then
result, errors = opt.on_check(result, errors)
end
result = result or false
-- stop profile
profiler.leave("has_flags", tool.name, checkflags[1])
-- trace
if option.get("verbose") or option.get("diagnosis") or opt.verbose then
cprintf("${dim}checking for flags (")
io.write(opt.flagskey)
cprint("${dim}) ... %s", result and "${color.success}${text.success}" or "${color.nothing}${text.nothing}")
if option.get("diagnosis") then
cprint("${dim}> %s \"%s\"", path.filename(tool.program), table.concat(checkflags, "\" \""))
if errors and #tostring(errors) > 0 then
cprint("${color.warning}checkinfo:${clear dim} %s", tostring(errors):trim())
end
end
end
-- save result to cache
cacheinfo[key] = result
detectcache:set("lib.detect.has_flags", cacheinfo)
detectcache:save()
scheduler.co_unlock(key)
return result
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/has_ctypes.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file has_ctypes.lua
--
-- imports
import("lib.detect.check_cxsnippets")
-- has the given c types?
--
-- @param types the types
-- @param opt the argument options
-- e.g.
-- { verbose = false, target = [target|option], includes = .., configs = {defines = .., ..}}
--
-- @return true or false
--
-- @code
-- local ok = has_ctypes("wchar_t")
-- local ok = has_ctypes({"char*", "wchar_t"}, {includes = "stdio.h"})
-- @endcode
--
function main(types, opt)
-- init options
opt = opt or {}
-- init types
opt.sourcekind = "cc"
opt.types = types
-- has types?
local name = opt.name or "has_ctypes"
return check_cxsnippets({[name] = ""}, opt)
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/has_cfuncs.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file has_cfuncs.lua
--
-- imports
import("lib.detect.check_csnippets")
-- has the given c funcs?
--
-- @param funcs the funcs
-- @param opt the argument options
-- e.g.
-- { verbose = false, target = [target|option], includes = "", configs = {linkdirs = .., links = .., defines = .., ..}}
--
-- funcs:
-- sigsetjmp
-- sigsetjmp((void*)0, 0)
-- sigsetjmp{sigsetjmp((void*)0, 0);}
-- sigsetjmp{int a = 0; sigsetjmp((void*)a, a);}
--
-- @return true or false
--
-- @code
-- local ok = has_cfuncs("setjmp")
-- local ok = has_cfuncs({"sigsetjmp((void*)0, 0)", "setjmp"}, {includes = "setjmp.h"})
-- @endcode
--
function main(funcs, opt)
-- init options
opt = opt or {}
opt.funcs = funcs
-- has funcs?
local name = opt.name or "has_cfuncs"
return check_csnippets({[name] = ""}, opt)
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/has_cxxincludes.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file has_cxxincludes.lua
--
-- imports
import("lib.detect.check_cxsnippets")
-- has the given c++ includes?
--
-- @param includes the includes
-- @param opt the argument options
-- e.g.
-- { verbose = false, target = [target|option], configs = {defines = "..", .. }}
--
-- @return true or false
--
-- @code
-- local ok = has_cxxincludes("stdio.h")
-- local ok = has_cxxincludes({"stdio.h", "stdlib.h"}, {target = target})
-- @endcode
--
function main(includes, opt)
-- init options
opt = opt or {}
-- init includes
opt.sourcekind = "cxx"
opt.includes = includes
-- has includes?
local name = opt.name or "has_cxxincludes"
return check_cxsnippets({[name] = ""}, opt)
end
|
0 | repos/xmake/xmake/modules/lib | repos/xmake/xmake/modules/lib/detect/check_sizeof.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file check_sizeof.lua
--
-- imports
import("lib.detect.check_cxxsnippets")
local binary_match_pattern = 'INFO:size%[(%d+)%]'
local check_sizeof_template = [[
#define SIZE (sizeof(${TYPE}))
static char info_size[] = {'I', 'N', 'F', 'O', ':', 's','i','z','e','[',
('0' + ((SIZE / 10000)%10)),
('0' + ((SIZE / 1000)%10)),
('0' + ((SIZE / 100)%10)),
('0' + ((SIZE / 10)%10)),
('0' + (SIZE % 10)),
']',
'\0'};
int main(int argc, char *argv[]) {
int require = 0;
require += info_size[argc];
(void)argv;
return require;
}]]
function _binary_match(content)
local match = content:match(binary_match_pattern)
if match then
return match:ltrim("0")
end
end
-- check the size of type
--
-- @param typename the typename
-- @param opt the argument options
-- e.g.
-- { verbose = false, target = [target|option], includes = "stdio.h"
-- , configs = {defines = "xx", cxflags = ""}}
--
-- @return the type size
--
-- @code
-- local size = check_sizeof("long")
-- local size = check_sizeof("std::string", {includes = "string"})
-- @endcode
--
function main(typename, opt)
local snippets = check_sizeof_template:gsub('${TYPE}', typename)
local ok, size = check_cxxsnippets(snippets, table.join(table.wrap(opt), {binary_match = _binary_match}))
if ok then
return size
end
end
|
0 | repos/xmake/xmake/modules | repos/xmake/xmake/modules/privilege/sudo.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file sudo.lua
--
-- imports
import("core.base.option")
import("detect.tools.find_sudo")
-- some inherited environment variables
function _envars(escape)
local names = {"PATH", "XMAKE_STATS", "COLORTERM"}
local envars = {"env"}
for _, name in ipairs(names) do
local value = os.getenv(name)
if escape and value then
value = "\"" .. (value:gsub("\"", "\\\"")) .. "\""
end
table.insert(envars, name .. "=" .. (value or ""))
end
return envars
end
-- sudo run command with administrator permission
--
-- e.g.
-- _sudo(os.run, "echo", "hello xmake!")
--
function _sudo(runner, cmd, ...)
-- find sudo
local sudo = find_sudo()
assert(sudo, "sudo not found!")
-- run it with administrator permission and preserve parent environment
runner(sudo .. " " .. table.concat(_envars(true), " ") .. " " .. cmd, ...)
end
-- sudo run command with administrator permission and arguments list
--
-- e.g.
-- _sudov(os.runv, {"echo", "hello xmake!"})
--
function _sudov(runner, program, argv, opt)
-- find sudo
local sudo = find_sudo()
assert(sudo, "sudo not found!")
-- run it with administrator permission and preserve parent environment
runner(sudo, table.join(_envars(), program, argv), opt)
end
-- sudo run lua script with administrator permission and arguments list
--
-- e.g.
-- _lua(os.runv, "xxx.lua", {"arg1", "arg2"})
--
function _lua(runner, luafile, luaargv)
-- init argv
local argv = {"lua", "--root"}
for _, name in ipairs({"file", "project", "diagnosis", "verbose", "quiet", "yes", "confirm"}) do
local value = option.get(name)
if type(value) == "string" then
table.insert(argv, "--" .. name .. "=" .. value)
elseif value then
table.insert(argv, "--" .. name)
end
end
-- run it with administrator permission
_sudov(runner, os.programfile(), table.join(argv, luafile, luaargv))
end
-- has sudo?
function has()
return find_sudo() ~= nil
end
-- sudo run command
function run(cmd, ...)
return _sudo(os.run, cmd, ...)
end
-- sudo run command with arguments list
function runv(program, argv, opt)
return _sudov(os.run, program, argv, opt)
end
-- sudo quietly run command and echo verbose info if [-v|--verbose] option is enabled
function vrun(cmd, ...)
return _sudo(os.vrun, cmd, ...)
end
-- sudo quietly run command with arguments list and echo verbose info if [-v|--verbose] option is enabled
function vrunv(program, argv, opt)
return _sudov(os.vrunv, program, argv, opt)
end
-- sudo run command and return output and error data
function iorun(cmd, ...)
return _sudo(os.iorun, cmd, ...)
end
-- sudo run command and return output and error data
function iorunv(program, argv, opt)
return _sudov(os.iorunv, program, argv, opt)
end
-- sudo execute command
function exec(cmd, ...)
return _sudo(os.exec, cmd, ...)
end
-- sudo execute command with arguments list
function execv(program, argv, opt)
return _sudov(os.execv, program, argv, opt)
end
-- sudo run lua script
function runl(luafile, luaargv, opt)
return _lua(os.runv, luafile, luaargv, opt)
end
-- sudo quietly run lua script and echo verbose info if [-v|--verbose] option is enabled
function vrunl(luafile, luaargv)
return _lua(os.vrunv, luafile, luaargv)
end
-- sudo run lua script and return output and error data
function iorunl(luafile, luaargv)
return _lua(os.iorunv, luafile, luaargv)
end
-- sudo execute lua script
function execl(luafile, luaargv)
return _lua(os.execv, luafile, luaargv)
end
|
0 | repos/xmake/xmake/modules | repos/xmake/xmake/modules/utils/progress.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author OpportunityLiu
-- @file progress.lua
--
-- imports
import("core.base.option")
import("core.base.object")
import("core.base.colors")
import("core.base.tty")
import("core.theme.theme")
-- define module
local progress = progress or object { _init = { "_RUNNING", "_INDEX", "_STREAM", "_OPT" } }
-- stop the progress indicator, clear written frames
function progress:stop()
if self._RUNNING ~= 0 then
self:clear()
self._RUNNING = 0
self._INDEX = 0
end
end
function progress:_clear()
if self._RUNNING == 1 then
tty.erase_line_to_end()
self._RUNNING = 2
return true
end
end
-- clear previous frame of the progress indicator
function progress:clear()
if self:_clear() then
self._STREAM:flush()
end
end
-- write next frame of the progress indicator
function progress:write()
local chars = self._OPT.chars[self._INDEX % #self._OPT.chars + 1]
tty.cursor_and_attrs_save()
self._STREAM:write(chars)
self._STREAM:flush()
tty.cursor_and_attrs_restore()
self._INDEX = self._INDEX + 1
self._RUNNING = 1
end
-- check if the progress indicator is running
function progress:running()
return self._RUNNING and true or false
end
-- showing progress line without scroll?
function showing_without_scroll()
return _g.showing_without_scroll
end
-- show the message with progress
function show(progress, format, ...)
progress = type(progress) == "table" and progress:percent() or math.floor(progress)
local progress_prefix = "${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} "
if option.get("verbose") then
cprint(progress_prefix .. "${dim}" .. format, progress, ...)
else
local is_scroll = _g.is_scroll
if is_scroll == nil then
is_scroll = theme.get("text.build.progress_style") == "scroll"
_g.is_scroll = is_scroll
end
if is_scroll then
cprint(progress_prefix .. format, progress, ...)
else
tty.erase_line_to_start().cr()
local msg = vformat(progress_prefix .. format, progress, ...)
local msg_plain = colors.translate(msg, {plain = true})
local maxwidth = os.getwinsize().width
if #msg_plain <= maxwidth then
cprintf(msg)
else
-- windows width is too small? strip the partial message in middle
local partlen = math.floor(maxwidth / 2) - 3
local sep = msg_plain:sub(partlen + 1, #msg_plain - partlen - 1)
local split = msg:split(sep, {plain = true, strict = true})
cprintf(table.concat(split, "..."))
end
if math.floor(progress) == 100 then
print("")
_g.showing_without_scroll = false
else
_g.showing_without_scroll = true
end
io.flush()
end
end
end
-- get the message text with progress
function text(progress, format, ...)
progress = type(progress) == "table" and progress:percent() or math.floor(progress)
local progress_prefix = "${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} "
if option.get("verbose") then
return string.format(progress_prefix .. "${dim}" .. format, progress, ...)
else
return string.format(progress_prefix .. format, progress, ...)
end
end
-- build a progress indicator
-- @params stream - stream to write to, will use io.stdout if not provided
-- @params opt - options
-- - chars - an array of chars for progress indicator
function new(stream, opt)
-- set default values
stream = stream or io.stdout
opt = opt or {}
if opt.chars == nil or #opt.chars == 0 then
opt.chars = theme.get("text.spinner.chars")
end
return progress {_OPT = opt, _STREAM = stream, _RUNNING = 0, _INDEX = 0}
end
|
0 | repos/xmake/xmake/modules/utils | repos/xmake/xmake/modules/utils/archive/extract.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file extract.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_file")
import("detect.tools.find_xz")
import("detect.tools.find_7z")
import("detect.tools.find_tar")
import("detect.tools.find_gzip")
import("detect.tools.find_unzip")
import("detect.tools.find_bzip2")
import("extract_xmz")
import("extension", {alias = "get_archive_extension"})
-- extract archivefile using xmake decompress module
function _extract_using_xmz(archivefile, outputdir, extension, opt)
extract_xmz(archivefile, outputdir, opt)
return true
end
-- extract archivefile using tar
function _extract_using_tar(archivefile, outputdir, extension, opt)
-- the tar on windows can only extract "*.tar", "*.tar.gz"
-- the tar on msys2 can extract more, like "*.tar.bz2", ..
if os.host() == "windows" and (extension ~= ".tar" and extension ~= ".tar.gz") then
return false
end
-- find tar
local program = find_tar()
if not program then
return false
end
-- init argv
local argv = {}
if is_host("windows") then
-- force "x:\\xx" as local file
local force_local = _g.force_local
if force_local == nil then
force_local = try {function ()
local result = os.iorunv(program, {"--help"})
if result and result:find("--force-local", 1, true) then
return true
end
end}
_g.force_local = force_local or false
end
if force_local then
table.insert(argv, "--force-local")
end
end
table.insert(argv, "-xf")
table.insert(argv, path.absolute(archivefile))
-- ensure output directory
if not os.isdir(outputdir) then
os.mkdir(outputdir)
end
-- set outputdir
if not is_host("windows") then
table.insert(argv, "-C")
table.insert(argv, outputdir)
end
-- excludes files
if opt.excludes then
table.insert(argv, "--exclude")
for _, exclude in ipairs(opt.excludes) do
table.insert(argv, exclude)
end
end
-- extract it
if is_host("windows") then
os.vrunv(program, argv, {curdir = outputdir})
else
os.vrunv(program, argv)
end
return true
end
-- extract archivefile using 7z
function _extract_using_7z(archivefile, outputdir, extension, opt)
-- find 7z
local program = find_7z()
if not program then
return false
end
-- p7zip cannot extract other archive format on msys/cygwin, but it can extract .tgz
-- https://github.com/xmake-io/xmake/issues/1575#issuecomment-898205462
if is_subhost("msys", "cygwin") and program:startswith("sh ") and
extension ~= ".7z" and extension ~= ".tgz" then
return false
end
-- extract to *.tar file first
local outputdir_old = nil
if extension:startswith(".tar.") or extension == ".tgz" then
outputdir_old = outputdir
outputdir = os.tmpfile({ramdisk = false}) .. ".tar"
end
-- on msys2/cygwin? we need to translate input path to cygwin-like path
if is_subhost("msys", "cygwin") and program:gsub("\\", "/"):find("/usr/bin") then
archivefile = path.cygwin_path(archivefile)
end
-- init argv
local argv = {"x", "-y", archivefile}
-- disable to store symlinks on windows
if is_host("windows") then
table.insert(argv, "-snl-")
end
-- ensure output directory
if not os.isdir(outputdir) then
os.mkdir(outputdir)
end
-- set outputdir
table.insert(argv, "-o" .. outputdir)
-- excludes files
local excludesfile = nil
if opt.excludes and not outputdir_old then
excludesfile = os.tmpfile()
io.writefile(excludesfile, table.concat(table.wrap(opt.excludes), '\n'))
table.insert(argv, "-xr@" .. excludesfile)
end
-- extract it
os.vrunv(program, argv)
-- remove the excludes file
if excludesfile then
os.tryrm(excludesfile)
end
-- remove unused pax_global_header file after extracting .tar file
if extension == ".tar" then
os.tryrm(path.join(outputdir, "pax_global_header"))
os.tryrm(path.join(outputdir, "PaxHeaders*"))
os.tryrm(path.join(outputdir, "@PaxHeader"))
-- https://github.com/xmake-io/xmake-repo/pull/2673
os.tryrm(path.join(outputdir, "*.paxheader"))
end
-- continue to extract *.tar file
if outputdir_old then
local tarfile = find_file("**.tar", outputdir)
if tarfile and os.isfile(tarfile) then
return _extract(tarfile, outputdir_old, ".tar", {_extract_using_7z, _extract_using_tar}, opt)
end
end
return true
end
-- extract archivefile using gzip
function _extract_using_gzip(archivefile, outputdir, extension, opt)
-- find gzip
local program = find_gzip()
if not program then
return false
end
-- extract to *.tar file first
local outputdir_old = nil
if extension:startswith(".tar.") then
outputdir_old = outputdir
outputdir = os.tmpfile({ramdisk = false}) .. ".tar"
end
-- init temporary archivefile
local tmpfile = path.join(outputdir, path.filename(archivefile))
-- init argv
local argv = {"-d", "-f"}
if not option.get("verbose") then
table.insert(argv, "-q")
end
table.insert(argv, tmpfile)
-- ensure output directory
if not os.isdir(outputdir) then
os.mkdir(outputdir)
end
-- copy archivefile to outputdir first
if path.absolute(archivefile) ~= path.absolute(tmpfile) then
os.cp(archivefile, tmpfile)
end
-- extract it
os.vrunv(program, argv, {curdir = outputdir})
-- continue to extract *.tar file
if outputdir_old then
local tarfile = find_file("**.tar", outputdir)
if tarfile and os.isfile(tarfile) then
return _extract(tarfile, outputdir_old, ".tar", {_extract_using_7z, _extract_using_tar}, opt)
end
end
return true
end
-- extract archivefile using xz
function _extract_using_xz(archivefile, outputdir, extension, opt)
-- find xz
local program = find_xz()
if not program then
return false
end
-- extract to *.tar file first
local outputdir_old = nil
if extension:startswith(".tar.") then
outputdir_old = outputdir
outputdir = os.tmpfile({ramdisk = false}) .. ".tar"
end
-- init temporary archivefile
local tmpfile = path.join(outputdir, path.filename(archivefile))
-- init argv
local argv = {"-d", "-f"}
if not option.get("verbose") then
table.insert(argv, "-q")
end
table.insert(argv, tmpfile)
-- ensure output directory
if not os.isdir(outputdir) then
os.mkdir(outputdir)
end
-- copy archivefile to outputdir first
if path.absolute(archivefile) ~= path.absolute(tmpfile) then
os.cp(archivefile, tmpfile)
end
-- extract it
os.vrunv(program, argv, {curdir = outputdir})
-- continue to extract *.tar file
if outputdir_old then
local tarfile = find_file("**.tar", outputdir)
if tarfile and os.isfile(tarfile) then
return _extract(tarfile, outputdir_old, ".tar", {_extract_using_7z, _extract_using_tar}, opt)
end
end
return true
end
-- extract archivefile using unzip
function _extract_using_unzip(archivefile, outputdir, extension, opt)
-- find unzip
local program = find_unzip()
if not program then
return false
end
-- extract to *.tar file first
local outputdir_old = nil
if extension:startswith(".tar.") then
outputdir_old = outputdir
outputdir = os.tmpfile({ramdisk = false}) .. ".tar"
end
-- init argv
local argv = {"-o"} -- overwrite existing files without prompting
if not option.get("verbose") then
table.insert(argv, "-q")
end
table.insert(argv, archivefile)
-- ensure output directory
if not os.isdir(outputdir) then
os.mkdir(outputdir)
end
-- extract to outputdir
table.insert(argv, "-d")
table.insert(argv, outputdir)
-- excludes files
if opt.excludes and not outputdir_old then
table.insert(argv, "-x")
for _, exclude in ipairs(opt.excludes) do
table.insert(argv, exclude)
end
end
-- extract it
os.vrunv(program, argv)
-- continue to extract *.tar file
if outputdir_old then
local tarfile = find_file("**.tar", outputdir)
if tarfile and os.isfile(tarfile) then
return _extract(tarfile, outputdir_old, ".tar", {_extract_using_tar, _extract_using_7z}, opt)
end
end
return true
end
-- extract archivefile using bzip2
function _extract_using_bzip2(archivefile, outputdir, extension, opt)
-- find bzip2
local program = find_bzip2()
if not program then
return false
end
-- extract to *.tar file first
local outputdir_old = nil
if extension:startswith(".tar.") then
outputdir_old = outputdir
outputdir = os.tmpfile({ramdisk = false}) .. ".tar"
end
-- on msys2/cygwin? we need to translate input path to cygwin-like path
if is_subhost("msys", "cygwin") and program:gsub("\\", "/"):find("/usr/bin") then
archivefile = path.cygwin_path(archivefile)
end
-- init temporary archivefile
local tmpfile = path.join(outputdir, path.filename(archivefile))
-- init argv
local argv = {"-d", "-f"}
if not option.get("verbose") then
table.insert(argv, "-q")
end
table.insert(argv, tmpfile)
-- ensure output directory
if not os.isdir(outputdir) then
os.mkdir(outputdir)
end
-- copy archivefile to outputdir first
if path.absolute(archivefile) ~= path.absolute(tmpfile) then
os.cp(archivefile, tmpfile)
end
-- extract it
os.vrunv(program, argv, {curdir = outputdir})
-- continue to extract *.tar file
if outputdir_old then
local tarfile = find_file("**.tar", outputdir)
if tarfile and os.isfile(tarfile) then
return _extract(tarfile, outputdir_old, ".tar", {_extract_using_7z, _extract_using_tar}, opt)
end
end
return true
end
-- extract archive file using extractors
function _extract(archivefile, outputdir, extension, extractors, opt)
local errors
for _, extract in ipairs(extractors) do
local ok = try {
function ()
return extract(archivefile, outputdir, extension, opt)
end,
catch {
function (errs)
if errs then
errors = tostring(errs)
end
end
}
}
if ok then
return true
end
end
raise("cannot extract %s, %s!", path.filename(archivefile), errors or "extractors not found!")
end
-- extract file
--
-- @param archivefile the archive file. e.g. *.tar.gz, *.zip, *.7z, *.tar.bz2, ..
-- @param outputdir the output directory
-- @param options the options, e.g.. {excludes = {"*/dir/*", "dir/*"}}
--
function main(archivefile, outputdir, opt)
opt = opt or {}
outputdir = outputdir or os.curdir()
-- init extractors
local extractors
if is_subhost("windows") then
-- we use 7z first, becase xmake package has builtin 7z program on windows
-- tar/windows can not extract .bz2 ...
extractors =
{
[".zip"] = {_extract_using_7z, _extract_using_unzip, _extract_using_tar}
, [".7z"] = {_extract_using_7z}
, [".gz"] = {_extract_using_7z, _extract_using_gzip, _extract_using_tar}
, [".xz"] = {_extract_using_7z, _extract_using_xz, _extract_using_tar}
, [".tgz"] = {_extract_using_7z, _extract_using_tar}
, [".bz2"] = {_extract_using_7z, _extract_using_bzip2}
, [".tar"] = {_extract_using_7z, _extract_using_tar}
-- @see https://github.com/xmake-io/xmake/issues/5538
, [".tar.gz"] = {_extract_using_tar, _extract_using_7z, _extract_using_gzip}
, [".tar.xz"] = {_extract_using_7z, _extract_using_xz}
, [".tar.bz2"] = {_extract_using_7z, _extract_using_bzip2}
, [".tar.lz"] = {_extract_using_7z}
, [".tar.Z"] = {_extract_using_7z}
, [".xmz"] = {_extract_using_xmz}
}
else
extractors =
{
-- tar supports .zip on macOS but does not on Linux
[".zip"] = is_host("macosx") and {_extract_using_unzip, _extract_using_tar, _extract_using_7z} or {_extract_using_unzip, _extract_using_7z}
, [".7z"] = {_extract_using_7z}
, [".gz"] = {_extract_using_gzip, _extract_using_tar, _extract_using_7z}
, [".xz"] = {_extract_using_xz, _extract_using_tar, _extract_using_7z}
, [".tgz"] = {_extract_using_tar, _extract_using_7z}
, [".bz2"] = {_extract_using_bzip2, _extract_using_tar, _extract_using_7z}
, [".tar"] = {_extract_using_tar, _extract_using_7z}
, [".tar.gz"] = {_extract_using_tar, _extract_using_7z, _extract_using_gzip}
, [".tar.xz"] = {_extract_using_tar, _extract_using_7z, _extract_using_xz}
, [".tar.bz2"] = {_extract_using_tar, _extract_using_7z, _extract_using_bzip2}
, [".tar.lz"] = {_extract_using_tar, _extract_using_7z}
, [".tar.Z"] = {_extract_using_tar, _extract_using_7z}
, [".xmz"] = {_extract_using_xmz}
}
end
-- get extension
local extension = opt.extension or get_archive_extension(archivefile)
-- extract it
return _extract(archivefile, outputdir, extension, extractors[extension], opt)
end
|
0 | repos/xmake/xmake/modules/utils | repos/xmake/xmake/modules/utils/archive/extract_xmz.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file extract_xmz.lua
--
-- imports
import("core.base.option")
import("core.base.bytes")
import("core.compress.lz4")
-- extract files
function _extract_files(archivefile, outputdir, opt)
local inputfile = io.open(archivefile, "rb")
local filesize = inputfile:size()
local readsize = 0
while readsize < filesize do
local data = inputfile:read(2)
local size = bytes(data):u16be(1)
local filepath
if size > 0 then
filepath = inputfile:read(size)
end
readsize = readsize + 2 + size
data = inputfile:read(4)
size = bytes(data):u32be(1)
local filedata
if size > 0 then
filedata = inputfile:read(size)
end
readsize = readsize + 4 + size
if filepath then
vprint("extracting %s, %d bytes", filepath, filedata and #filedata or 0)
if filedata then
io.writefile(path.join(outputdir, filepath), filedata, {encoding = "binary"})
else
os.touch(filepath)
end
end
end
inputfile:close()
end
-- decompress file
function _decompress_file(archivefile, outputfile, opt)
lz4.decompress_file(archivefile, outputfile)
end
-- extract file
--
-- @param archivefile the archive file. e.g. *.tar.gz, *.zip, *.7z, *.tar.bz2, ..
-- @param outputdir the output directory
-- @param options the options, e.g.. {excludes = {"*/dir/*", "dir/*"}}
--
function main(archivefile, outputdir, opt)
opt = opt or {}
local archivefile_tmp = os.tmpfile({ramdisk = false})
_decompress_file(archivefile, archivefile_tmp, opt)
_extract_files(archivefile_tmp, outputdir, opt)
os.tryrm(archivefile_tmp)
end
|
0 | repos/xmake/xmake/modules/utils | repos/xmake/xmake/modules/utils/archive/archive_xmz.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file archive_xmz.lua
--
-- imports
import("core.base.option")
import("core.base.bytes")
import("core.compress.lz4")
-- archive files
function _archive_files(archivefile, inputfiles, opt)
local curdir = opt.curdir
local outputfile = io.open(archivefile, "wb")
for _, inputfile in ipairs(inputfiles) do
local filepath = inputfile
if curdir then
filepath = path.relative(filepath, curdir)
end
outputfile:write(bytes(2):u16be_set(1, #filepath))
outputfile:write(filepath)
local data = io.readfile(inputfile, {encoding = "binary"})
vprint("archiving %s, %d bytes", inputfile, data and #data or 0)
outputfile:write(bytes(4):u32be_set(1, #data))
outputfile:write(data)
end
outputfile:close()
end
-- compress file
function _compress_file(archivefile, outputfile, opt)
lz4.compress_file(archivefile, outputfile)
end
-- archive file
--
-- @param archivefile the archive file. e.g. *.tar.gz, *.zip, *.7z, *.tar.bz2, ..
-- @param inputfiles the input file or directory or list
-- @param options the options, e.g.. {curdir = "/tmp", recurse = true, compress = "fastest|faster|default|better|best", excludes = {"*/dir/*", "dir/*"}}
--
function main(archivefile, inputfiles, opt)
opt = opt or {}
local files = {}
for _, inputfile in ipairs(inputfiles) do
if os.isdir(inputfile) then
table.join2(files, os.files(path.join(inputfile, opt.recurse and "**" or "*")))
elseif os.isfile(inputfile) then
table.insert(files, inputfile)
end
end
inputfiles = files
local archivefile_tmp = os.tmpfile({ramdisk = false})
_archive_files(archivefile_tmp, inputfiles, opt)
_compress_file(archivefile_tmp, archivefile, opt)
os.tryrm(archivefile_tmp)
end
|
0 | repos/xmake/xmake/modules/utils | repos/xmake/xmake/modules/utils/archive/archive.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file archive.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_file")
import("lib.detect.find_tool")
import("archive_xmz")
import("extension", {alias = "get_archive_extension"})
-- archive archivefile using xmake compress module
function _archive_using_xmz(archivefile, inputfiles, extension, opt)
archive_xmz(archivefile, inputfiles, opt)
return true
end
-- archive archivefile using zip
function _archive_using_zip(archivefile, inputfiles, extension, opt)
-- find zip
local zip = find_tool("zip")
if not zip then
return false
end
-- init argv
local argv = {archivefile}
if not option.get("verbose") then
table.insert(argv, "-q")
end
if opt.excludes then
table.insert(argv, "-x")
for _, exclude in ipairs(opt.excludes) do
table.insert(argv, exclude)
end
end
local compress = opt.compress
if compress then
if compress == "faster" or compress == "fastest" then
table.insert(argv, "-1")
elseif compress == "better" or compress == "best" then
table.insert(argv, "-9")
end
end
if opt.recurse then
table.insert(argv, "-r")
end
local inputlistfile = os.tmpfile()
if type(inputfiles) == "table" then
local file = io.open(inputlistfile, "w")
for _, inputfile in ipairs(inputfiles) do
file:print(inputfile)
end
file:close()
table.insert(argv, "-@")
else
table.insert(argv, inputfiles)
end
-- archive it
os.vrunv(zip.program, argv, {curdir = opt.curdir, stdin = inputlistfile})
if inputlistfile then
os.tryrm(inputlistfile)
end
return true
end
-- archive archivefile using 7z
function _archive_using_7z(archivefile, inputfiles, extension, opt)
-- find 7z
local z7 = find_tool("7z")
if not z7 then
return false
end
-- init argv
local argv = {"a", archivefile, "-y"}
local excludesfile
if opt.excludes then
excludesfile = os.tmpfile()
io.writefile(excludesfile, table.concat(table.wrap(opt.excludes), '\n'))
table.insert(argv, "-xr@" .. excludesfile)
end
local compress = opt.compress
if compress then
if compress == "fastest" then
table.insert(argv, "-mx1")
elseif compress == "faster" then
table.insert(argv, "-mx3")
elseif compress == "better" then
table.insert(argv, "-mx7")
elseif compress == "best" then
table.insert(argv, "-mx9")
end
end
if opt.recurse then
table.insert(argv, "-r")
end
local inputlistfile = os.tmpfile()
if type(inputfiles) == "table" then
local file = io.open(inputlistfile, "w")
for _, inputfile in ipairs(inputfiles) do
file:print(inputfile)
end
file:close()
table.insert(argv, "-i@" .. inputlistfile)
else
table.insert(argv, inputfiles)
end
-- archive it
os.vrunv(z7.program, argv, {curdir = opt.curdir})
-- remove the excludes files
if excludesfile then
os.tryrm(excludesfile)
end
if inputlistfile then
os.tryrm(inputlistfile)
end
return true
end
-- archive archivefile using xz
function _archive_using_xz(archivefile, inputfiles, extension, opt)
-- find xz
local xz = find_tool("xz")
if not xz then
return false
end
-- init argv
local argv = {"-z", "-k", "-c", archivefile}
if not option.get("verbose") then
table.insert(argv, "-q")
end
local compress = opt.compress
if compress then
if compress == "fastest" then
table.insert(argv, "-1")
elseif compress == "faster" then
table.insert(argv, "-3")
elseif compress == "better" then
table.insert(argv, "-7")
elseif compress == "best" then
table.insert(argv, "-9")
end
end
if type(inputfiles) == "table" then
for _, inputfile in ipairs(inputfiles) do
table.insert(argv, inputfile)
end
else
table.insert(argv, inputfiles)
end
-- archive it
os.vrunv(xz.program, argv, {stdout = archivefile, curdir = opt.curdir})
return true
end
-- archive archivefile using gzip
function _archive_using_gzip(archivefile, inputfiles, extension, opt)
-- find gzip
local gzip = find_tool("gzip")
if not gzip then
return false
end
-- init argv
local argv = {"-k", "-c", archivefile}
if not option.get("verbose") then
table.insert(argv, "-q")
end
local compress = opt.compress
if compress then
if compress == "fastest" then
table.insert(argv, "-1")
elseif compress == "faster" then
table.insert(argv, "-3")
elseif compress == "better" then
table.insert(argv, "-7")
elseif compress == "best" then
table.insert(argv, "-9")
end
end
if opt.recurse then
table.insert(argv, "-r")
end
if type(inputfiles) == "table" then
for _, inputfile in ipairs(inputfiles) do
table.insert(argv, inputfile)
end
else
table.insert(argv, inputfiles)
end
-- archive it
os.vrunv(gzip.program, argv, {stdout = archivefile, curdir = opt.curdir})
return true
end
-- archive archivefile using tar
function _archive_using_tar(archivefile, inputfiles, extension, opt)
-- find tar
local tar = find_tool("tar")
if not tar then
return false
end
-- with compress? e.g. .tar.xz
local compress = false
local archivefile_tar
if extension ~= ".tar" then
if is_host("windows") then
return false
else
compress = true
archivefile_tar = path.join(path.directory(archivefile), path.basename(archivefile))
end
end
-- init argv
local argv = {}
if compress then
table.insert(argv, "-a")
end
if option.get("verbose") then
table.insert(argv, "-cvf")
else
table.insert(argv, "-cf")
end
table.insert(argv, archivefile_tar and archivefile_tar or archivefile)
if opt.excludes then
for _, exclude in ipairs(opt.excludes) do
table.insert(argv, "--exclude=")
table.insert(argv, exclude)
end
end
if not opt.recurse then
table.insert(argv, "-n")
end
local inputlistfile = os.tmpfile()
if type(inputfiles) == "table" then
local file = io.open(inputlistfile, "w")
for _, inputfile in ipairs(inputfiles) do
file:print(inputfile)
end
file:close()
table.insert(argv, "-T")
table.insert(argv, inputlistfile)
else
table.insert(argv, inputfiles)
end
-- archive it
os.vrunv(tar.program, argv, {curdir = opt.curdir})
if inputlistfile then
os.tryrm(inputlistfile)
end
if archivefile_tar and os.isfile(archivefile_tar) then
_archive_tarfile(archivefile, archivefile_tar, opt)
os.rm(archivefile_tar)
end
return true
end
-- archive archive file using archivers
function _archive(archivefile, inputfiles, extension, archivers, opt)
local errors
for _, archive in ipairs(archivers) do
local ok = try {
function ()
return archive(archivefile, inputfiles, extension, opt)
end,
catch {
function (errs)
if errs then
errors = tostring(errs)
end
end
}
}
if ok then
return true
end
end
raise("cannot archive %s, %s!", path.filename(archivefile), errors or "archivers not found!")
end
-- only archive tar file
function _archive_tarfile(archivefile, tarfile, opt)
local archivers = {
[".xz"] = {_archive_using_xz}
, [".gz"] = {_archive_using_gzip}
}
local extension = opt.extension or path.extension(archivefile)
return _archive(archivefile, tarfile, extension, archivers[extension], opt)
end
-- archive file
--
-- @param archivefile the archive file. e.g. *.tar.gz, *.zip, *.7z, *.tar.bz2, ..
-- @param inputfiles the input file or directory or list
-- @param options the options, e.g.. {curdir = "/tmp", recurse = true, compress = "fastest|faster|default|better|best", excludes = {"*/dir/*", "dir/*"}}
--
function main(archivefile, inputfiles, opt)
opt = opt or {}
inputfiles = inputfiles or os.curdir()
if opt.recurse == nil then
opt.recurse = true
end
-- init archivers
local archivers = {
[".zip"] = {_archive_using_zip, _archive_using_7z}
, [".7z"] = {_archive_using_7z}
, [".xz"] = {_archive_using_xz}
, [".gz"] = {_archive_using_gzip}
, [".tar"] = {_archive_using_tar}
, [".tar.gz"] = {_archive_using_tar, _archive_using_gzip}
, [".tar.xz"] = {_archive_using_tar, _archive_using_xz}
, [".xmz"] = {_archive_using_xmz}
}
-- get extension
local extension = opt.extension or get_archive_extension(archivefile)
-- ensure output directory
local archivedir = path.directory(archivefile)
if not os.isdir(archivedir) then
os.mkdir(archivedir)
end
-- archive it
return _archive(archivefile, inputfiles, extension, archivers[extension], opt)
end
|
0 | repos/xmake/xmake/modules/utils | repos/xmake/xmake/modules/utils/archive/merge_staticlib.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file merge_staticlib.lua
--
-- imports
import("core.base.option")
import("private.tools.vstool")
-- merge *.a archive libraries for ar
function _merge_for_ar(target, program, outputfile, libraryfiles, opt)
opt = opt or {}
if target:is_plat("macosx", "iphoneos", "watchos", "appletvos") then
os.vrunv("libtool", table.join("-static", "-o", outputfile, libraryfiles))
else
-- we can't generate directly to outputfile,
-- because on windows/ndk, llvm-ar.exe may fail to write with no permission, even though it's a writable temp file.
--
-- @see https://github.com/xmake-io/xmake/issues/1973
local archivefile = target:autogenfile((hash.uuid(outputfile):gsub("%-", ""))) .. ".a"
os.mkdir(path.directory(archivefile))
local tmpfile = os.tmpfile()
local mrifile = io.open(tmpfile, "w")
mrifile:print("create %s", archivefile)
for _, libraryfile in ipairs(libraryfiles) do
mrifile:print("addlib %s", libraryfile)
end
mrifile:print("save")
mrifile:print("end")
mrifile:close()
os.vrunv(program, {"-M"}, {stdin = tmpfile})
os.cp(archivefile, outputfile)
os.rm(tmpfile)
os.rm(archivefile)
end
end
-- merge *.a archive libraries for msvc/lib.exe
function _merge_for_msvclib(target, program, outputfile, libraryfiles, opt)
opt = opt or {}
vstool.runv(program, table.join("-nologo", "-out:" .. outputfile, libraryfiles), {envs = opt.runenvs})
end
-- merge *.a archive libraries
function main(target, outputfile, libraryfiles)
local program, toolname = target:tool("ar")
if program and toolname then
if toolname:find("ar") then
_merge_for_ar(target, program, outputfile, libraryfiles)
elseif toolname == "link" and target:is_plat("windows") then
local msvc
for _, toolchain_inst in ipairs(target:toolchains()) do
if toolchain_inst:name() == "msvc" then
msvc = toolchain_inst
break
end
end
_merge_for_msvclib(target, (program:gsub("link%.exe", "lib.exe")), outputfile, libraryfiles, {runenvs = msvc and msvc:runenvs()})
else
raise("cannot merge (%s): unknown ar tool %s!", table.concat(libraryfiles, ", "), toolname)
end
else
raise("cannot merge (%s): ar not found!", table.concat(libraryfiles, ", "))
end
end
|
0 | repos/xmake/xmake/modules/utils | repos/xmake/xmake/modules/utils/archive/extension.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file extension.lua
--
-- imports
import("core.base.hashset")
-- get the archive extension
function main(archivefile)
local extension = ""
local filename = path.filename(archivefile)
local extensionset = hashset.from({
".xmz", -- xmake compression format
".zip", ".7z", ".gz", ".xz", ".tgz",
".bz2", ".tar", ".tar.gz", ".tar.xz",
".tar.bz2", ".tar.Z"})
local i = filename:lastof(".", true)
if i then
local p = filename:sub(1, i - 1):lastof(".", true)
if p and extensionset:has(filename:sub(p)) then i = p end
extension = filename:sub(i)
end
return extensionset:has(extension) and extension or ""
end
|
0 | repos/xmake/xmake/modules/utils | repos/xmake/xmake/modules/utils/binary/deplibs.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file deplibs.lua
--
-- imports
import("core.base.option")
import("core.tool.toolchain")
import("lib.detect.find_tool")
function _get_all_depends_by_dumpbin(binaryfile, opt)
local depends
local plat = opt.plat or os.host()
local arch = opt.arch or os.arch()
local cachekey = "utils.binary.deplibs"
local msvc = toolchain.load("msvc", {plat = plat, arch = arch})
if msvc:check() then
local dumpbin = find_tool("dumpbin", {cachekey = cachekey, envs = msvc:runenvs()})
if dumpbin then
local binarydir = path.directory(binaryfile)
local result = try { function () return os.iorunv(dumpbin.program, {"/dependents", "/nologo", binaryfile}) end }
if result then
for _, line in ipairs(result:split("\n")) do
line = line:trim()
if line:endswith(".dll") then
depends = depends or {}
table.insert(depends, line)
end
end
end
end
end
return depends
end
function _get_all_depends_by_objdump(binaryfile, opt)
local depends
local plat = opt.plat or os.host()
local arch = opt.arch or os.arch()
local cachekey = "utils.binary.deplibs"
local objdump = find_tool("llvm-objdump", {cachekey = cachekey}) or find_tool("objdump", {cachekey = cachekey})
if objdump then
local binarydir = path.directory(binaryfile)
local argv = {"-p", binaryfile}
if plat == "macosx" or plat == "iphoneos" or plat == "appletvos" or plat == "watchos" then
argv = {"--macho", "--dylibs-used", binaryfile}
end
local result = try { function () return os.iorunv(objdump.program, argv) end }
if result then
for _, line in ipairs(result:split("\n")) do
line = line:trim()
if plat == "windows" or plat == "mingw" then
if line:startswith("DLL Name:") then
local filename = line:split(":")[2]:trim()
if filename:endswith(".dll") then
depends = depends or {}
table.insert(depends, filename)
end
end
elseif plat == "macosx" or plat == "iphoneos" or plat == "appletvos" or plat == "watchos" then
local filename = line:match(".-%.dylib") or line:match(".-%.framework")
if filename then
depends = depends or {}
table.insert(depends, filename)
end
else
if line:startswith("NEEDED") then
local filename = line:split("%s+")[2]
if filename and filename:endswith(".so") then
depends = depends or {}
table.insert(depends, filename)
end
end
end
end
end
end
return depends
end
-- $ldd ./build/linux/x86_64/release/test
-- linux-vdso.so.1 (0x00007ffc51fdd000)
-- libfoo.so => /mnt/xmake/tests/projects/c/shared_library/./build/linux/x86_64/release/libfoo.so (0x00007fe241233000)
-- libstdc++.so.6 => /lib64/libstdc++.so.6 (0x00007fe240fca000)
-- libm.so.6 => /lib64/libm.so.6 (0x00007fe240ee7000)
-- libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007fe240eba000)
-- libc.so.6 => /lib64/libc.so.6 (0x00007fe240ccd000)
-- /lib64/ld-linux-x86-64.so.2 (0x00007fe24123a000)
--
function _get_all_depends_by_ldd(binaryfile, opt)
local plat = opt.plat or os.host()
local arch = opt.arch or os.arch()
if plat ~= "linux" and plat ~= "bsd" then
return
end
local depends
local cachekey = "utils.binary.deplibs"
local ldd = find_tool("ldd", {cachekey = cachekey})
if ldd then
local binarydir = path.directory(binaryfile)
local result = try { function () return os.iorunv(ldd.program, {binaryfile}) end }
if result then
for _, line in ipairs(result:split("\n")) do
local splitinfo = line:split("=>")
line = splitinfo[2]
if not line or line:find("not found", 1, true) then
line = splitinfo[1]
end
line = line:gsub("%(.+%)", ""):trim()
local filename = line:match(".-%.so$") or line:match(".-%.so%.%d+")
if filename then
depends = depends or {}
table.insert(depends, filename:trim())
end
end
end
end
return depends
end
-- $ readelf -d build/linux/x86_64/release/test
--
-- Dynamic section at offset 0x2db8 contains 29 entries:
-- Tag Type Name/Value
-- 0x0000000000000001 (NEEDED) Shared library: [libfoo.so]
-- 0x0000000000000001 (NEEDED) Shared library: [libstdc++.so.6]
-- 0x0000000000000001 (NEEDED) Shared library: [libm.so.6]
-- 0x0000000000000001 (NEEDED) Shared library: [libgcc_s.so.1]
-- 0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
-- 0x000000000000001d (RUNPATH) Library runpath: [$ORIGIN]
function _get_all_depends_by_readelf(binaryfile, opt)
local plat = opt.plat or os.host()
local arch = opt.arch or os.arch()
if plat ~= "linux" and plat ~= "bsd" and plat ~= "android" and plat ~= "cross" then
return
end
local depends
local cachekey = "utils.binary.deplibs"
local readelf = find_tool("readelf", {cachekey = cachekey})
if readelf then
local binarydir = path.directory(binaryfile)
local result = try { function () return os.iorunv(readelf.program, {"-d", binaryfile}) end }
if result then
for _, line in ipairs(result:split("\n")) do
if line:find("NEEDED", 1, true) then
local filename = line:match("Shared library: %[(.-)%]")
if filename then
depends = depends or {}
table.insert(depends, filename:trim())
end
end
end
end
end
return depends
end
-- $ otool -L build/iphoneos/arm64/release/test
-- build/iphoneos/arm64/release/test:
-- @rpath/libfoo.dylib (compatibility version 0.0.0, current version 0.0.0)
-- /System/Library/Frameworks/Foundation.framework/Foundation (compatibility version 300.0.0, current version 2048.1.101)
-- /usr/lib/libobjc.A.dylib (compatibility version 1.0.0, current version 228.0.0)
-- /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 1600.151.0)
-- /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1336.0.0)
--
function _get_all_depends_by_otool(binaryfile, opt)
local plat = opt.plat or os.host()
local arch = opt.arch or os.arch()
if plat ~= "macosx" and plat ~= "iphoneos" and plat ~= "appletvos" and plat ~= "watchos" then
return
end
local depends
local cachekey = "utils.binary.deplibs"
local otool = find_tool("otool", {cachekey = cachekey})
if otool then
local binarydir = path.directory(binaryfile)
local result = try { function () return os.iorunv(otool.program, {"-L", binaryfile}) end }
if result then
for _, line in ipairs(result:split("\n")) do
local filename = line:match(".-%.dylib") or line:match(".-%.framework")
if filename then
depends = depends or {}
table.insert(depends, filename:trim())
end
end
end
end
return depends
end
function main(binaryfile, opt)
opt = opt or {}
local ops = {
_get_all_depends_by_objdump,
_get_all_depends_by_readelf
}
if is_host("windows") then
table.insert(ops, 2, _get_all_depends_by_dumpbin)
elseif is_host("linux", "bsd") then
table.insert(ops, 1, _get_all_depends_by_ldd)
elseif is_host("macosx") then
table.insert(ops, 1, _get_all_depends_by_otool)
end
for _, op in ipairs(ops) do
local depends = op(binaryfile, opt)
if depends then
return depends
end
end
end
|
0 | repos/xmake/xmake/modules/utils | repos/xmake/xmake/modules/utils/binary/rpath.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file rpath.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_tool")
function _replace_rpath_vars(rpath, opt)
local plat = opt.plat or os.host()
local arch = opt.arch or os.arch()
if plat == "macosx" or plat == "iphoneos" or plat == "appletvos" or plat == "watchos" then
rpath = rpath:gsub("%$ORIGIN", "@loader_path")
else
rpath = rpath:gsub("@loader_path", "$ORIGIN")
rpath = rpath:gsub("@executable_path", "$ORIGIN")
end
return rpath
end
function _get_rpath_list_by_objdump(binaryfile, opt)
local list
local plat = opt.plat or os.host()
local arch = opt.arch or os.arch()
local cachekey = "utils.binary.rpath"
local objdump = find_tool("llvm-objdump", {cachekey = cachekey}) or find_tool("objdump", {cachekey = cachekey})
if objdump then
local binarydir = path.directory(binaryfile)
local argv = {"-x", binaryfile}
if plat == "macosx" or plat == "iphoneos" or plat == "appletvos" or plat == "watchos" then
argv = {"--macho", "-x", binaryfile}
end
local result = try { function () return os.iorunv(objdump.program, argv) end }
if result then
local cmd = false
for _, line in ipairs(result:split("\n")) do
line = line:trim()
if plat == "macosx" or plat == "iphoneos" or plat == "appletvos" or plat == "watchos" then
if not cmd and line:find("cmd LC_RPATH", 1, true) then
cmd = true
elseif cmd and (line:find("cmd ", 1, true) or line:find("Load command", 1, true)) then
cmd = false
end
if cmd then
local p = line:match("path (.-) %(")
if p then
list = list or {}
table.insert(list, p:trim())
end
end
else
if line:startswith("RUNPATH") or line:startswith("RPATH") then
local p = line:split("%s+")[2]
if p then
list = list or {}
table.join2(list, path.splitenv(p:trim()))
end
end
end
end
end
end
return list
end
-- $ readelf -d build/linux/x86_64/release/test
--
-- Dynamic section at offset 0x2db8 contains 29 entries:
-- Tag Type Name/Value
-- 0x0000000000000001 (NEEDED) Shared library: [libfoo.so]
-- 0x0000000000000001 (NEEDED) Shared library: [libstdc++.so.6]
-- 0x0000000000000001 (NEEDED) Shared library: [libm.so.6]
-- 0x0000000000000001 (NEEDED) Shared library: [libgcc_s.so.1]
-- 0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
-- 0x000000000000001d (RUNPATH) Library runpath: [$ORIGIN]
-- ...
-- 0x000000000000000f (RPATH) Library rpath: [$ORIGIN]
function _get_rpath_list_by_readelf(binaryfile, opt)
local plat = opt.plat or os.host()
local arch = opt.arch or os.arch()
if plat ~= "linux" and plat ~= "bsd" and plat ~= "android" and plat ~= "cross" then
return
end
local list
local cachekey = "utils.binary.rpath"
local readelf = find_tool("readelf", {cachekey = cachekey})
if readelf then
local binarydir = path.directory(binaryfile)
local result = try { function () return os.iorunv(readelf.program, {"-d", binaryfile}) end }
if result then
for _, line in ipairs(result:split("\n")) do
if line:find("RUNPATH", 1, true) then
local p = line:match("Library runpath: %[(.-)%]")
if p then
list = list or {}
table.join2(list, path.splitenv(p:trim()))
end
elseif line:find("RPATH", 1, true) then
local p = line:match("Library rpath: %[(.-)%]")
if p then
list = list or {}
table.join2(list, path.splitenv(p:trim()))
end
end
end
end
end
return list
end
-- $ patchelf --print-rpath ./build/linux/x86_64/release/app
-- $ORIGIN:xxx:bar
function _get_rpath_list_by_patchelf(binaryfile, opt)
local plat = opt.plat or os.host()
local arch = opt.arch or os.arch()
if plat ~= "linux" and plat ~= "bsd" and plat ~= "android" and plat ~= "cross" then
return
end
local list
local cachekey = "utils.binary.rpath"
local patchelf = find_tool("patchelf", {cachekey = cachekey})
if patchelf then
local binarydir = path.directory(binaryfile)
local result = try { function () return os.iorunv(patchelf.program, {"--print-rpath", binaryfile}) end }
if result then
result = result:trim()
if #result > 0 then
list = path.splitenv(result)
end
end
end
return list
end
-- $ otool -l build/iphoneos/arm64/release/test
-- build/iphoneos/arm64/release/test:
-- cmd LC_RPATH
-- cmdsize 32
-- path @loader_path (offset 12)
--
function _get_rpath_list_by_otool(binaryfile, opt)
local plat = opt.plat or os.host()
local arch = opt.arch or os.arch()
if plat ~= "macosx" and plat ~= "iphoneos" and plat ~= "appletvos" and plat ~= "watchos" then
return
end
local list
local cachekey = "utils.binary.rpath"
local otool = find_tool("otool", {cachekey = cachekey})
if otool then
local binarydir = path.directory(binaryfile)
local result = try { function () return os.iorunv(otool.program, {"-l", binaryfile}) end }
if result then
local cmd = false
for _, line in ipairs(result:split("\n")) do
if not cmd and line:find("cmd LC_RPATH", 1, true) then
cmd = true
elseif cmd and (line:find("cmd ", 1, true) or line:find("Load command", 1, true)) then
cmd = false
end
if cmd then
local p = line:match("path (.-) %(")
if p then
list = list or {}
table.insert(list, p:trim())
end
end
end
end
end
return list
end
-- patchelf --add-rpath binaryfile
function _insert_rpath_by_patchelf(binaryfile, rpath, opt)
local plat = opt.plat or os.host()
local arch = opt.arch or os.arch()
if plat ~= "linux" and plat ~= "bsd" and plat ~= "android" and plat ~= "cross" then
return false
end
local ok = try { function ()
os.runv("patchelf", {"--add-rpath", rpath, binaryfile})
return true
end }
return ok
end
-- install_name_tool -add_rpath <rpath> binaryfile
function _insert_rpath_by_install_name_tool(binaryfile, rpath, opt)
local plat = opt.plat or os.host()
local arch = opt.arch or os.arch()
if plat ~= "macosx" and plat ~= "iphoneos" and plat ~= "appletvos" and plat ~= "watchos" then
return false
end
local ok = try { function ()
os.vrunv("install_name_tool", {"-add_rpath", rpath, binaryfile})
return true
end }
return ok
end
-- install_name_tool -rpath <rpath_old> <rpath_new> binaryfile
function _change_rpath_by_install_name_tool(binaryfile, rpath_old, rpath_new, opt)
local plat = opt.plat or os.host()
local arch = opt.arch or os.arch()
if plat ~= "macosx" and plat ~= "iphoneos" and plat ~= "appletvos" and plat ~= "watchos" then
return false
end
local ok = try { function ()
os.vrunv("install_name_tool", {"-rpath", rpath_old, rpath_new, binaryfile})
return true
end }
return ok
end
-- use patchelf to remove the given rpath
function _remove_rpath_by_patchelf(binaryfile, rpath, opt)
local plat = opt.plat or os.host()
local arch = opt.arch or os.arch()
if plat ~= "linux" and plat ~= "bsd" and plat ~= "android" and plat ~= "cross" then
return false
end
local ok = try { function ()
local result = os.iorunv("patchelf", {"--print-rpath", binaryfile})
if result then
local rpaths_new = {}
local removed = false
for _, p in ipairs(path.splitenv(result:trim())) do
if p ~= rpath then
table.insert(rpaths_new, p)
else
removed = true
end
end
if removed then
if #rpaths_new > 0 then
os.runv("patchelf", {"--set-rpath", path.joinenv(rpaths_new), binaryfile})
else
os.runv("patchelf", {"--remove-rpath", binaryfile})
end
end
end
return true
end }
return ok
end
-- install_name_tool -delete_rpath <rpath> binaryfile
function _remove_rpath_by_install_name_tool(binaryfile, rpath, opt)
local plat = opt.plat or os.host()
local arch = opt.arch or os.arch()
if plat ~= "macosx" and plat ~= "iphoneos" and plat ~= "appletvos" and plat ~= "watchos" then
return false
end
local ok = try { function ()
os.vrunv("install_name_tool", {"-delete_rpath", rpath, binaryfile})
return true
end }
return ok
end
-- patchelf --remove-rpath binaryfile
function _clean_rpath_by_patchelf(binaryfile, opt)
local plat = opt.plat or os.host()
local arch = opt.arch or os.arch()
if plat ~= "linux" and plat ~= "bsd" and plat ~= "android" and plat ~= "cross" then
return false
end
local ok = try { function ()
os.runv("patchelf", {"--remove-rpath", binaryfile})
return true
end }
return ok
end
-- get rpath list
function list(binaryfile, opt)
opt = opt or {}
local ops = {
_get_rpath_list_by_objdump,
_get_rpath_list_by_readelf,
_get_rpath_list_by_patchelf
}
if is_host("macosx") then
table.insert(ops, 1, _get_rpath_list_by_otool)
end
for _, op in ipairs(ops) do
local result = op(binaryfile, opt)
if result then
return result
end
end
end
-- insert rpath
function insert(binaryfile, rpath, opt)
opt = opt or {}
local ops = {
_insert_rpath_by_patchelf
}
if is_host("macosx") then
table.insert(ops, 1, _insert_rpath_by_install_name_tool)
end
rpath = _replace_rpath_vars(rpath, opt)
local done = false
for _, op in ipairs(ops) do
if op(binaryfile, rpath, opt) then
done = true
break
end
end
if not done then
wprint("cannot insert rpath to %s, no rpath utility available, maybe we need to install patchelf", binaryfile)
end
end
-- remove rpath
function remove(binaryfile, rpath, opt)
opt = opt or {}
local ops = {
_remove_rpath_by_patchelf
}
if is_host("macosx") then
table.insert(ops, 1, _remove_rpath_by_install_name_tool)
end
rpath = _replace_rpath_vars(rpath, opt)
for _, op in ipairs(ops) do
if op(binaryfile, rpath, opt) then
break
end
end
end
-- change rpath
function change(binaryfile, rpath_old, rpath_new, opt)
local function _change_rpath_by_generic(binaryfile, rpath_old, rpath_new, opt)
remove(binaryfile, rpath_old, opt)
insert(binaryfile, rpath_new, opt)
return true
end
opt = opt or {}
local ops = {
_change_rpath_by_generic
}
if is_host("macosx") then
table.insert(ops, 1, _change_rpath_by_install_name_tool)
end
rpath_old = _replace_rpath_vars(rpath_old, opt)
rpath_new = _replace_rpath_vars(rpath_new, opt)
local done = false
for _, op in ipairs(ops) do
if op(binaryfile, rpath_old, rpath_new, opt) then
done = true
break
end
end
if not done then
wprint("cannot change rpath to %s, no rpath utility available, maybe we need to install patchelf", binaryfile)
end
end
-- clean rpath
function clean(binaryfile, opt)
local function _clean_rpath_by_generic(binaryfile, opt)
for _, rpath in ipairs(list(binaryfile, opt)) do
remove(binaryfile, rpath, opt)
end
return true
end
opt = opt or {}
local ops = {
_clean_rpath_by_patchelf,
_clean_rpath_by_generic
}
local done = false
for _, op in ipairs(ops) do
if op(binaryfile, opt) then
done = true
break
end
end
if not done then
wprint("cannot clean rpath %s, no rpath utility available, maybe we need to install patchelf", binaryfile)
end
end
|
0 | repos/xmake/xmake/modules/utils | repos/xmake/xmake/modules/utils/ipa/resign.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file resign.lua
--
-- imports
import("lib.detect.find_tool")
import("lib.detect.find_directory")
import("utils.archive.extract")
import("private.tools.codesign")
import("utils.ipa.package", {alias = "ipagen"})
-- resign *.app directory
function _resign_app(appdir, codesign_identity, mobile_provision, bundle_identifier)
-- get default codesign identity
if not codesign_identity then
for identity, _ in pairs(codesign.codesign_identities()) do
codesign_identity = identity
break
end
end
-- get default mobile provision
if not mobile_provision then
for provision, _ in pairs(codesign.mobile_provisions()) do
mobile_provision = provision
break
end
end
-- generate embedded.mobileprovision to *.app/embedded.mobileprovision
local mobile_provision_embedded = path.join(appdir, "embedded.mobileprovision")
if mobile_provision then
os.tryrm(mobile_provision_embedded)
local provisions = codesign.mobile_provisions()
if provisions then
local mobile_provision_data = provisions[mobile_provision]
if mobile_provision_data then
io.writefile(mobile_provision_embedded, mobile_provision_data)
end
end
end
-- replace bundle identifier of Info.plist
if bundle_identifier then
local info_plist_file = path.join(appdir, "Info.plist")
if os.isfile(info_plist_file) then
local info_plist_data = io.readfile(info_plist_file)
if info_plist_data then
local p = info_plist_data:find("<key>CFBundleIdentifier</key>", 1, true)
if p then
local e = info_plist_data:find("</string>", p, true)
if e then
local block = info_plist_data:sub(p, e + 9):match("<string>(.+)</string>")
if block then
info_plist_data = info_plist_data:gsub(block, bundle_identifier)
io.writefile(info_plist_file, info_plist_data)
end
end
end
end
end
end
-- do codesign
codesign(appdir, codesign_identity, mobile_provision)
end
-- resign *.ipa file
function _resign_ipa(ipafile, codesign_identity, mobile_provision, bundle_identifier)
-- get resigned ipa file
local ipafile_resigned = path.join(path.directory(ipafile), path.basename(ipafile) .. "_resign" .. path.extension(ipafile))
-- extract *.ipa file
local appdir = os.tmpfile() .. ".app"
extract(ipafile, appdir, {extension = ".zip"})
-- find real *.app directory
local appdir_real = find_directory("**.app", appdir)
if not appdir_real then
appdir_real = appdir
end
-- resign *.app directory
_resign_app(appdir_real, codesign_identity, mobile_provision, bundle_identifier)
-- re-generate *.ipa file
ipagen(appdir_real, ipafile_resigned)
-- remove tmp files
os.tryrm(appdir)
-- trace
cprint("output: ${bright}%s", ipafile_resigned)
end
-- main entry
function main (filepath, codesign_identity, mobile_provision, bundle_identifier)
-- check
assert(os.exists(filepath), "%s not found!", filepath)
-- resign *.ipa or *.app application
if os.isfile(filepath) then
_resign_ipa(filepath, codesign_identity, mobile_provision, bundle_identifier)
else
_resign_app(filepath, codesign_identity, mobile_provision, bundle_identifier)
end
-- ok
cprint("${color.success}resign ok!")
end
|
0 | repos/xmake/xmake/modules/utils | repos/xmake/xmake/modules/utils/ipa/install.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file install.lua
--
-- imports
import("utils.ipa.package", {alias = "ipagen"})
import("lib.detect.find_tool")
-- main entry
function main (ipafile)
-- check
assert(os.exists(ipafile), "%s not found!", ipafile)
-- find ideviceinstaller
local ideviceinstaller = assert(find_tool("ideviceinstaller"), "ideviceinstaller not found!")
-- is *.app directory? package it first
local istmp = false
if os.isdir(ipafile) then
local appdir = ipafile
ipafile = os.tmpfile() .. ".ipa"
ipagen(appdir, ipafile)
istmp = true
end
-- do install
os.vrunv(ideviceinstaller.program, {"-i", ipafile})
if istmp then
os.tryrm(ipafile)
end
end
|
0 | repos/xmake/xmake/modules/utils | repos/xmake/xmake/modules/utils/ipa/package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file package.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_tool")
-- main entry
function main (appdir, ipafile, iconfile)
-- check
assert(appdir)
assert(os.isdir(appdir), "%s not found!", appdir)
-- find zip
local zip = find_tool("zip")
assert(zip, "zip not found!")
-- get the .ipa file path
local appname = path.basename(appdir)
if not ipafile then
ipafile = path.join(path.directory(appdir), appname .. ".ipa")
end
ipafile = path.absolute(ipafile)
-- remove the old ipafile first
os.tryrm(ipafile)
-- the temporary directory
local tmpdir = path.join(os.tmpdir(), "ipagen", appname)
-- clean the tmpdir first
os.rm(tmpdir)
-- make the payload directory
os.mkdir(path.join(tmpdir, "Payload"))
-- copy the .app directory into payload
os.vcp(appdir, path.join(tmpdir, "Payload"))
-- copy icon file to iTunesArtwork
if iconfile then
os.vcp(iconfile, path.join(tmpdir, "iTunesArtwork"))
end
-- generate .ipa file
local argv = {"-r", ipafile, "Payload"}
if iconfile then
table.insert(argv, "iTunesArtwork")
end
local oldir = os.cd(tmpdir)
os.vrunv(zip.program, argv)
os.cd(oldir)
-- remove the temporary directory
os.rm(tmpdir)
-- check
assert(os.isfile(ipafile), "generate %s failed!", ipafile)
end
|
0 | repos/xmake/xmake/modules/utils | repos/xmake/xmake/modules/utils/wdk/testcert.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file testcert.lua
--
-- imports
import("core.base.option")
import("core.base.global")
import("core.project.config")
import("detect.sdks.find_wdk")
-- get tool
function _get_tool(wdk, name)
-- init cache
_g.tools = _g.tools or {}
-- get it from the cache
local tool = _g.tools[name]
if not tool then
-- get arch
local arch = config.arch() or os.arch()
-- get tool
tool = path.join(wdk.bindir, arch, name .. ".exe")
if not os.isexec(tool) then
tool = path.join(wdk.bindir, wdk.sdkver, arch, name .. ".exe")
end
assert(os.isexec(tool), name .. " not found!")
_g.tools[name] = tool
end
return tool
end
-- install test certificate
function _install(wdk)
-- get signtool
local signtool = _get_tool(wdk, "signtool")
-- check test certificate first
local ok = try
{
function ()
local tmpfile = os.tmpfile(os.programfile())
if not os.isfile(tmpfile) then
os.cp(os.programfile(), tmpfile)
end
os.vrunv(signtool, {"sign", "/v", "/a", "/s", "PrivateCertStore", "/n", "tboox.org(test)", tmpfile})
return true
end
}
if ok then
return
end
-- get makecert
local makecert = _get_tool(wdk, "makecert")
-- get certmgr
local certmgr = _get_tool(wdk, "certmgr")
-- get a test certificate
local testcer = path.join(global.directory(), "sign", "test.cer")
local company = "tboox.org(test)"
-- make a new test certificate @note need re-generate certificate when reinstalling
local signdir = path.directory(testcer)
if not os.isdir(signdir) then
os.mkdir(signdir)
end
os.vrunv(makecert, {"-r", "-pe", "-ss", "PrivateCertStore", "-n", "CN=" .. company, testcer})
-- register this test certificate
try
{
function ()
os.vrunv(certmgr, {"/add", testcer, "/s", "/r", "localMachine", "root"})
os.vrunv(certmgr, {"/add", testcer, "/s", "/r", "localMachine", "trustedpublisher"})
end,
catch
{
function (errors)
os.tryrm(testcer)
raise(errors)
end
}
}
-- trace
print("install test certificate ok!")
print(" - company: %s", company)
print(" - cerfile: %s", testcer)
end
-- entry function
function main(action)
-- find wdk envirnoment first
local wdk = find_wdk()
assert(wdk, "wdk not found!")
-- install or uninstall test certificate
if action == "install" then
_install(wdk)
end
end
|
0 | repos/xmake/xmake/modules/utils | repos/xmake/xmake/modules/utils/platform/gnu2mslib.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file gnu2mslib.lua
--
-- imports
import("core.base.option")
import("core.base.hashset")
import("core.project.config")
import("core.tool.toolchain")
import("lib.detect.find_tool")
-- get .def file path from gnulib
function _get_defpath_from_gnulib(gnulib, msvc)
-- check
assert(os.isfile(gnulib), "%s not found!", gnulib)
-- get dumpbin.exe
local dumpbin = assert(find_tool("dumpbin", {envs = msvc:runenvs()}), "gnu2mslib(): dumpbin.exe not found!")
-- get symbols
local symbols_exported = hashset.new()
local symbols = try {function() return os.iorunv(dumpbin.program, {"/linkermember", gnulib}) end}
if symbols then
local symbols_count
local symbols_index = 0
for _, line in ipairs(symbols:split('\n', {plain = true})) do
if symbols_count == nil then
symbols_count = line:match("(%d+) public symbols")
if symbols_count then
symbols_count = tonumber(symbols_count)
end
else
local symbol = line:match("%s+[%dABCDEF]+%s+(.+)")
if symbol then
if not symbol:startswith("__") and not symbol:startswith("?") then
symbols_exported:insert(symbol)
end
symbols_index = symbols_index + 1
if symbols_index >= symbols_count then
break
end
end
end
end
end
-- generate .def file
if symbols_exported:size() > 0 then
local defpath = os.tmpfile() .. ".def"
local file = io.open(defpath, "w")
file:print("EXPORTS")
for _, symbol in ipairs(symbols_exported) do
file:print("%s", symbol)
end
file:close()
return defpath
end
end
-- convert mingw/gnu xxx.dll.a to msvc xxx.lib
--
-- gnu2mslib(mslib, gnulib_or_defpath, {arch = "x64", dllname = "foo.dll"}
--
-- @see https://github.com/xmake-io/xmake/issues/1181
--
function main(mslib, gnulib_or_defpath, opt)
-- check
opt = opt or {}
assert(is_host("windows"), "we can only run gnu2mslib() on windows!")
assert(mslib and gnulib_or_defpath, "invalid input parameters, usage: gnu2mslib(mslib, gnulib_or_defpath, {arch = \"x64\", dllname = \"foo.dll\"})")
-- get msvc toolchain
local msvc = toolchain.load("msvc", {plat = opt.plat, arch = opt.arch})
if not msvc:check() then
raise("we can not get msvc toolchain!")
end
-- get lib.exe
local libtool = assert(find_tool("lib", {envs = msvc:runenvs()}), "gnu2mslib(): lib.exe not found!")
-- get dll name
local dllname = opt.dllname or path.basename(mslib) .. ".dll"
-- get def file path
local defpath = gnulib_or_defpath:endswith(".def") and gnulib_or_defpath or _get_defpath_from_gnulib(gnulib_or_defpath, msvc)
assert(defpath and os.isfile(defpath), "gnu2mslib(): convert failed, cannot get .def file!")
-- generate mslib from gnulib
os.vrunv(libtool.program, {"/machine:" .. opt.arch, "/def:" .. defpath, "/name:" .. path.filename(dllname), "/out:" .. mslib}, {envs = msvc:runenvs()})
-- remove temporary .def file
if not gnulib_or_defpath:endswith(".def") then
os.rm(defpath)
end
end
|
0 | repos/xmake/xmake/modules/utils | repos/xmake/xmake/modules/utils/ci/is_running.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file is_running.lua
--
-- is running on ci(travis/appveyor/...)?
function main()
local on_ci = _g._ON_CI
if on_ci == nil then
local ci = (os.getenv("CI") or os.getenv("GITHUB_ACTIONS") or ""):lower()
if ci == "true" or ci == "1" then
on_ci = true
else
on_ci = false
end
_g._ON_CI = on_ci
end
return on_ci
end
|
0 | repos/xmake/xmake/modules/utils | repos/xmake/xmake/modules/utils/ci/packageskey.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file packageskey.lua
--
-- imports
import("core.base.option")
import("private.action.require.impl.package")
import("private.action.require.impl.utils.get_requires")
-- generate a hash key of all packages to cache packages on github/ci
--
-- on windows.yml
--
-- - name: Retrieve dependencies hash
-- id: packageskey
-- run: echo "::set-output name=hash::$(xmake l utils.ci.packageskey)"
-- Cache xmake dependencies
-- - name: Retrieve cached xmake dependencies
-- uses: actions/cache@v2
-- with:
-- path: ${{env.APPLOCALDATA}}\.xmake\packages
-- key: ${{ steps.packageskey.outputs.hash }}
--
function main(requires_raw)
-- suppress all logs
option.save()
option.set("quiet", true, {force = true})
-- get requires and extra config
local requires_extra = nil
local requires, requires_extra = get_requires(requires_raw)
if not requires or #requires == 0 then
return
end
-- get keys
local keys = {}
for _, instance in ipairs(package.load_packages(requires, {requires_extra = requires_extra})) do
table.insert(keys, instance:installdir()) -- contain name/version/buildhash
end
table.sort(keys)
keys = table.concat(keys, ",")
option.restore()
print(hash.uuid4(keys):gsub('-', ''):lower())
end
|
0 | repos/xmake/xmake/modules | repos/xmake/xmake/modules/net/proxy.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file proxy.lua
--
-- imports
import("core.base.global")
-- get proxy hosts
function _proxy_hosts()
local proxy_hosts = _g._PROXY_HOSTS
if proxy_hosts == nil then
proxy_hosts = global.get("proxy_hosts")
if proxy_hosts then
proxy_hosts = proxy_hosts:split(',', {plain = true})
end
_g._PROXY_HOSTS = proxy_hosts or false
end
return proxy_hosts or nil
end
-- get proxy pac file
--
-- pac.lua
--
-- @code
-- function mirror(url)
-- return url:gsub("github.com", "hub.fastgit.org")
-- end
-- function main(url, host)
-- if host:find("bintray.com") then
-- return true
-- end
-- end
-- @endcode
--
function _proxy_pac()
local proxy_pac = _g._PROXY_PAC
if proxy_pac == nil then
local pac = global.get("proxy_pac")
local pacfile
if pac and pac:endswith(".lua") then
if os.isfile(pac) then
pacfile = pac
end
if not pacfile and not path.is_absolute(pac) then
pacfile = path.join(global.directory(), pac)
if not os.isfile(pacfile) and os.isfile(path.join(os.programdir(), "scripts", "pac", pac)) then
pacfile = path.join(os.programdir(), "scripts", "pac", pac)
end
end
end
if pacfile and os.isfile(pacfile) then
proxy_pac = import(path.basename(pacfile), {rootdir = path.directory(pacfile), try = true, anonymous = true})
end
_g._PROXY_PAC = proxy_pac or false
end
return proxy_pac or nil
end
-- convert host pattern to a lua pattern
function _host_pattern(pattern)
pattern = pattern:gsub("([%+%.%-%^%$%(%)%%])", "%%%1")
pattern = pattern:gsub("%*", "\001")
pattern = pattern:gsub("\001", ".*")
return pattern
end
-- has main entry? it will be callable directly
function _is_callable(func)
if type(func) == "function" then
return true
elseif type(func) == "table" then
local meta = debug.getmetatable(func)
if meta and meta.__call then
return true
end
end
end
-- get proxy mirror url
function mirror(url)
local proxy_pac = _proxy_pac()
if proxy_pac and proxy_pac.mirror then
return proxy_pac.mirror(url)
end
return url
end
-- get proxy configuration from the given url, [protocol://]host[:port]
--
-- @see https://github.com/xmake-io/xmake/issues/854
--
function config(url)
-- enable proxy for the given url and configuration pattern
if url then
-- filter proxy host from the given hosts pattern
local host = url:match("://(.-)/") or url:match("@(.-):")
local proxy_hosts = _proxy_hosts()
if host and proxy_hosts then
host = host:lower()
for _, proxy_host in ipairs(proxy_hosts) do
proxy_host = proxy_host:lower()
if host == proxy_hosts or host:match(_host_pattern(proxy_host)) then
return global.get("proxy")
end
end
end
-- filter proxy host from the pac file
local proxy_pac = _proxy_pac()
if proxy_pac and host and _is_callable(proxy_pac) and proxy_pac(url, host) then
return global.get("proxy")
end
-- use global proxy
if not proxy_pac and not proxy_hosts then
return global.get("proxy")
end
return
end
-- enable global proxy
return global.get("proxy")
end
|
0 | repos/xmake/xmake/modules | repos/xmake/xmake/modules/net/fasturl.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file fasturl.lua
--
-- imports
import("ping")
-- http[s]://xxx.com[:1234]/.. or [email protected]:xxx/xxx.git
function _parse_host(url)
_g._URLHOSTS = _g._URLHOSTS or {}
local host = _g._URLHOSTS[url] or url:match("://([^/:]+)") or url:match("@(.-):")
_g._URLHOSTS[url] = host
return host
end
function add(urls)
local pinginfo = _g._PINGINFO or {}
_g._PINGHOSTS = _g._PINGHOSTS or {}
for _, url in ipairs(urls) do
local host = _parse_host(url)
if host and not pinginfo[host] then
table.insert(_g._PINGHOSTS, host)
end
end
end
function sort(urls)
-- ping hosts
local pinghosts = table.unique(_g._PINGHOSTS or {})
if pinghosts and #pinghosts > 0 then
local pinginfo = ping(pinghosts)
_g._PINGINFO = table.join(_g._PINGINFO or {}, pinginfo)
end
-- sort urls by the ping info
local pinginfo = _g._PINGINFO or {}
table.sort(urls, function(a, b)
a = pinginfo[_parse_host(a) or ""] or 65536
b = pinginfo[_parse_host(b) or ""] or 65536
return a < b
end)
_g._PINGHOSTS = {}
return urls
end
|
0 | repos/xmake/xmake/modules | repos/xmake/xmake/modules/net/ping.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file ping.lua
--
-- imports
import("core.cache.detectcache")
import("lib.detect.find_tool")
import("async.runjobs")
-- ping host
function _ping(ping, host)
local data = nil
if is_host("windows") then
data = try { function () return os.iorun("%s -n 1 -w 1000 %s", ping.program, host) end }
elseif is_host("macosx") then
data = try { function () return os.iorun("%s -c 1 -t 1 %s", ping.program, host) end }
else
-- https://github.com/xmake-io/xmake/issues/4470#issuecomment-1840338777
data = try { function () return os.iorun("%s -c 1 -W 1 -n %s", ping.program, host) end }
if not data then
data = try { function () return os.iorun("%s -c 1 -W 1 %s", ping.program, host) end }
end
end
local timeval = "65535"
if data then
timeval = data:match("time[=<]([%d%s%.]-)ms", 1, true) or data:match("[=<]([%d%s%.]-)ms TTL", 1, true) or "65535"
end
if timeval then
timeval = tonumber(timeval:trim())
end
return timeval
end
-- send ping to hosts
--
-- @param hosts the hosts
-- @param opt the options
--
-- @return the time or -1
--
function main(hosts, opt)
opt = opt or {}
local ping = find_tool("ping", opt)
if not ping then
return {}
end
local cacheinfo = nil
if not opt.force then
cacheinfo = detectcache:get("net.ping")
end
local results = {}
hosts = table.wrap(hosts)
runjobs("ping", function (index)
local host = hosts[index]
if host then
local timeval = nil
if cacheinfo then
timeval = cacheinfo[host]
end
if timeval then
results[host] = timeval
else
timeval = _ping(ping, host)
results[host] = timeval
if cacheinfo then
cacheinfo[host] = timeval
end
vprint("pinging the host(%s) ... %d ms", host, math.floor(timeval))
end
end
end, {total = #hosts})
if cacheinfo then
detectcache:set("net.ping", cacheinfo)
detectcache:save()
end
return results
end
|
0 | repos/xmake/xmake/modules/net | repos/xmake/xmake/modules/net/http/download.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file download.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_tool")
import("net.proxy")
-- get user agent
function _get_user_agent()
-- init user agent
if _g._USER_AGENT == nil then
-- init systems
local systems = {macosx = "Macintosh", linux = "Linux", windows = "Windows", msys = "MSYS", cygwin = "Cygwin"}
-- os user agent
local os_user_agent = ""
if is_host("macosx") then
local osver = try { function() return os.iorun("/usr/bin/sw_vers -productVersion") end }
if osver then
os_user_agent = ("Intel Mac OS X " .. (osver or "")):trim()
end
elseif is_subhost("linux", "msys", "cygwin") then
local osver = try { function () return os.iorun("uname -r") end }
if osver then
os_user_agent = (os_user_agent .. " " .. (osver or "")):trim()
end
end
-- make user agent
_g._USER_AGENT = string.format("Xmake/%s (%s;%s)", xmake.version(), systems[os.subhost()] or os.subhost(), os_user_agent)
end
return _g._USER_AGENT
end
-- download url using curl
function _curl_download(tool, url, outputfile, opt)
-- set basic arguments
local argv = {}
if option.get("verbose") then
table.insert(argv, "-SL")
else
table.insert(argv, "-fsSL")
end
-- use proxy?
local proxy_conf = proxy.config(url)
if proxy_conf then
table.insert(argv, "-x")
table.insert(argv, proxy_conf)
end
-- set user-agent
local user_agent = _get_user_agent()
if user_agent then
if tool.version then
user_agent = user_agent .. " curl/" .. tool.version
end
table.insert(argv, "-A")
table.insert(argv, user_agent)
end
-- ignore to check ssl certificates
if opt.insecure then
table.insert(argv, "-k")
end
-- add custom headers
if opt.headers then
for _, header in ipairs(opt.headers) do
table.insert(argv, "-H")
table.insert(argv, header)
end
end
-- continue to download?
if opt.continue then
table.insert(argv, "-C")
table.insert(argv, "-")
end
-- set timeout
if opt.timeout then
table.insert(argv, "--max-time")
table.insert(argv, tostring(opt.timeout))
end
-- set read timeout
if opt.read_timeout then
table.insert(argv, "--speed-limit")
table.insert(argv, "0")
table.insert(argv, "--speed-time")
table.insert(argv, tostring(opt.read_timeout))
end
-- set url
table.insert(argv, url)
-- ensure output directory
local outputdir = path.directory(outputfile)
if not os.isdir(outputdir) then
os.mkdir(outputdir)
end
-- set outputfile
table.insert(argv, "-o")
table.insert(argv, outputfile)
-- download it
os.vrunv(tool.program, argv)
end
-- download url using wget
function _wget_download(tool, url, outputfile, opt)
-- ensure output directory
local argv = {url}
local outputdir = path.directory(outputfile)
if not os.isdir(outputdir) then
os.mkdir(outputdir)
end
-- use proxy?
local proxy_conf = proxy.config(url)
if proxy_conf then
table.insert(argv, "-e")
table.insert(argv, "use_proxy=yes")
table.insert(argv, "-e")
if url:startswith("http://") then
table.insert(argv, "http_proxy=" .. proxy_conf)
elseif url:startswith("https://") then
table.insert(argv, "https_proxy=" .. proxy_conf)
elseif url:startswith("ftp://") then
table.insert(argv, "ftp_proxy=" .. proxy_conf)
else
table.insert(argv, "http_proxy=" .. proxy_conf)
end
end
-- set user-agent
local user_agent = _get_user_agent()
if user_agent then
if tool.version then
user_agent = user_agent .. " wget/" .. tool.version
end
table.insert(argv, "-U")
table.insert(argv, user_agent)
end
-- ignore to check ssl certificates
if opt.insecure then
table.insert(argv, "--no-check-certificate")
end
-- add custom headers
if opt.headers then
for _, header in ipairs(opt.headers) do
table.insert(argv, "--header=" .. header)
end
end
-- continue to download?
if opt.continue then
table.insert(argv, "-c")
end
-- set timeout
if opt.timeout then
table.insert(argv, "--timeout=" .. tostring(opt.timeout))
end
-- set read timeout
if opt.read_timeout then
table.insert(argv, "--read-timeout=" .. tostring(opt.read_timeout))
end
-- set outputfile
table.insert(argv, "-O")
table.insert(argv, outputfile)
-- download it
os.vrunv(tool.program, argv)
end
-- download url
--
-- @param url the input url
-- @param outputfile the output file
-- @param opt the option, {continue = true}
--
--
function main(url, outputfile, opt)
-- init output file
opt = opt or {}
outputfile = outputfile or path.filename(url):gsub("%?.+$", "")
-- attempt to download url using curl first
local tool = find_tool("curl", {version = true})
if tool then
return _curl_download(tool, url, outputfile, opt)
end
-- download url using wget
tool = find_tool("wget", {version = true})
if tool then
return _wget_download(tool, url, outputfile, opt)
end
assert(tool, "curl or wget not found!")
end
|
0 | repos/xmake/xmake/modules/package | repos/xmake/xmake/modules/package/manager/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_package.lua
--
-- imports
import("core.base.semver")
import("core.base.option")
import("core.project.config")
import("lib.detect.find_tool")
import("private.core.base.is_cross")
-- Is the current version matched?
function _is_match_version(current_version, require_version)
if current_version then
if current_version == require_version then
return true
end
if semver.is_valid(current_version) and semver.satisfies(current_version, require_version) then
return true
end
end
end
-- find package with the builtin rule
--
-- opt.system:
-- nil: find local or system packages
-- true: only find system package
-- false: only find local packages
--
function _find_package_with_builtin_rule(package_name, opt)
-- we cannot find it from xmake repo and package directories if only find system packages
local managers = {}
if opt.system ~= true then
table.insert(managers, "xmake")
end
-- find system package if be not disabled
if opt.system ~= false then
local plat = opt.plat
local arch = opt.arch
local find_from_host = not is_cross(plat, arch)
if find_from_host and not is_host("windows") then
table.insert(managers, "brew")
end
-- vcpkg/conan support multi-platforms/architectures
table.insert(managers, "vcpkg")
table.insert(managers, "conan")
if find_from_host then
table.insert(managers, "pkgconfig")
if is_subhost("linux", "msys") and plat ~= "windows" and find_tool("pacman") then
table.insert(managers, "pacman")
end
if is_subhost("linux", "msys") and plat ~= "windows" and find_tool("emerge") then
table.insert(managers, "portage")
end
table.insert(managers, "system")
end
end
-- find package from the given package manager
local result = nil
local found_manager_name = nil
opt = table.join({try = true}, opt)
for _, manager_name in ipairs(managers) do
dprint("finding %s from %s ..", package_name, manager_name)
result = import("package.manager." .. manager_name .. ".find_package", {anonymous = true})(package_name, opt)
if result then
found_manager_name = manager_name
break
end
end
return result, found_manager_name
end
-- find package
function _find_package(manager_name, package_name, opt)
-- find package from the given package manager
local result = nil
if manager_name then
-- trace
dprint("finding %s from %s ..", package_name, manager_name)
-- TODO compatible with the previous version: pkg_config (deprecated)
if manager_name == "pkg_config" then
manager_name = "pkgconfig"
wprint("please use find_package(\"pkgconfig::%s\") instead of `pkg_config::%s`", package_name, package_name)
end
-- find it
result = import("package.manager." .. manager_name .. ".find_package", {anonymous = true})(package_name, opt)
else
-- find package from the given custom "detect.packages.find_xxx" script
local builtin = false
local find_package = import("detect.packages.find_" .. package_name, {anonymous = true, try = true})
if find_package then
-- trace
dprint("finding %s from find_%s ..", package_name, package_name)
-- find it
result = find_package(table.join(opt, { find_package = function (...)
builtin = true
return _find_package_with_builtin_rule(...)
end}))
end
-- find package with the builtin rule
if not result and not builtin then
result, manager_name = _find_package_with_builtin_rule(package_name, opt)
end
end
-- found?
if result then
-- remove repeat
result.linkdirs = table.unique(result.linkdirs)
result.includedirs = table.unique(result.includedirs)
end
-- ok?
return result, manager_name
end
-- find package using the package manager
--
-- @param name the package name
-- e.g. zlib 1.12.x (try all), xmake::zlib 1.12.x, brew::zlib, brew::pcre/libpcre16, vcpkg::zlib, conan::OpenSSL/1.0.2n@conan/stable
-- @param opt the options
-- e.g. { verbose = false, force = false, plat = "iphoneos", arch = "arm64", mode = "debug", version = "1.0.x",
-- linkdirs = {"/usr/lib"}, includedirs = "/usr/include", links = {"ssl"}, includes = {"ssl.h"}
-- packagedirs = {"/tmp/packages"}, system = true}
--
-- @return {links = {"ssl", "crypto", "z"}, linkdirs = {"/usr/local/lib"}, includedirs = {"/usr/local/include"}},
-- manager_name, package_name
--
-- @code
--
-- local package = find_package("openssl")
-- local package = find_package("openssl", {require_version = "1.0.*"})
-- local package = find_package("openssl", {plat = "iphoneos"})
-- local package = find_package("openssl", {linkdirs = {"/usr/lib", "/usr/local/lib"}, includedirs = "/usr/local/include", require_version = "1.0.1"})
-- local package = find_package("openssl", {linkdirs = {"/usr/lib", "/usr/local/lib", links = {"ssl", "crypto"}, includes = {"ssl.h"}})
-- local package, manager_name, package_name = find_package("openssl")
--
-- @endcode
--
function main(name, opt)
-- get the copied options
opt = table.copy(opt)
opt.plat = opt.plat or config.get("plat") or os.host()
opt.arch = opt.arch or config.get("arch") or os.arch()
opt.mode = opt.mode or config.mode() or "release"
-- get package manager name
local manager_name, package_name = table.unpack(name:split("::", {plain = true, strict = true}))
if package_name == nil then
package_name = manager_name
manager_name = nil
else
manager_name = manager_name:lower():trim()
end
-- get package name and require version
local require_version = nil
package_name, require_version = table.unpack(package_name:trim():split("%s"))
opt.require_version = require_version or opt.require_version
-- find package
local found_manager_name = nil
result, found_manager_name = _find_package(manager_name, package_name, opt)
-- match version?
if opt.require_version and opt.require_version:find('.', 1, true) and result then
if not _is_match_version(result.version, opt.require_version) then
result = nil
end
end
return result, found_manager_name, package_name
end
|
0 | repos/xmake/xmake/modules/package | repos/xmake/xmake/modules/package/manager/install_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file install_package.lua
--
-- imports
import("core.project.config")
-- install package
function _install_package(manager_name, package_name, opt)
-- get managers
if manager_name then
dprint("installing %s from %s ..", package_name, manager_name)
return import("package.manager." .. manager_name .. ".install_package", {anonymous = true})(package_name, opt)
end
-- get suitable package managers
local managers = {}
if is_host("windows") then
table.insert(managers, "pacman") -- msys/mingw
elseif is_host("linux") then
table.insert(managers, "apt")
table.insert(managers, "yum")
table.insert(managers, "pacman")
table.insert(managers, "portage")
table.insert(managers, "brew")
table.insert(managers, "zypper")
elseif is_host("macosx") then
table.insert(managers, "vcpkg")
table.insert(managers, "brew")
end
assert(#managers > 0, "no suitable package manager!")
-- install package from the given package managers
local errors = nil
for _, manager in ipairs(managers) do
-- trace
dprint("installing %s from %s ..", package_name, manager)
-- try to install it
local ok = try
{
function ()
import("package.manager." .. manager .. ".install_package", {anonymous = true})(package_name, opt)
return true
end,
catch
{
function (errs)
errors = errs
end
}
}
-- install ok?
if ok then
dprint("install %s ok from %s", package_name, manager)
return
end
end
-- install failed
raise("install %s failed! %s", package_name, errors or "")
end
-- install package using the package manager
--
-- @param name the package name, e.g. zlib 1.12.x (try all), XMAKE::zlib 1.12.x, BREW::zlib, VCPKG::zlib, CONAN::OpenSSL/1.0.2n@conan/stable
-- @param opt the options, e.g. {verbose = true, version = "1.12.x")
--
function main(name, opt)
-- get the copied options
opt = table.copy(opt)
opt.plat = opt.plat or config.get("plat") or os.host()
opt.arch = opt.arch or config.get("arch") or os.arch()
opt.mode = opt.mode or config.mode() or "release"
-- get package manager name
local manager_name, package_name = table.unpack(name:split("::", {plain = true, strict = true}))
if package_name == nil then
package_name = manager_name
manager_name = nil
else
manager_name = manager_name:lower():trim()
end
-- get package name and require version
local require_version = nil
package_name, require_version = table.unpack(package_name:trim():split("%s"))
opt.require_version = require_version or opt.require_version
-- do install package
_install_package(manager_name, package_name, opt)
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/zypper/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, Lingfeng Fu
-- @file find_package.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("core.project.target")
import("lib.detect.find_tool")
import("private.core.base.is_cross")
import("package.manager.pkgconfig.find_package", { alias = "find_package_from_pkgconfig" })
-- find package
function _find_package(rpm, name, opt)
if opt.require_version and opt.require_version ~= "latest" then
name = name .. '-' .. opt.require_version:gsub('%.', '_')
end
local result = nil
local pkgconfig_files = {}
local listinfo = try { function()
return os.iorunv(rpm.program, { "-ql", name })
end }
if listinfo then
for _, line in ipairs(listinfo:split('\n', { plain = true })) do
line = line:trim()
-- get includedirs
local pos = line:find("include/", 1, true)
if pos then
-- we don't need to add includedirs, gcc/clang will use /usr/ as default sysroot
result = result or {}
end
-- get pc files
if line:find("/pkgconfig/", 1, true) and line:endswith(".pc") then
table.insert(pkgconfig_files, line)
end
-- get linkdirs and links
if line:endswith(".a") or line:endswith(".so") then
result = result or {}
result.links = result.links or {}
result.linkdirs = result.linkdirs or {}
result.libfiles = result.libfiles or {}
table.insert(result.linkdirs, path.directory(line))
table.insert(result.links, target.linkname(path.filename(line), { plat = opt.plat }))
table.insert(result.libfiles, path.join(path.directory(line), path.filename(line)))
end
end
end
-- we iterate over each pkgconfig file to extract the required data
local foundpc = false
local pcresult = { includedirs = {}, linkdirs = {}, links = {} }
for _, pkgconfig_file in ipairs(pkgconfig_files) do
local pkgconfig_dir = path.directory(pkgconfig_file)
local pkgconfig_name = path.basename(pkgconfig_file)
local pcinfo = find_package_from_pkgconfig(pkgconfig_name, { configdirs = pkgconfig_dir, linkdirs = linkdirs })
-- the pkgconfig file has been parse successfully
if pcinfo then
for _, includedir in ipairs(pcinfo.includedirs) do
table.insert(pcresult.includedirs, includedir)
end
for _, linkdir in ipairs(pcinfo.linkdirs) do
table.insert(pcresult.linkdirs, linkdir)
end
for _, link in ipairs(pcinfo.links) do
table.insert(pcresult.links, link)
end
-- version should be the same if a pacman package contains multiples .pc
pcresult.version = pcinfo.version
foundpc = true
end
end
if foundpc then
pcresult.includedirs = table.unique(pcresult.includedirs)
pcresult.linkdirs = table.unique(pcresult.linkdirs)
pcresult.links = table.reverse_unique(pcresult.links)
result = pcresult
end
-- meta/alias package? e.g. libboost_headers-devel -> libboost_headers1_82_0-devel
-- @see https://github.com/xmake-io/xmake/issues/1786
if not result then
local statusinfo = try { function()
return os.iorunv(rpm.program, { "-qR", name })
end }
if statusinfo then
for _, line in ipairs(statusinfo:split("\n", { plain = true })) do
-- parse depends, e.g. Depends: libboost1.74-dev
if not line:startswith("rpmlib(") then
local depends = line
result = _find_package(rpm, depends, opt)
if result then
return result
end
end
end
end
end
-- remove repeat
if result then
if result.links then
result.links = table.unique(result.links)
end
if result.linkdirs then
result.linkdirs = table.unique(result.linkdirs)
end
if result.includedirs then
result.includedirs = table.unique(result.includedirs)
end
end
return result
end
-- find package using the rpm package manager
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, version = "1.12.0")
--
function main(name, opt)
opt = opt or {}
if is_cross(opt.plat, opt.arch) then
return
end
local rpm = find_tool("rpm")
if not rpm then
return
end
return _find_package(rpm, name, opt)
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/zypper/install_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, Lingfeng Fu
-- @file install_package.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_tool")
import("privilege.sudo")
-- install package
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, apt = "the package name"}
--
-- @return true or false
--
function main(name, opt)
-- init options
opt = opt or {}
if opt.require_version and opt.require_version ~= "latest" then
name = name .. '-' .. opt.require_version:gsub('%.', '_')
end
-- find apt
local zypper = find_tool("zypper")
if not zypper then
raise("apt not found!")
end
-- init argv
local argv = { "install", "-y", opt.zypper or name }
-- install package directly if the current user is root
if os.isroot() then
os.vrunv(zypper.program, argv)
-- install with administrator permission?
elseif sudo.has() then
-- install it if be confirmed
local description = format("try installing %s with administrator permission", name)
local confirm = utils.confirm({ default = true, description = description })
if confirm then
sudo.vrunv(zypper.program, argv)
end
else
raise("cannot get administrator permission!")
end
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/zypper/search_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki, Lingfeng Fu
-- @file search_package.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_tool")
-- search package using the zypper package manager
--
-- @param name the package name with pattern
--
function main(name)
-- find zypper
local zypper = find_tool("zypper")
if not zypper then
raise("zypper not found!")
end
-- search packages
--
-- | libboost_wave-devel | Development headers for Boost.Wave library | package
--
-- i | libboost_wave-devel | Development headers for Boost.Wave library | package
--
-- i+ | libboost_headers-devel | Development headers for Boost | package
--
local results = {}
local searchdata = os.iorunv(zypper.program, { "search", name })
for _, line in ipairs(searchdata:split("\n", { plain = true })) do
if line:endswith("package") then
local splitinfo = line:split("%s+|%s+", { limit = 4 })
if not line:startswith(" ") then
table.remove(splitinfo, 1)
end
local packagename = splitinfo[1]
local description = splitinfo[2]
table.insert(results, { name = "zypper::" .. packagename, version = version, description = description })
end
end
return results
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/system/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_package.lua
--
-- imports
import("core.language.language")
import("core.platform.platform")
import("private.core.base.is_cross")
import("lib.detect.check_cxsnippets")
-- get package items
function _get_package_items()
local items = {}
for _, apiname in ipairs(table.join(language.apis().values, language.apis().paths)) do
if apiname:startswith("target.") then
local valuename = apiname:split('.add_', {plain = true})[2]
if valuename then
table.insert(items, valuename)
end
end
end
return items
end
-- find package from system and compiler
-- @see https://github.com/xmake-io/xmake/issues/4596
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, package = <package instance>, includes = "", sourcekind = "[cc|cxx|mm|mxx]",
-- funcs = {"sigsetjmp", "sigsetjmp((void*)0, 0)"},
-- configs = {defines = "", links = "", cflags = ""}}
--
function main(name, opt)
opt = opt or {}
if is_cross(opt.plat, opt.arch) then
return
end
local configs = opt.configs or {}
local items = _get_package_items()
local snippet_configs = {}
for _, name in ipairs(items) do
snippet_configs[name] = configs[name]
end
snippet_configs.links = snippet_configs.links or name
local snippet_opt = {
verbose = opt.verbose,
target = opt.package,
funcs = opt.funcs,
sourcekind = opt.sourcekind,
includes = opt.includes,
configs = snippet_configs}
local snippetname = "find_package/" .. name
local snippets = opt.snippets or {[snippetname] = ""}
if check_cxsnippets(snippets, snippet_opt) then
local result = snippet_configs
if not table.empty(result) then
return result
end
end
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/cargo/configurations.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file configurations.lua
--
-- get configurations
function main()
return
{
features = {description = "Set the features of dependency."},
default_features = {description = "Enable or disable any defaults provided by the dependency.", default = true},
std = {description = "Enable or disable std module."},
main = {description = "Enable or disable main entry function."},
cargo_toml = {description = "Set Cargo.toml file path"}
}
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/cargo/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_package.lua
--
-- imports
import("core.base.option")
import("core.base.semver")
import("core.base.hashset")
import("core.base.json")
import("core.project.config")
import("core.project.target")
import("lib.detect.find_tool")
import("lib.detect.find_file")
import("private.tools.rust.check_target")
-- get cargo registry directory
function _get_cargo_registrydir()
return path.join(is_host("windows") and os.getenv("USERPROFILE") or "~", ".cargo", "registry")
end
-- get the Cargo.toml of package
-- e.g. ~/.cargo/registry/src/github.com-1ecc6299db9ec823/obj-rs-0.6.4/Cargo.toml
function _get_package_toml(name)
local registrydir = _get_cargo_registrydir()
local registrysrc = path.join(registrydir, "src")
if os.isdir(registrysrc) then
local files = os.files(path.join(registrysrc, "*", name .. "-*", "Cargo.toml"))
for _, file in ipairs(files) do
local dir = path.directory(file)
local basename = path.filename(dir)
if basename:startswith(name) then
basename = basename:sub(#name + 1)
if basename:match("^%-[%d%.]+$") then
return file
end
end
end
end
end
-- get rust library name
--
-- e.g.
-- sdl2 -> libsdl2
-- future-util -> libfuture_util
function _get_libname(name)
-- we attempt to parse libname from Cargo.toml/[lib]
-- @see https://github.com/xmake-io/xmake/issues/3452
-- e.g. obj-rs -> libobj
local tomlfile = _get_package_toml(name)
if tomlfile then
local libinfo = false
local tomldata = io.readfile(tomlfile)
for _, line in ipairs(tomldata:split("\n")) do
if line:find("[lib]", 1, true) then
libinfo = true
elseif line:find("[", 1, true) then
libinfo = false
elseif libinfo then
local name = line:match("name%s+=%s+\"(.+)\"")
if name then
return "lib" .. name
end
end
end
end
return "lib" .. name:gsub("-", "_")
end
-- get the name set of libraries
function _get_names_of_libraries(name, opt)
local configs = opt.configs or {}
local names = hashset.new()
local metadata_file = path.join(opt.installdir, "metadata.txt")
if configs.cargo_toml and os.isfile(metadata_file) then
local fileinfo = io.load(metadata_file)
local metadata = json.decode(fileinfo.metadata)
local metadata_without_deps = json.decode(fileinfo.metadata_without_deps)
-- FIXME: should consider the case of multiple packages in a workspace!
local direct_deps = metadata_without_deps.packages[1].dependencies
-- get the intersection of the direct dependencies and all dependencies for the target platform
for _, dep in ipairs(direct_deps) do
local dep_metadata
for _, pkg in ipairs(metadata.packages) do
if pkg.name == dep.name then
dep_metadata = pkg
break
end
end
if dep_metadata then
names:insert(_get_libname(dep.name))
end
end
else
names:insert(_get_libname(name))
end
return names
end
-- find package using the cargo package manager
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, require_version = "1.12.x")
--
function main(name, opt)
-- get configs
opt = opt or {}
local configs = opt.configs or {}
-- get names of libraries
local names = _get_names_of_libraries(name, opt)
assert(not names:empty())
local frameworkdirs
local frameworks
local librarydir = path.join(opt.installdir, "lib")
local librarydir_host = path.join(opt.installdir, "lib", "host")
local libfiles = os.files(path.join(librarydir, "*.rlib"))
-- @see https://github.com/xmake-io/xmake/issues/4228
local libfiles_native
local plat = opt.plat
if plat == "macosx" then
libfiles_native = os.files(path.join(librarydir, "*.dylib"))
elseif plat == "windows" or plat == "mingw" then
libfiles_native = os.files(path.join(librarydir, "*.lib"))
else
libfiles_native = os.files(path.join(librarydir, "*.so"))
end
-- @see https://github.com/xmake-io/xmake/issues/5156
local libfiles_native_host
if is_host("macosx") then
libfiles_native_host = os.files(path.join(librarydir_host, "*.dylib"))
elseif is_host("windows") then
libfiles_native_host = os.files(path.join(librarydir_host, "*.lib|*.dll.lib"))
table.join2(libfiles_native_host, os.files(path.join(librarydir_host, "*.dll")))
else
libfiles_native_host = os.files(path.join(librarydir_host, "*.so"))
end
for _, libraryfile in ipairs(table.join(libfiles or {}, libfiles_native or {}, libfiles_native_host)) do
local filename = path.filename(libraryfile)
local libraryname = filename:split('-', {plain = true})[1]
-- https://github.com/xmake-io/xmake/issues/5156#issuecomment-2143509207
if not libraryname:startswith("lib") then
libraryname = "lib" .. libraryname
end
if names:has(libraryname) then
frameworkdirs = frameworkdirs or {}
frameworks = frameworks or {}
table.insert(frameworkdirs, path.directory(libraryfile))
table.insert(frameworks, libraryfile)
end
end
local result
if frameworks and frameworkdirs then
result = result or {}
result.libfiles = libfiles
result.frameworkdirs = frameworkdirs and table.unique(frameworkdirs) or nil
result.frameworks = frameworks
result.version = opt.require_version
end
return result
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/cargo/install_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file install_package.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("lib.detect.find_tool")
import("private.tools.rust.check_target")
-- translate local path in dependencies
-- @see https://github.com/xmake-io/xmake/issues/4222
-- https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html
--
-- e.g.
-- [dependencies]
-- hello_utils = { path = "./hello_utils", version = "0.1.0" }
--
-- [dependencies.my_lib]
-- path = "../my_lib"
function _translate_local_path_in_deps(cargotoml, rootdir)
local content = io.readfile(cargotoml)
content = content:gsub("path%s+=%s+\"(.-)\"", function (localpath)
if not path.is_absolute(localpath) then
localpath = path.absolute(localpath, rootdir)
end
localpath = localpath:gsub("\\", "/")
return "path = \"" .. localpath .. "\""
end)
io.writefile(cargotoml, content)
end
-- install package
--
-- e.g.
-- add_requires("cargo::base64")
-- add_requires("cargo::base64 0.13.0")
-- add_requires("cargo::flate2 1.0.17", {configs = {features = {"zlib"}, ["default-features"] = false}})
-- add_requires("cargo::xxx", {configs = {cargo_toml = path.join(os.projectdir(), "Cargo.toml")}})
--
-- @param name the package name, e.g. cargo::base64
-- @param opt the options, e.g. { verbose = true, mode = "release", plat = , arch = , require_version = "x.x.x"}
--
-- @return true or false
--
function main(name, opt)
-- find cargo
local cargo = find_tool("cargo")
if not cargo then
raise("cargo not found!")
end
-- get required version
opt = opt or {}
local configs = opt.configs or {}
local require_version = opt.require_version
if not require_version or require_version == "latest" then
require_version = "*"
end
-- get target
-- e.g. x86_64-pc-windows-msvc, aarch64-unknown-none
-- @see https://github.com/xmake-io/xmake/issues/4049
local target = check_target(opt.arch, true) and opt.arch or nil
-- generate Cargo.toml
local sourcedir = path.join(opt.cachedir, "source")
local cargotoml = path.join(sourcedir, "Cargo.toml")
os.tryrm(sourcedir)
if configs.cargo_toml then
assert(os.isfile(configs.cargo_toml), "%s not found!", configs.cargo_toml)
os.cp(configs.cargo_toml, cargotoml)
_translate_local_path_in_deps(cargotoml, path.directory(configs.cargo_toml))
-- we need add `[workspace]` to prevent cargo from searching up for a parent.
-- https://github.com/rust-lang/cargo/issues/10534#issuecomment-1087631050
local tomlfile = io.open(cargotoml, "a")
tomlfile:print("")
tomlfile:print("[lib]")
tomlfile:print("crate-type = [\"staticlib\"]")
tomlfile:print("")
tomlfile:print("[workspace]")
tomlfile:print("")
tomlfile:close()
else
local tomlfile = io.open(cargotoml, "w")
tomlfile:print("[lib]")
tomlfile:print("crate-type = [\"staticlib\"]")
tomlfile:print("")
tomlfile:print("[package]")
tomlfile:print("name = \"cargodeps\"")
tomlfile:print("version = \"0.1.0\"")
tomlfile:print("edition = \"2018\"")
tomlfile:print("")
tomlfile:print("[dependencies]")
local features = configs.features
if features then
features = table.wrap(features)
tomlfile:print("%s = {version = \"%s\", features = [\"%s\"], default-features = %s}", name, require_version, table.concat(features, "\", \""), configs.default_features)
else
tomlfile:print("%s = \"%s\"", name, require_version)
end
tomlfile:print("")
tomlfile:close()
end
-- generate .cargo/config.toml
local configtoml = path.join(sourcedir, ".cargo", "config.toml")
if target then
io.writefile(configtoml, format([[
[build]
target = "%s"
]], target))
end
-- generate main.rs
local file = io.open(path.join(sourcedir, "src", "lib.rs"), "w")
if configs.main == false then
file:print("#![no_main]")
end
if configs.std == false then
file:print("#![no_std]")
end
if configs.main == false then
file:print([[
use core::panic::PanicInfo;
#[panic_handler]
fn panic(_panic: &PanicInfo<'_>) -> ! {
loop {}
}]])
else
file:print([[
fn main() {
println!("Hello, world!");
}]])
end
file:close()
-- do build
local argv = {"build"}
if opt.mode ~= "debug" then
table.insert(argv, "--release")
end
if option.get("verbose") then
table.insert(argv, option.get("diagnosis") and "-vv" or "-v")
end
os.vrunv(cargo.program, argv, {curdir = sourcedir})
-- do install
local installdir = opt.installdir
local librarydir = path.join(installdir, "lib")
local librarydir_host = path.join(installdir, "lib", "host")
os.tryrm(librarydir)
if target then
os.vcp(path.join(sourcedir, "target", target, opt.mode == "debug" and "debug" or "release", "deps"), librarydir)
-- @see https://github.com/xmake-io/xmake/issues/5156#issuecomment-2142566862
os.vcp(path.join(sourcedir, "target", opt.mode == "debug" and "debug" or "release", "deps"), librarydir_host)
else
os.vcp(path.join(sourcedir, "target", opt.mode == "debug" and "debug" or "release", "deps"), librarydir)
end
-- install metadata
argv = {"metadata", "--format-version", "1", "--manifest-path", cargotoml, "--color", "never"}
if target then
table.insert(argv, "--filter-platform")
table.insert(argv, target)
end
local metadata = os.iorunv(cargo.program, argv, {curdir = sourcedir})
-- fetch the direct dependencies list regradless of the target platform
table.insert(argv, "--no-deps")
local metadata_without_deps = os.iorunv(cargo.program, argv, {curdir = sourcedir})
io.save(path.join(installdir, "metadata.txt"), {metadata = metadata, metadata_without_deps = metadata_without_deps})
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/yum/install_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file install_package.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_tool")
import("privilege.sudo")
-- install package
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, yum = "the package name"}
--
-- @return true or false
--
function main(name, opt)
-- init options
opt = opt or {}
-- find yum
local yum = find_tool("yum")
if not yum then
raise("yum not found!")
end
-- init argv
local argv = {"install", "-y", opt.yum or name}
if opt.verbose or option.get("verbose") then
table.insert(argv, "--verbose")
end
-- install package directly if the current user is root
if os.isroot() then
os.vrunv(yum.program, argv)
-- install with administrator permission?
elseif sudo.has() then
-- install it if be confirmed
local description = format("try installing %s with administrator permission", name)
local confirm = utils.confirm({default = true, description = description})
if confirm then
sudo.vrunv(yum.program, argv)
end
else
raise("cannot get administrator permission!")
end
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/apt/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_package.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("core.project.target")
import("lib.detect.find_tool")
import("private.core.base.is_cross")
import("package.manager.pkgconfig.find_package", {alias = "find_package_from_pkgconfig"})
-- find package
function _find_package(dpkg, name, opt)
local result = nil
local pkgconfig_files = {}
local listinfo = try {function () return os.iorunv(dpkg.program, {"--listfiles", name}) end}
if listinfo then
for _, line in ipairs(listinfo:split('\n', {plain = true})) do
line = line:trim()
-- get includedirs
local pos = line:find("include/", 1, true)
if pos then
-- we don't need to add includedirs, gcc/clang will use /usr/ as default sysroot
result = result or {}
end
-- get pc files
if line:find("/pkgconfig/", 1, true) and line:endswith(".pc") then
table.insert(pkgconfig_files, line)
end
-- get linkdirs and links
if line:endswith(".a") or line:endswith(".so") then
result = result or {}
result.links = result.links or {}
result.linkdirs = result.linkdirs or {}
result.libfiles = result.libfiles or {}
if line:endswith(".a") then
result.static = true
else
result.shared = true
end
table.insert(result.linkdirs, path.directory(line))
table.insert(result.links, target.linkname(path.filename(line), {plat = opt.plat}))
table.insert(result.libfiles, path.join(path.directory(line), path.filename(line)))
end
end
end
-- we iterate over each pkgconfig file to extract the required data
local foundpc = false
local pcresult = {includedirs = {}, linkdirs = {}, links = {}, libfiles = {}}
for _, pkgconfig_file in ipairs(pkgconfig_files) do
local pkgconfig_dir = path.directory(pkgconfig_file)
local pkgconfig_name = path.basename(pkgconfig_file)
local pcinfo = find_package_from_pkgconfig(pkgconfig_name, {configdirs = pkgconfig_dir, linkdirs = linkdirs})
-- the pkgconfig file has been parse successfully
if pcinfo then
for _, includedir in ipairs(pcinfo.includedirs) do
table.insert(pcresult.includedirs, includedir)
end
for _, linkdir in ipairs(pcinfo.linkdirs) do
table.insert(pcresult.linkdirs, linkdir)
end
for _, link in ipairs(pcinfo.links) do
table.insert(pcresult.links, link)
end
if not result or not result.libfiles then
for _, libfile in ipairs(pcinfo.libfiles) do
table.insert(pcresult.libfiles, libfile)
end
pcresult.static = pcinfo.static
pcresult.shared = pcinfo.shared
end
-- version should be the same if a pacman package contains multiples .pc
pcresult.version = pcinfo.version
foundpc = true
end
end
if foundpc == true then
pcresult.includedirs = table.unique(pcresult.includedirs)
pcresult.linkdirs = table.unique(pcresult.linkdirs)
pcresult.libfiles = table.unique(pcresult.libfiles)
pcresult.links = table.reverse_unique(pcresult.links)
result = pcresult
end
-- meta/alias package? e.g. libboost-dev -> libboost1.74-dev
-- @see https://github.com/xmake-io/xmake/issues/1786
if not result then
local statusinfo = try {function () return os.iorunv(dpkg.program, {"--status", name}) end}
if statusinfo then
for _, line in ipairs(statusinfo:split("\n", {plain = true})) do
-- parse depends, e.g. Depends: libboost1.74-dev, libomp-14-dev (>= 14~)
if line:startswith("Depends:") then
local depends = line:sub(9):gsub("%(.-%)", ""):split("%s+")
if #depends == 1 then
return _find_package(dpkg, depends[1], opt)
end
break
end
end
end
end
if result then
if result.links then
result.links = table.unique(result.links)
if #result.links == 0 then
result.links = nil
end
end
if result.linkdirs then
result.linkdirs = table.unique(result.linkdirs)
if #result.linkdirs == 0 then
result.linkdirs = nil
end
end
if result.includedirs then
result.includedirs = table.unique(result.includedirs)
if #result.includedirs == 0 then
result.includedirs = nil
end
end
if result.libfiles then
result.libfiles = table.unique(result.libfiles)
if #result.libfiles == 0 then
result.libfiles = nil
end
end
end
return result
end
-- find package using the dpkg package manager
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, version = "1.12.0")
--
function main(name, opt)
opt = opt or {}
if is_cross(opt.plat, opt.arch) then
return
end
local dpkg = find_tool("dpkg")
if not dpkg then
return
end
return _find_package(dpkg, name, opt)
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/apt/install_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file install_package.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_tool")
import("privilege.sudo")
-- install package
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, apt = "the package name"}
--
-- @return true or false
--
function main(name, opt)
-- init options
opt = opt or {}
-- find apt
local apt = find_tool("apt")
if not apt then
raise("apt not found!")
end
-- init argv
local argv = {"install", "-y", opt.apt or name}
-- install package directly if the current user is root
if os.isroot() then
os.vrunv(apt.program, argv)
-- install with administrator permission?
elseif sudo.has() then
-- install it if be confirmed
local description = format("try installing %s with administrator permission", name)
local confirm = utils.confirm({default = true, description = description})
if confirm then
sudo.vrunv(apt.program, argv)
end
else
raise("cannot get administrator permission!")
end
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/apt/search_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file search_package.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_tool")
-- search package using the apt package manager
--
-- @param name the package name with pattern
--
function main(name)
-- find apt
local apt = find_tool("apt")
if not apt then
raise("apt not found!")
end
-- search packages
--
-- libzopfli1/groovy 1.0.3-1build1 amd64
-- zlib (gzip, deflate) compatible compressor - shared library
--
-- lua-zlib/groovy 1.2-2 amd64
-- zlib library for the Lua language
--
local results = {}
local searchdata = os.iorunv(apt.program, {"search", name})
local packagename
for _, line in ipairs(searchdata:split("\n", {plain = true})) do
if line:find("/", 1, true) then
local splitinfo = line:split("%s+", {limit = 3})
packagename = splitinfo[1]
if packagename then
packagename = packagename:split('/')[1]
end
elseif line:trim() ~= "" and packagename then
local description = line:trim()
if packagename:find(name, 1, true) then
table.insert(results, {name = "apt::" .. packagename, version = version, description = description})
end
packagename = nil
end
end
return results
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/pkgconfig/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_package.lua
--
-- imports
import("lib.detect.pkgconfig")
import("lib.detect.find_library")
import("private.core.base.is_cross")
import("package.manager.system.find_package", {alias = "find_package_from_system"})
-- find package from the pkg-config package manager
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, version = "1.12.x")
--
function main(name, opt)
opt = opt or {}
if is_cross(opt.plat, opt.arch) then
return
end
-- get library info
local libinfo = pkgconfig.libinfo(name, opt)
if not libinfo and name:startswith("lib") then
-- libxxx? attempt to find xxx without `lib` prefix
libinfo = pkgconfig.libinfo(name:sub(4), opt)
end
if not libinfo then
return
end
-- no linkdirs in pkg-config? attempt to find it from system directories
if libinfo.links and not libinfo.linkdirs then
local libinfo_sys = find_package_from_system(name, table.join(opt, {links = libinfo.links}))
if libinfo_sys then
libinfo.linkdirs = libinfo_sys.linkdirs
end
end
-- get result, libinfo may be empty body, but it's also valid
-- @see https://github.com/xmake-io/xmake/issues/3777#issuecomment-1568453316
local result = nil
if libinfo then
result = result or {}
result.includedirs = libinfo.includedirs
result.linkdirs = libinfo.linkdirs
result.links = libinfo.links
result.defines = libinfo.defines
result.cxflags = libinfo.cxflags
result.ldflags = libinfo.ldflags
result.shflags = libinfo.shflags
result.version = libinfo.version
end
-- find libfiles
if result and libinfo then
local libdirs = libinfo.linkdirs
if not libdirs then
local pcfile = pkgconfig.pcfile(name, opt)
if not pcfile and name:startswith("lib") then
pcfile = pkgconfig.pcfile(name:sub(4), opt)
end
if pcfile then
libdirs = path.directory(pcfile)
if path.filename(libdirs) == "pkgconfig" then
libdirs = path.directory(libdirs)
end
end
end
if libdirs and libinfo.links then
for _, link in ipairs(libinfo.links) do
local info = find_library(link, libdirs, {plat = opt.plat})
if info and info.linkdir and info.filename then
result.libfiles = result.libfiles or {}
table.insert(result.libfiles, path.join(info.linkdir, info.filename))
if info.kind then
result[info.kind] = true
end
end
end
end
if result.libfiles then
result.libfiles = table.unique(result.libfiles)
end
end
return result
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/pacman/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_package.lua
--
-- imports
import("core.base.option")
import("core.project.target")
import("lib.detect.find_tool")
import("private.core.base.is_cross")
import("package.manager.pkgconfig.find_package", {alias = "find_package_from_pkgconfig"})
-- find package from list of file inside pacman package
function _find_package_from_list(list, name, pacman, opt)
-- mingw + pacman = cygpath available
local cygpath = nil
local pathtomsys = nil
local msystem = nil
if is_subhost("msys") and opt.plat == "mingw" then
cygpath = find_tool("cygpath")
if not cygpath then
return
end
pathtomsys = os.iorunv(cygpath.program, {"--windows", "/"})
pathtomsys = pathtomsys:trim()
msystem = os.getenv("MSYSTEM")
if msystem then
msystem = msystem:lower()
end
end
-- iterate over each file path inside the pacman package
local result = {}
for _, line in ipairs(list:split('\n', {plain = true})) do -- on msys cygpath should be used to convert local path to windows path
line = line:trim():split('%s+')[2]
if line:find("/include/", 1, true) and (line:endswith(".h") or line:endswith(".hpp")) then
if not line:startswith("/usr/include/") then
result.includedirs = result.includedirs or {}
local hpath = line
if is_subhost("msys") and opt.plat == "mingw" then
hpath = path.join(pathtomsys, line)
local basehpath = path.join(pathtomsys, msystem .. "/include")
table.insert(result.includedirs, basehpath)
end
table.insert(result.includedirs, path.directory(hpath))
end
-- remove lib and .a, .dll.a and .so to have the links
elseif line:endswith(".dll.a") then -- only for mingw
local apath = path.join(pathtomsys, line)
apath = apath:trim()
result.linkdirs = result.linkdirs or {}
result.links = result.links or {}
table.insert(result.linkdirs, path.directory(apath))
table.insert(result.links, target.linkname(path.filename(apath), {plat = opt.plat}))
elseif line:endswith(".so") then
result.linkdirs = result.linkdirs or {}
result.links = result.links or {}
table.insert(result.linkdirs, path.directory(line))
table.insert(result.links, target.linkname(path.filename(line), {plat = opt.plat}))
elseif line:endswith(".a") then
result.linkdirs = result.linkdirs or {}
result.links = result.links or {}
local apath = line
if is_subhost("msys") and opt.plat == "mingw" then
apath = path.join(pathtomsys, line)
apath = apath:trim()
end
table.insert(result.linkdirs, path.directory(apath))
table.insert(result.links, target.linkname(path.filename(apath), {plat = opt.plat}))
end
end
if result.includedirs then
result.includedirs = table.unique(result.includedirs)
end
if result.linkdirs then
result.linkdirs = table.unique(result.linkdirs)
end
if result.links then
result.links = table.reverse_unique(result.links)
end
-- use pacman package version as version
local version = try { function() return os.iorunv(pacman.program, {"-Q", name}) end }
if version then
version = version:trim():split('%s+')[2]
-- we need strip "1:" prefix, @see https://github.com/xmake-io/xmake/issues/2020
-- e.g. vulkan-headers 1:1.3.204-1
if version:startswith("1:") then
version = version:split(':')[2]
end
result.version = version:split('-')[1]
else
result = nil
end
return result
end
-- find libfiles from list of file inside pacman package
function _find_libfiles_from_list(list, name, pacman, opt)
-- mingw + pacman = cygpath available
local cygpath = nil
local pathtomsys = nil
if is_subhost("msys") and opt.plat == "mingw" then
cygpath = find_tool("cygpath")
if not cygpath then
return
end
pathtomsys = os.iorunv(cygpath.program, {"--windows", "/"})
pathtomsys = pathtomsys:trim()
end
-- iterate over each file path inside the pacman package
local libfiles
for _, line in ipairs(list:split('\n', {plain = true})) do -- on msys cygpath should be used to convert local path to windows path
line = line:trim():split('%s+')[2]
if line:endswith(".dll.a") then -- only for mingw
local apath = path.join(pathtomsys, line)
apath = apath:trim()
libfiles = libfiles or {}
table.insert(libfiles, apath)
elseif line:endswith(".so") then
libfiles = libfiles or {}
table.insert(libfiles, line)
elseif line:endswith(".a") then
local apath = line
if is_subhost("msys") and opt.plat == "mingw" then
apath = path.join(pathtomsys, line)
apath = apath:trim()
end
libfiles = libfiles or {}
table.insert(libfiles, apath)
end
end
return libfiles
end
-- find package from the system directories
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, version = "1.12.x")
--
function main(name, opt)
opt = opt or {}
if is_cross(opt.plat, opt.arch) then
return
end
-- find pacman
local pacman = find_tool("pacman")
if not pacman then
return
end
-- for msys2/mingw? mingw-w64-[i686|x86_64]-xxx
if is_subhost("msys") and opt.plat == "mingw" then
-- try to get the package prefix from the environment first
-- https://www.msys2.org/docs/package-naming/
local prefix = "mingw-w64-"
local arch = (opt.arch == "x86_64" and "x86_64-" or "i686-")
local msystem = os.getenv("MSYSTEM")
if msystem and not msystem:startswith("MINGW") then
local i, j = msystem:find("%D+")
name = prefix .. msystem:sub(i, j):lower() .. "-" .. arch .. name
else
name = prefix .. arch .. name
end
end
-- get package files list
list = name and try { function() return os.iorunv(pacman.program, {"-Q", "-l", name}) end }
if not list then
return
end
-- parse package files list
local linkdirs = {}
local pkgconfig_files = {}
for _, line in ipairs(list:split('\n', {plain = true})) do
line = line:trim():split('%s+')[2]
if line:find("/pkgconfig/", 1, true) and line:endswith(".pc") then
table.insert(pkgconfig_files, line)
end
if line:endswith(".so") or line:endswith(".a") or line:endswith(".lib") then
table.insert(linkdirs, path.directory(line))
end
end
linkdirs = table.unique(linkdirs)
-- we iterate over each pkgconfig file to extract the required data
local result
for _, pkgconfig_file in ipairs(pkgconfig_files) do
local pkgconfig_dir = path.directory(pkgconfig_file)
local pkgconfig_name = path.basename(pkgconfig_file)
local pcresult = find_package_from_pkgconfig(pkgconfig_name, {configdirs = pkgconfig_dir, linkdirs = linkdirs})
if pcresult then
result = result or {}
for _, includedir in ipairs(pcresult.includedirs) do
result.includedirs = result.includedirs or {}
table.insert(result.includedirs, includedir)
end
for _, linkdir in ipairs(pcresult.linkdirs) do
result.linkdirs = result.linkdirs or {}
table.insert(result.linkdirs, linkdir)
end
for _, link in ipairs(pcresult.links) do
result.links = result.links or {}
table.insert(result.links, link)
end
for _, libfile in ipairs(pcresult.libfiles) do
result.libfiles = result.libfiles or {}
table.insert(result.libfiles, libfile)
end
-- version should be the same if a pacman package contains multiples .pc
result.version = pcresult.version
result.shared = pcresult.shared
result.static = pcresult.static
end
end
if result then
if result.includedirs then
result.includedirs = table.unique(result.includedirs)
end
if result.linkdirs then
result.linkdirs = table.unique(result.linkdirs)
end
if result.libfiles then
result.libfiles = table.unique(result.libfiles)
end
if result.links then
result.links = table.reverse_unique(result.links)
end
else
-- if there is no .pc, we parse the package content to obtain the data we want
result = _find_package_from_list(list, name, pacman, opt)
end
if result then
-- we give priority to libfiles in the list
local libfiles = _find_libfiles_from_list(list, name, pacman, opt)
if libfiles then
result.shared = nil
result.static = nil
result.libfiles = libfiles
for _, libfile in ipairs(libfiles) do
if libfile:endswith(".so") then
result.shared = true
elseif libfile:endswith(".a") then
result.static = true
end
end
end
end
return result
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/pacman/install_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file install_package.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_tool")
import("privilege.sudo")
-- install package
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, pacman = "the package name"}
--
-- @return true or false
--
function main(name, opt)
-- init options
opt = opt or {}
-- find pacman
local pacman = find_tool("pacman")
if not pacman then
raise("pacman not found!")
end
-- for msys2/mingw? mingw-w64-[i686|x86_64]-xxx
if is_subhost("msys") and opt.plat == "mingw" then
-- try to get the package prefix from the environment first
-- https://www.msys2.org/docs/package-naming/
local prefix = "mingw-w64-"
local arch = (opt.arch == "x86_64" and "x86_64-" or "i686-")
local msystem = os.getenv("MSYSTEM")
if msystem and not msystem:startswith("MINGW") then
local i, j = msystem:find("%D+")
name = prefix .. msystem:sub(i, j):lower() .. "-" .. arch .. name
else
name = prefix .. arch .. name
end
end
-- init argv
local argv = {"-Sy", "--noconfirm", "--needed", "--disable-download-timeout", opt.pacman or name}
if opt.verbose or option.get("verbose") then
table.insert(argv, "--verbose")
end
-- install package directly if the current user is root
if is_host("windows") or os.isroot() then
os.vrunv(pacman.program, argv)
-- install with administrator permission?
elseif sudo.has() then
-- install it if be confirmed
local description = format("try installing %s with administrator permission", name)
local confirm = utils.confirm({default = true, description = description})
if confirm then
sudo.vrunv(pacman.program, argv)
end
else
raise("cannot get administrator permission!")
end
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/nimble/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_package.lua
--
-- imports
import("core.base.option")
import("core.base.semver")
import("core.project.config")
import("core.project.target")
import("lib.detect.find_tool")
import("lib.detect.find_file")
-- parse package name and version
--
-- e.g.
-- zip [0.3.1]
-- zip [(version: 0.3.1, checksum: 747aab3c43ecb7b50671cdd0ec3b2edc2c83494c)]
--
function _parse_packageinfo(line)
local splitinfo = line:split("%s+", {limit = 2})
local package_name = splitinfo[1]
local version_str = splitinfo[2]
if version_str then
local version = semver.match(version_str)
if version then
package_version = version:rawstr()
end
end
return package_name, package_version
end
-- find package using the nimble package manager
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, require_version = "1.12.x")
--
function main(name, opt)
-- find nimble
local nimble = find_tool("nimble")
if not nimble then
raise("nimble not found!")
end
-- find it from all installed package list
local result
local list = os.iorunv(nimble.program, {"list", "-i"})
for _, line in ipairs(list:split("\n", {plain = true})) do
local package_name, package_version = _parse_packageinfo(line)
if package_name == name then
if opt.require_version then
if package_version and (opt.require_version == "latest" or semver.satisfies(package_version, opt.require_version)) then
result = {version = package_version}
break
end
else
result = {}
break
end
end
end
-- @note we don't need return links and includedirs information,
-- because it's nim source code package and nim will find them automatically
return result
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/nimble/install_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file install_package.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("lib.detect.find_tool")
-- install package
--
-- e.g.
-- add_requires("nimble::zip")
-- add_requires("nimble::zip >0.3")
-- add_requires("nimble::zip 0.3.1")
--
-- @param name the package name, e.g. nimble::zip
-- @param opt the options, e.g. { verbose = true, mode = "release", plat = , arch = , require_version = "x.x.x"}
--
-- @return true or false
--
function main(name, opt)
-- find nimble
local nimble = find_tool("nimble")
if not nimble then
raise("nimble not found!")
end
-- install the given package
local argv = {"install", "-y"}
if option.get("verbose") then
table.insert(argv, "--verbose")
end
local require_str = name
if opt.require_version and opt.require_version ~= "latest" and opt.require_version ~= "master" then
name = name .. "@"
name = name .. opt.require_version
end
table.insert(argv, name)
os.vrunv(nimble.program, argv)
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/conda/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_package.lua
--
-- imports
import("core.base.json")
import("core.base.option")
import("core.project.config")
import("core.project.target")
import("lib.detect.find_tool")
-- get conda prefix directory
function _conda_prefixdir(conda)
local prefixdir = _g.prefixdir
if prefixdir == nil then
prefixdir = os.getenv("CONDA_PREFIX")
if not prefixdir then
local info = try {function () return os.iorunv(conda.program, {"info"}) end}
if info then
for _, line in ipairs(info:split('\n', {plain = true})) do
if line:find("base environment") then
prefixdir = line:match("ase environment : (.-) %(writable%)")
if prefixdir then
prefixdir = prefixdir:trim()
end
break
end
end
end
end
_g.prefixdir = prefixdir
end
return prefixdir
end
-- find package using the conda package manager
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, require_version = "1.12.0")
--
function main(name, opt)
-- check
opt = opt or {}
if not is_host(opt.plat) or os.arch() ~= opt.arch then
return
end
-- find conda
local conda = find_tool("conda")
if not conda then
return
end
-- find package
local version, build
local listinfo = try {function () return os.iorunv(conda.program, {"list", name}) end}
if listinfo then
for _, line in ipairs(listinfo:split('\n', {plain = true})) do
if line:startswith(name) then
version, build = listinfo:match(name .. "%s-([%w%.%d%-%+]+)%s-([%w%d_]+)")
if version and build then
break
end
end
end
end
if not version or not build then
return
end
if opt.require_version and opt.require_version:find('.', 1, true) and opt.require_version ~= version then
return
end
-- get meta info of package
-- e.g. ~/miniconda2/conda-meta/libpng-1.6.37-ha441bb4_0.json
local prefixdir = _conda_prefixdir(conda)
if not prefixdir then
return
end
local metafile = path.join(prefixdir, "conda-meta", name .. "-" .. version .. "-" .. build .. ".json")
if not os.isfile(metafile) then
return
end
local metainfo = json.loadfile(metafile)
if not metainfo or not metainfo.extracted_package_dir then
return
end
-- save includedirs, linkdirs and links
local result = nil
local packagedir = metainfo.extracted_package_dir
for _, line in ipairs(metainfo.files) do
line = line:trim()
-- get includedirs
local pos = line:find("include/", 1, true)
if pos then
result = result or {}
result.includedirs = result.includedirs or {}
table.insert(result.includedirs, path.join(packagedir, line:sub(1, pos + 7)))
end
-- get linkdirs and links
if line:endswith(".lib") or line:endswith(".a") or line:endswith(".so") or line:endswith(".dylib") then
result = result or {}
result.links = result.links or {}
result.linkdirs = result.linkdirs or {}
result.libfiles = result.libfiles or {}
table.insert(result.linkdirs, path.join(packagedir, path.directory(line)))
table.insert(result.links, target.linkname(path.filename(line), {plat = opt.plat}))
table.insert(result.libfiles, path.join(packagedir, path.directory(line), path.filename(line)))
end
-- add shared library directory (/bin/) to linkdirs for running with PATH on windows
if opt.plat == "windows" and line:endswith(".dll") then
result = result or {}
result.linkdirs = result.linkdirs or {}
result.libfiles = result.libfiles or {}
table.insert(result.linkdirs, path.join(packagedir, path.directory(line)))
table.insert(result.libfiles, path.join(packagedir, path.directory(line), path.filename(line)))
end
end
-- save version
if result then
result.version = metainfo.version or version
end
-- remove repeat
if result then
if result.links then
result.links = table.unique(result.links)
end
if result.linkdirs then
result.linkdirs = table.unique(result.linkdirs)
end
if result.includedirs then
result.includedirs = table.unique(result.includedirs)
end
end
return result
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/conda/install_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file install_package.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("lib.detect.find_tool")
-- install package
--
-- @param name the package name, e.g. conda::libpng 1.6.37
-- @param opt the options, e.g. { verbose = true }
--
-- @return true or false
--
function main(name, opt)
-- check
opt = opt or {}
assert(is_host(opt.plat) and os.arch() == opt.arch, "conda cannot install %s for %s/%s", name, opt.plat, opt.arch)
-- find conda
local conda = find_tool("conda")
if not conda then
raise("conda not found!")
end
-- install package
local argv = {"install", "-y"}
if option.get("verbose") then
table.insert(argv, "-v")
end
if opt.require_version and opt.require_version:find('.', 1, true) then
name = name .. "=" .. opt.require_version
end
table.insert(argv, name)
os.vrunv(conda.program, argv)
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/conda/search_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file search_package.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_tool")
-- search package using the conda package manager
--
-- @param name the package name with pattern
--
function main(name)
-- find conda
local conda = find_tool("conda")
if not conda then
raise("conda not found!")
end
-- search packages
local results = {}
local searchdata = os.iorunv(conda.program, {"search", "-q", name})
for _, line in ipairs(searchdata:split("\n", {plain = true})) do
local splitinfo = line:split("%s+", {limit = 3})
local packagename = splitinfo[1]
local version = splitinfo[2]
local description = splitinfo[3]
if packagename:find(name, 1, true) then
table.insert(results, {name = "conda::" .. packagename, version = version, description = description})
end
end
return results
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/go/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_package.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("core.package.package")
-- get the package install directory
function _go_get_installdir(name, opt)
local name = "go_" .. name:lower()
local dir = path.join(package.installdir(), name:sub(1, 1):lower(), name)
if opt.require_version then
dir = path.join(dir, opt.require_version)
end
return path.join(dir, opt.buildhash)
end
-- find package using the go package manager
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, version = "1.12.x")
--
function main(name, opt)
local result
local installdir = _go_get_installdir(name, opt)
for _, libraryfile in ipairs(os.files(path.join(installdir, "lib", "**.a"))) do
result = {version = opt.require_version, linkdirs = path.join(installdir, "lib"), includedirs = path.join(installdir, "lib")}
break
end
return result
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/go/install_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file install_package.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("lib.detect.find_tool")
import("core.package.package")
import("private.tools.go.goenv")
-- get the package cache directory
function _go_get_cachedir(name, opt)
local name = "go_" .. name:lower()
return path.join(package.cachedir(), name:sub(1, 1), name, opt.require_version)
end
-- get the package install directory
function _go_get_installdir(name, opt)
local name = "go_" .. name:lower()
local dir = path.join(package.installdir(), name:sub(1, 1):lower(), name)
if opt.require_version then
dir = path.join(dir, opt.require_version)
end
return path.join(dir, opt.buildhash)
end
-- install package
--
-- @param name the package name, e.g. go::github.com/sirupsen/logrus
-- @param opt the options, e.g. { verbose = true, mode = "release", plat = , arch = , require_version = "x.x.x", buildhash = "xxxxxx"}
--
-- @return true or false
--
function main(name, opt)
-- TODO we do not yet support the installation of go packages in specific versions
local version = opt.require_version
assert(not version or version == "latest" or version == "master", "we can only support to install go packages without version!")
-- find go
local go = find_tool("go")
if not go then
raise("go not found!")
end
-- get plat and arch
local goos = goenv.GOOS(opt.plat)
local goarch = goenv.GOARCH(opt.arch)
-- get go package to cachedir/pkg/${goos}_${goarch}/github.com/xxx/*.a
local cachedir = _go_get_cachedir(name, opt)
os.tryrm(cachedir)
os.mkdir(cachedir)
os.vrunv(go.program, {"get", "-u", name}, {envs = {GOPATH = cachedir, GOOS = goos, GOARCH = goarch}, curdir = cachedir})
-- install go package
local installdir = _go_get_installdir(name, opt)
local pkgdir = path.join(cachedir, "pkg", goos .. "_" .. goarch)
os.tryrm(installdir)
os.mkdir(path.join(installdir, "lib"))
os.vcp(path.join(pkgdir, "**.a"), path.join(installdir, "lib"), {rootdir = pkgdir})
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/dub/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_package.lua
--
-- imports
import("core.base.option")
import("core.base.semver")
import("core.base.json")
import("core.project.config")
import("core.project.target")
import("lib.detect.find_tool")
import("lib.detect.find_file")
-- find package using the dub package manager
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, require_version = "1.12.x")
--
function main(name, opt)
-- find dub
local dub = find_tool("dub")
if not dub then
raise("dub not found!")
end
-- get the library pattern
local libpattern = (opt.plat == "windows") and "**.lib" or "**.a"
-- find package
local result
local pkglist = os.iorunv(dub.program, {"list"})
if pkglist then
local pkgdir
for _, line in ipairs(pkglist:split('\n', {plain = true})) do
local pkginfo = line:split(': ', {plain = true})
if #pkginfo == 2 then
local pkgkey = pkginfo[1]:trim():split(' ', {plain = true})
local pkgpath = pkginfo[2]:trim()
if #pkgkey == 2 then
local pkgname = pkgkey[1]:trim()
local pkgversion = pkgkey[2]:trim()
if pkgname == name and find_file(libpattern, pkgpath) and
(not opt.require_version or opt.require_version == "latest" or opt.require_version == "master" or semver.satisfies(pkgversion, opt.require_version)) then
pkgdir = pkgpath
break
end
end
end
end
if pkgdir then
local links = {}
local linkdirs = {}
for _, libraryfile in ipairs(os.files(path.join(pkgdir, libpattern))) do
table.insert(links, target.linkname(path.filename(libraryfile), {plat = opt.plat}))
table.insert(linkdirs, path.directory(libraryfile))
end
linkdirs = table.unique(linkdirs)
local includedirs = {}
local dubjson = path.join(pkgdir, "dub.json")
if os.isfile(dubjson) then
dubjson = json.loadfile(dubjson)
if dubjson and dubjson.importPaths then
for _, importPath in ipairs(dubjson.importPaths) do
table.insert(includedirs, path.join(pkgdir, importPath))
end
end
end
if #includedirs > 0 and #links > 0 then
result = {version = opt.require_version, links = links, linkdirs = linkdirs, includedirs = includedirs}
end
end
end
return result
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/dub/install_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file install_package.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("lib.detect.find_tool")
-- install package
--
-- @param name the package name, e.g. dub::log
-- @param opt the options, e.g. { verbose = true, mode = "release", plat = , arch = , require_version = "x.x.x"}
--
-- @return true or false
--
function main(name, opt)
-- find dub
local dub = find_tool("dub")
if not dub then
raise("dub not found!")
end
-- fetch the given package
local argv = {"fetch", name}
if option.get("verbose") then
table.insert(argv, "-v")
end
if opt.require_version and opt.require_version ~= "latest" and opt.require_version ~= "master" then
table.insert(argv, "--version=" .. opt.require_version)
end
os.vrunv(dub.program, argv)
-- build the given package
argv = {"build", name, "-y"}
if opt.mode == "debug" then
table.insert(argv, "--build=debug")
else
table.insert(argv, "--build=release")
end
if option.get("verbose") then
table.insert(argv, "-v")
end
local archs = {x86_64 = "x86_64",
x64 = "x86_64",
i386 = "x86",
x86 = "x86"}
local arch = archs[opt.arch]
if arch then
table.insert(argv, "--arch=" .. arch)
else
raise("cannot install package(%s) for arch(%s)!", name, opt.arch)
end
os.vrunv(dub.program, argv)
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/conan/configurations.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file configurations.lua
--
-- get configurations
function main()
return
{
build = {description = "Use it to choose if you want to build from sources.", default = "missing", values = {"all", "never", "missing", "outdated"}},
remote = {description = "Set the conan remote server."},
options = {description = "Set the options values, e.g. shared=True"},
settings = {description = "Set the host settings for conan."},
settings_host = {description = "Set the host settings for conan."},
settings_build = {description = "Set the build settings for conan."},
imports = {description = "Set the imports for conan 1.x, it has been deprecated in conan 2.x."},
build_requires = {description = "Set the build requires for conan."}
}
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/conan/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_package.lua
--
-- imports
import("core.base.option")
import("core.project.config")
-- get build info file
function _conan_get_buildinfo_file(name, dep_name)
local filename = "conanbuildinfo.xmake.lua"
if dep_name then
filename = "conanbuildinfo_" .. dep_name .. ".xmake.lua"
end
return path.absolute(path.join(config.buildir() or os.tmpdir(), ".conan", name, filename))
end
-- get conan platform
function _conan_get_plat(opt)
local plats = {macosx = "Macos", windows = "Windows", mingw = "Windows", linux = "Linux", cross = "Linux", iphoneos = "iOS", android = "Android"}
return plats[opt.plat]
end
-- get conan architecture
function _conan_get_arch(opt)
local archs = {x86_64 = "x86_64",
x64 = "x86_64",
i386 = "x86",
x86 = "x86",
armv7 = "armv7",
["armv7-a"] = "armv7", -- for android, deprecated
["armeabi"] = "armv7", -- for android, removed in ndk r17
["armeabi-v7a"] = "armv7", -- for android
armv7s = "armv7s", -- for iphoneos
arm64 = "armv8", -- for iphoneos
["arm64-v8a"] = "armv8", -- for android
mips = "mips",
mips64 = "mips64"}
return archs[opt.arch]
end
-- get conan mode
function _conan_get_mode(opt)
return opt.mode == "debug" and "Debug" or "Release"
end
-- get info key
function _conan_get_infokey(opt)
local plat = _conan_get_plat(opt)
local arch = _conan_get_arch(opt)
local mode = _conan_get_mode(opt)
if plat and arch and mode then
return plat .. "_" .. arch .. "_" .. mode
end
end
-- get build info
function _conan_get_buildinfo(name, opt)
opt = opt or {}
local buildinfo_file = _conan_get_buildinfo_file(name, opt.dep_name)
if not os.isfile(buildinfo_file) then
return
end
-- load build info
local infokey = _conan_get_infokey(opt)
if not infokey then
return
end
local buildinfo = io.load(buildinfo_file)
if buildinfo then
buildinfo = buildinfo[infokey]
end
-- get the package info of the given platform, architecture and mode
local found = false
local result = {}
local dep_names
for k, v in pairs(buildinfo) do
if not k:startswith("__") then
if #table.wrap(v) > 0 then
result[k] = v
found = true
end
end
end
-- remove unused frameworks for linux
-- @see https://github.com/xmake-io/xmake/issues/5358
local plat = opt.plat
if found and result and plat ~= "macosx" and plat ~= "iphoneos" then
result.frameworks = nil
result.frameworkdirs = nil
end
if found then
return buildinfo, result
end
end
-- find conan library
function _conan_find_library(name, opt)
opt = opt or {}
local buildinfo, result = _conan_get_buildinfo(name, opt)
if result then
local libfiles = {}
for _, linkdir in ipairs(result.linkdirs) do
for _, file in ipairs(os.files(path.join(linkdir, "*"))) do
if file:endswith(".lib") or file:endswith(".a") then
result.static = true
table.insert(libfiles, file)
elseif file:endswith(".so") or file:match(".+%.so%..+$") or file:endswith(".dylib") or file:endswith(".dll") then -- maybe symlink to libxxx.so.1
result.shared = true
table.insert(libfiles, file)
end
end
end
if opt.plat == "windows" or opt.plat == "mingw" then
for _, bindir in ipairs(buildinfo.__bindirs) do
for _, file in ipairs(os.files(path.join(bindir, "*.dll"))) do
result.shared = true
table.insert(libfiles, file)
end
end
end
for _, includedir in ipairs(result.includedirs) do
if not os.isdir(includedir) then
return
end
end
local require_version = opt.require_version
if require_version ~= nil and require_version ~= "latest" then
result.version = opt.require_version
end
result.libfiles = table.unique(libfiles)
return result, buildinfo.__dep_names
end
end
-- find package using the conan package manager
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true)
--
function main(name, opt)
local result, dep_names = _conan_find_library(name, opt)
if result and dep_names then
for _, dep_name in ipairs(dep_names) do
local depinfo = _conan_find_library(name, table.join(opt, {dep_name = dep_name}))
for k, v in pairs(depinfo) do
result[k] = table.join(result[k] or {}, v)
end
end
for k, v in pairs(result) do
if k == "links" or k == "syslinks" or k == "frameworks" then
result[k] = table.unwrap(table.reverse_unique(v))
else
result[k] = table.unwrap(table.unique(v))
end
end
end
return result
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/conan/install_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file install_package.lua
--
-- imports
import("core.base.option")
import("core.base.semver")
import("lib.detect.find_tool")
-- install package
--
-- @param name the package name, e.g. conan::OpenSSL 1.0.2n
-- @param opt the options, e.g. { verbose = true, mode = "release", plat = , arch = ,
-- configs = {
-- remote = "", build = "all", options = {}, imports = {}, build_requires = {},
-- settings = {"compiler=msvc", "compiler.version=10", "compiler.runtime=MD"}}}
--
function main(name, opt)
local conan = find_tool("conan", {version = true})
if not conan then
raise("conan not found!")
end
if conan.version and semver.compare(conan.version, "2.0.5") >= 0 then
-- https://github.com/conan-io/conan/issues/13709
import("package.manager.conan.v2.install_package")(conan, name, opt)
elseif conan.version and semver.compare(conan.version, "2.0.0") < 0 then
import("package.manager.conan.v1.install_package")(conan, name, opt)
else
-- conan 2.0.0-2.0.4 does not supported
raise("conan %s is not supported, please use conan 1.x", conan.version)
end
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/conan/search_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file search_package.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_tool")
-- search package using the conan package manager
--
-- @param name the package name with pattern
--
function main(name)
-- find conan
local conan = find_tool("conan")
if not conan then
raise("conan not found!")
end
-- search packages
local results = {}
local searchdata = os.iorunv(conan.program, {"search", name})
for _, line in ipairs(searchdata:split("\n", {plain = true})) do
local packagename = line:trim()
if packagename:find(name, 1, true) then
table.insert(results, {name = "conan::" .. packagename})
end
end
return results
end
|
0 | repos/xmake/xmake/modules/package/manager/conan | repos/xmake/xmake/modules/package/manager/conan/v1/install_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file install_package.lua
--
-- imports
import("core.base.option")
import("core.base.semver")
import("core.project.config")
import("core.tool.toolchain")
import("core.platform.platform")
import("lib.detect.find_tool")
import("devel.git")
import("net.fasturl")
-- get build env
function _conan_get_build_env(name, plat)
local value = config.get(name)
if value == nil then
value = platform.toolconfig(name, plat)
end
if value == nil then
value = platform.tool(name, plat)
end
value = table.unique(table.wrap(value))
if #value > 0 then
value = table.unwrap(value)
return value
end
end
-- get build directory
function _conan_get_build_directory(name)
return path.absolute(path.join(config.buildir() or os.tmpdir(), ".conan", name))
end
-- generate conanfile.txt
function _conan_generate_conanfile(name, configs, opt)
-- trace
dprint("generate %s ..", path.join(_conan_get_build_directory(name), "conanfile.txt"))
-- get conan options, imports and build_requires
local options = table.wrap(configs.options)
local imports = table.wrap(configs.imports)
local build_requires = table.wrap(configs.build_requires or "xmake_generator/0.1.0@bincrafters/testing")
-- @see https://docs.conan.io/en/latest/systems_cross_building/cross_building.html
-- generate it
local conanfile = io.open("conanfile.txt", "w")
if conanfile then
conanfile:print("[generators]")
conanfile:print("xmake")
conanfile:print("[requires]")
local require_version = opt.require_version
if require_version ~= nil and require_version ~= "latest" then
conanfile:print("%s/%s", name, require_version)
else
conanfile:print("%s", name)
end
if #options > 0 then
conanfile:print("[options]")
for _, item in ipairs(options) do
if not item:find(":", 1, true) then
item = name .. ":" .. item
end
conanfile:print("%s", item)
end
end
if #imports > 0 then
conanfile:print("[imports]")
conanfile:print("%s", table.concat(imports, "\n"))
end
if #build_requires > 0 then
conanfile:print("[build_requires]")
conanfile:print("%s", table.concat(build_requires, "\n"))
end
conanfile:close()
end
end
-- install xmake generator
function _conan_install_xmake_generator(conan)
local xmake_generator_localdir = path.join(config.directory(), "conan", "xmake_generator")
if not os.isdir(xmake_generator_localdir) then
-- sort main urls
local mainurls = {"https://github.com/xmake-io/conan-xmake_generator.git",
"https://gitlab.com/xmake-io/conan-xmake_generator.git",
"https://gitee.com/xmake-io/conan-xmake_generator.git"}
fasturl.add(mainurls)
mainurls = fasturl.sort(mainurls)
-- clone xmake generator repository
local ok = false
for _, url in ipairs(mainurls) do
ok = try { function () git.clone(url, {depth = 1, branch = "0.1.0/testing", outputdir = xmake_generator_localdir}); return true end }
if ok then
break
end
end
if ok then
os.vrunv(conan.program, {"export", xmake_generator_localdir, "bincrafters/testing"})
end
end
end
-- install package
function main(conan, name, opt)
-- get configs
opt = opt or {}
local configs = opt.configs or {}
-- get build directory
local buildir = _conan_get_build_directory(name)
-- clean the build directory
os.tryrm(buildir)
if not os.isdir(buildir) then
os.mkdir(buildir)
end
-- enter build directory
local oldir = os.cd(buildir)
-- install xmake generator
_conan_install_xmake_generator(conan)
-- generate conanfile.txt
_conan_generate_conanfile(name, configs, opt)
-- install package
local argv = {"install", "."}
if configs.build then
if configs.build == "all" then
table.insert(argv, "--build")
else
table.insert(argv, "--build=" .. configs.build)
end
end
-- set platform
local plats = {macosx = "Macos", windows = "Windows", mingw = "Windows", linux = "Linux", cross = "Linux", iphoneos = "iOS", android = "Android"}
table.insert(argv, "-s")
local plat = plats[opt.plat]
if plat then
table.insert(argv, "os=" .. plat)
else
raise("cannot install package(%s) on platform(%s)!", name, opt.plat)
end
-- set architecture
local archs = {x86_64 = "x86_64",
x64 = "x86_64",
i386 = "x86",
x86 = "x86",
armv7 = "armv7",
["armv7-a"] = "armv7", -- for android, deprecated
["armeabi"] = "armv7", -- for android, removed in ndk r17
["armeabi-v7a"] = "armv7", -- for android
armv7s = "armv7s", -- for iphoneos
arm64 = "armv8", -- for iphoneos
["arm64-v8a"] = "armv8", -- for android
mips = "mips",
mips64 = "mips64"}
table.insert(argv, "-s")
local arch = archs[opt.arch]
if arch then
table.insert(argv, "arch=" .. arch)
else
raise("cannot install package(%s) for arch(%s)!", name, opt.arch)
end
-- set build mode
table.insert(argv, "-s")
if opt.mode == "debug" then
table.insert(argv, "build_type=Debug")
else
table.insert(argv, "build_type=Release")
end
-- set compiler settings
if opt.plat == "windows" then
local vsvers = {["2022"] = "17",
["2019"] = "16",
["2017"] = "15",
["2015"] = "14",
["2013"] = "12",
["2012"] = "11",
["2010"] = "10",
["2008"] = "9",
["2005"] = "8"}
local vs = assert(config.get("vs"), "vs not found!")
table.insert(argv, "-s")
table.insert(argv, "compiler=Visual Studio")
table.insert(argv, "-s")
table.insert(argv, "compiler.version=" .. assert(vsvers[vs], "unknown msvc version!"))
if configs.runtimes then
table.insert(argv, "-s")
table.insert(argv, "compiler.runtime=" .. configs.runtimes)
end
elseif opt.plat == "iphoneos" then
local target_minver = nil
local toolchain_xcode = toolchain.load("xcode", {plat = opt.plat, arch = opt.arch})
if toolchain_xcode then
target_minver = toolchain_xcode:config("target_minver")
end
if target_minver and tonumber(target_minver) > 10 and (arch == "armv7" or arch == "armv7s" or arch == "x86") then
target_minver = "10" -- iOS 10 is the maximum deployment target for 32-bit targets
end
if target_minver then
table.insert(argv, "-s")
table.insert(argv, "os.version=" .. target_minver)
end
elseif opt.plat == "android" then
local ndk_sdkver = config.get("ndk_sdkver")
if ndk_sdkver then
table.insert(argv, "-s")
table.insert(argv, "os.api_level=" .. ndk_sdkver)
end
end
-- set custom settings
for _, setting in ipairs(configs.settings) do
table.insert(argv, "-s")
table.insert(argv, setting)
end
-- set remote
if configs.remote then
table.insert(argv, "-r")
table.insert(argv, configs.remote)
end
-- TODO set environments
if opt.plat == "android" then
local envs = {}
local cflags = table.join(table.wrap(_conan_get_build_env("cxflags", opt.plat)), _conan_get_build_env("cflags", opt.plat))
local cxxflags = table.join(table.wrap(_conan_get_build_env("cxflags", opt.plat)), _conan_get_build_env("cxxflags", opt.plat))
envs.CC = _conan_get_build_env("cc", opt.plat)
envs.CXX = _conan_get_build_env("cxx", opt.plat)
envs.AS = _conan_get_build_env("as", opt.plat)
envs.AR = _conan_get_build_env("ar", opt.plat)
envs.LD = _conan_get_build_env("ld", opt.plat)
envs.LDSHARED = _conan_get_build_env("sh", opt.plat)
envs.CPP = _conan_get_build_env("cpp", opt.plat)
envs.RANLIB = _conan_get_build_env("ranlib", opt.plat)
envs.CFLAGS = table.concat(cflags, ' ')
envs.CXXFLAGS = table.concat(cxxflags, ' ')
envs.ASFLAGS = table.concat(table.wrap(_conan_get_build_env("asflags", opt.plat)), ' ')
envs.ARFLAGS = table.concat(table.wrap(_conan_get_build_env("arflags", opt.plat)), ' ')
envs.LDFLAGS = table.concat(table.wrap(_conan_get_build_env("ldflags", opt.plat)), ' ')
envs.SHFLAGS = table.concat(table.wrap(_conan_get_build_env("shflags", opt.plat)), ' ')
local toolchain_ndk = toolchain.load("ndk", {plat = opt.plat, arch = opt.arch})
local ndk_sysroot = toolchain_ndk:config("ndk_sysroot")
if ndk_sysroot then
table.insert(argv, "-e")
table.insert(argv, "CONAN_CMAKE_FIND_ROOT_PATH=" .. ndk_sysroot)
end
for k, v in pairs(envs) do
table.insert(argv, "-e")
table.insert(argv, k .. "=" .. v)
end
end
-- do install
os.vrunv(conan.program, argv)
-- leave build directory
os.cd(oldir)
end
|
0 | repos/xmake/xmake/modules/package/manager/conan | repos/xmake/xmake/modules/package/manager/conan/v2/install_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file install_package.lua
--
-- imports
import("core.base.option")
import("core.base.semver")
import("core.project.config")
import("core.tool.toolchain")
import("core.platform.platform")
import("lib.detect.find_tool")
import("devel.git")
import("net.fasturl")
-- get build env
function _conan_get_build_env(name, plat)
local value = config.get(name)
if value == nil then
value = platform.toolconfig(name, plat)
end
if value == nil then
value = platform.tool(name, plat)
end
value = table.unique(table.wrap(value))
if #value > 0 then
value = table.unwrap(value)
return value
end
end
-- get build directory
function _conan_get_build_directory(name)
return path.absolute(path.join(config.buildir() or os.tmpdir(), ".conan", name))
end
-- generate conanfile.txt
function _conan_generate_conanfile(name, configs, opt)
-- trace
dprint("generate %s ..", path.join(_conan_get_build_directory(name), "conanfile.txt"))
-- get conan options, imports and build_requires
local options = table.wrap(configs.options)
local build_requires = table.wrap(configs.build_requires)
-- @see https://docs.conan.io/1/migrating_to_2.0/recipes.html
-- https://docs.conan.io/en/latest/systems_cross_building/cross_building.html
-- generate it
local conanfile = io.open("conanfile.txt", "w")
if conanfile then
conanfile:print("[requires]")
local require_version = opt.require_version
if require_version ~= nil and require_version ~= "latest" then
conanfile:print("%s/%s", name, require_version)
else
conanfile:print("%s", name)
end
if #options > 0 then
conanfile:print("[options]")
for _, item in ipairs(options) do
if not item:find(":", 1, true) then
item = name .. "/*:" .. item
end
conanfile:print("%s", item)
end
end
if #build_requires > 0 then
conanfile:print("[tool_requires]")
conanfile:print("%s", table.concat(build_requires, "\n"))
end
conanfile:close()
end
end
-- get conan home directory
function _conan_get_homedir(conan)
local homedir = _g.homedir
if homedir == nil then
homedir = try {function () return os.iorunv(conan.program, {"config", "home"}) end}
_g.homedir = homedir
end
return homedir
end
-- install xmake generator
-- @see https://github.com/conan-io/conan/pull/13718
--
function _conan_install_xmake_generator(conan)
local homedir = assert(_conan_get_homedir(conan), "cannot get conan home")
local scriptfile_now = path.join(os.programdir(), "scripts", "conan", "extensions", "generators", "xmake_generator.py")
local scriptfile_installed = path.join(homedir, "extensions", "generators", "xmake_generator.py")
if not os.isfile(scriptfile_installed) or os.mtime(scriptfile_now) > os.mtime(scriptfile_installed) then
os.vrunv(conan.program, {"config", "install", path.join(os.programdir(), "scripts", "conan")})
end
end
-- get arch
function _conan_get_arch(arch)
local map = {x86_64 = "x86_64",
x64 = "x86_64",
i386 = "x86",
x86 = "x86",
armv7 = "armv7",
["armv7-a"] = "armv7", -- for android, deprecated
["armeabi"] = "armv7", -- for android, removed in ndk r17
["armeabi-v7a"] = "armv7", -- for android
armv7s = "armv7s", -- for iphoneos
arm64 = "armv8", -- for iphoneos
["arm64-v8a"] = "armv8", -- for android
mips = "mips",
mips64 = "mips64"}
return assert(map[arch], "unknown arch(%s)!", arch)
end
-- get os
function _conan_get_os(plat)
local map = {macosx = "Macos",
windows = "Windows",
mingw = "Windows",
linux = "Linux",
cross = "Linux",
iphoneos = "iOS",
android = "Android"}
return assert(map[plat], "unknown os(%s)!", plat)
end
-- get build type
function _conan_get_build_type(mode)
if mode == "debug" then
return "Debug"
else
return "Release"
end
end
-- get compiler version
--
-- https://github.com/conan-io/conan/blob/353c63b16c31c90d370305b5cbb5dc175cf8a443/conan/tools/microsoft/visual.py#L13
-- https://github.com/xmake-io/xmake/issues/5338
function _conan_get_compiler_version(name, opt)
opt = opt or {}
local version
local result = find_tool(name, {program = opt.program, version = true, envs = opt.envs})
if result and result.version then
local v = semver.try_parse(result.version)
if v then
if name == "cl" then
version = tostring(v:major()) .. tostring(v:minor()):sub(1, 1)
else
version = tostring(v:major())
end
end
end
return version
end
-- generate compiler profile
function _conan_generate_compiler_profile(profile, configs, opt)
local conf
local plat = opt.plat
local arch = opt.arch
local runtimes = configs.runtimes
if plat == "windows" then
local msvc = toolchain.load("msvc", {plat = plat, arch = arch})
assert(msvc:check(), "vs not found!")
local vs = assert(msvc:config("vs"), "vs not found!")
profile:print("compiler=msvc")
local version = _conan_get_compiler_version("cl", {envs = msvc:runenvs()})
if version then
profile:print("compiler.version=" .. version)
end
-- @see https://github.com/conan-io/conan/issues/12387
if tonumber(vs) >= 2015 then
profile:print("compiler.cppstd=14")
end
if runtimes then
profile:print("compiler.runtime=" .. (runtimes:startswith("MD") and "dynamic" or "static"))
profile:print("compiler.runtime_type=" .. (runtimes:endswith("d") and "Debug" or "Release"))
end
elseif plat == "iphoneos" then
local target_minver = nil
local xcode = toolchain.load("xcode", {plat = plat, arch = arch})
if xcode then
target_minver = xcode:config("target_minver")
end
if target_minver and tonumber(target_minver) > 10 and (arch == "armv7" or arch == "armv7s" or arch == "x86") then
target_minver = "10" -- iOS 10 is the maximum deployment target for 32-bit targets
end
if target_minver then
profile:print("os.version=" .. target_minver)
end
local simulator = xcode:config("appledev") == "simulator"
profile:print("os.sdk=" .. (simulator and "iphonesimulator" or "iphoneos"))
profile:print("compiler=clang")
local version = _conan_get_compiler_version("clang")
if version then
profile:print("compiler.version=" .. version)
end
elseif plat == "android" then
local ndk = toolchain.load("ndk", {plat = plat, arch = arch})
local ndk_sdkver = ndk:config("ndk_sdkver")
if ndk_sdkver then
profile:print("os.api_level=" .. ndk_sdkver)
end
if runtimes then
profile:print("compiler.libcxx=" .. runtimes)
end
local program, toolname = ndk:tool("cc")
local version = _conan_get_compiler_version(toolname, {program = program})
profile:print("compiler=" .. toolname)
if version then
profile:print("compiler.version=" .. version)
end
conf = {}
conf["tools.android:ndk_path"] = ndk:config("ndk")
else
local program, toolname = platform.tool("cc", plat, arch)
if toolname == "gcc" or toolname == "clang" then
profile:print("compiler=" .. toolname)
profile:print("compiler.cppstd=gnu17")
local libcxx = "libstdc++11"
if runtimes and table.contains(table.wrap(runtimes), "c++_static", "c++_shared") then
libcxx = "libc++"
elseif not runtimes and toolname == "clang" then
libcxx = "libc++"
end
profile:print("compiler.libcxx=" .. libcxx)
local version = _conan_get_compiler_version(toolname, {program = program})
if version then
profile:print("compiler.version=" .. version)
end
end
end
if conf then
profile:print("")
profile:print("[conf]")
for k, v in pairs(conf) do
profile:print("%s=%s", k, v)
end
end
end
-- generate build profile
function _conan_generate_build_profile(configs, opt)
local profile = io.open("profile_build.txt", "w")
profile:print("[settings]")
profile:print("arch=%s", _conan_get_arch(os.arch()))
profile:print("build_type=%s", _conan_get_build_type(opt.mode))
profile:print("os=%s", _conan_get_os(os.host()))
_conan_generate_compiler_profile(profile, configs, {plat = os.host(), arch = os.arch()})
profile:close()
end
-- generate host profile
function _conan_generate_host_profile(configs, opt)
local profile = io.open("profile_host.txt", "w")
profile:print("[settings]")
profile:print("arch=%s", _conan_get_arch(opt.arch))
profile:print("build_type=%s", _conan_get_build_type(opt.mode))
profile:print("os=%s", _conan_get_os(opt.plat))
_conan_generate_compiler_profile(profile, configs, opt)
profile:close()
end
-- install package
function main(conan, name, opt)
-- get configs
opt = opt or {}
local configs = opt.configs or {}
-- get build directory
local buildir = _conan_get_build_directory(name)
-- clean the build directory
os.tryrm(buildir)
if not os.isdir(buildir) then
os.mkdir(buildir)
end
-- enter build directory
local oldir = os.cd(buildir)
-- install xmake generator
_conan_install_xmake_generator(conan)
-- generate conanfile.txt
_conan_generate_conanfile(name, configs, opt)
-- generate host profile
_conan_generate_host_profile(configs, opt)
-- generate build profile
_conan_generate_build_profile(configs, opt)
-- install package
local argv = {"install", ".", "-g", "XmakeGenerator",
"--profile:build=profile_build.txt", "--profile:host=profile_host.txt"}
if configs.build then
if configs.build == "all" then
table.insert(argv, "--build")
else
table.insert(argv, "--build=" .. configs.build)
end
end
-- set custom host settings
for _, setting in ipairs(configs.settings or configs.settings_host) do
table.insert(argv, "-s")
table.insert(argv, setting)
end
-- set custom build settings
for _, setting in ipairs(configs.settings_build) do
table.insert(argv, "-s:b")
table.insert(argv, setting)
end
-- set remote
if configs.remote then
table.insert(argv, "-r")
table.insert(argv, configs.remote)
end
-- do install
os.vrunv(conan.program, argv)
-- leave build directory
os.cd(oldir)
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/portage/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_package.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_file")
import("lib.detect.find_tool")
import("private.core.base.is_cross")
import("package.manager.pkgconfig.find_package", {alias = "find_package_from_pkgconfig"})
-- find package from the system directories
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, version = "1.12.x")
--
function main(name, opt)
opt = opt or {}
if is_cross(opt.plat, opt.arch) then
return
end
-- for msys2/mingw? mingw-w64-[i686|x86_64]-xxx
if opt.plat == "mingw" then
name = "mingw64-runtime" -- there is only one package for mingw
end
-- get package contents file
local file = find_file("CONTENTS", "/var/db/pkg/*/" .. name .. "-*")
if not file then
return
end
-- get package files list
local list = {}
local file_contents = io.readfile(file)
for _, entry in pairs(file_contents:split("\n")) do
-- the file path is the second element after being delimited by spaces
local split_entry = entry:split(" ")[2]
if split_entry then
table.insert(list, split_entry)
end
end
-- parse package files list
local linkdirs = {}
local has_includes = false
local pkgconfig_files = {}
for _, line in ipairs(list) do
line = line:trim():split('%s+')[1]
if line:find("/pkgconfig/", 1, true) and line:endswith(".pc") then
pkgconfig_files[path.basename(line)] = line
end
if line:endswith(".so") or line:endswith(".a") or line:endswith(".lib") then
table.insert(linkdirs, path.directory(line))
elseif line:find("/include/", 1, true) and (line:endswith(".h") or line:endswith(".hpp")) then
has_includes = true
end
end
-- get pkgconfig file
local pkgconfig_file = pkgconfig_files[name]
if not pkgconfig_file then
for _, file in pairs(pkgconfig_files) do
pkgconfig_file = file
break
end
end
-- find package
local result = nil
if pkgconfig_file then
local pkgconfig_dir = path.directory(pkgconfig_file)
local pkgconfig_name = path.basename(pkgconfig_file)
linkdirs = table.unique(linkdirs)
includedirs = table.unique(includedirs)
result = find_package_from_pkgconfig(pkgconfig_name, {configdirs = pkgconfig_dir, linkdirs = linkdirs})
if not result and has_includes then
-- header only and hidden /usr/include? we only need to return empty {}
result = {}
end
end
return result
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/portage/install_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file install_package.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_tool")
import("privilege.sudo")
-- install package
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, emerge = "the package name"}
--
-- @return true or false
--
function main(name, opt)
-- init options
opt = opt or {}
-- find emerge
local emerge = find_tool("emerge")
if not emerge then
raise("emerge not found!")
end
-- for msys2/mingw? mingw-w64-[i686|x86_64]-xxx
if opt.plat == "mingw" then
name = "mingw64-runtime"
end
-- init argv
-- ask for confirmation, view tree of packages, verbose
-- it is set this way because Portage compiles from source
-- therefore it's better to have more info and ask for confirmation
-- that way the user can ensure they installed the package with the correct USE flags
local argv = {"-a", "-t", "-v", opt.emerge or name}
if opt.verbose or option.get("verbose") then
table.insert(argv, "-v")
end
-- install package directly if the current user is root
if is_subhost("msys") or os.isroot() then
os.vrunv(emerge.program, argv)
-- install with administrator permission?
elseif sudo.has() then
-- install it if be confirmed
local description = format("try installing %s with administrator permission", name)
local confirm = utils.confirm({default = true, description = description})
if confirm then
sudo.vrunv(emerge.program, argv)
end
else
raise("cannot get administrator permission!")
end
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/clib/configurations.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author Adel Vilkov (aka RaZeR-RBI)
-- @file configurations.lua
--
-- get configurations
function main()
return
{
save = {description = "save dependency in project's package.json", default = false, type = "boolean"},
save_dev = {description = "save as development dependency in project's package.json", default = false, type = "boolean"},
outputdir = {description = "package installation directory relative to project root", default = "clib"},
}
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/clib/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author Adel Vilkov (aka RaZeR-RBI)
-- @file find_package.lua
--
-- imports
import("core.base.option")
import("core.project.config")
function main(name, opt)
-- check if a package marker file with install directory exists
local cache_dir = path.join(config.directory(), "clib", "cache", "packages")
local marker_filename = string.gsub(name, "%/", "=")
local marker_path = path.join(cache_dir, marker_filename)
dprint("looking for marker file for %s at %s", name, marker_path)
if not os.isfile(marker_path) then
dprint("no marker file found for %s", name)
return
end
dprint("found marker file for %s", name)
return io.load(marker_path)
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/clib/install_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author Adel Vilkov (aka RaZeR-RBI)
-- @file install_package.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("lib.detect.find_tool")
-- install package
-- @param name the package name, e.g. clib::clibs/[email protected]
-- @param opt the options, e.g. { verbose = true,
-- configs = {outputdir = "clib", save = false, save_dev = false}}
--
-- @return true or false
--
function main(name, opt)
-- find clib
local clib = find_tool("clib")
if not clib then
raise("clib not found!")
end
opt = opt or {}
local configs = opt.configs or {}
local argv = {"install", name}
local abs_out = path.join(os.projectdir(), configs.outputdir)
dprint("installing %s to %s", name, abs_out)
table.insert(argv, "-o " .. abs_out)
if not option.get("verbose") then
table.insert(argv, "-q")
end
if configs.save then
table.insert(argv, "--save")
end
if configs.save_dev then
table.insert(argv, "--save-dev")
end
-- save previous directory and cd to project directory
local old_dir = os.curdir()
os.cd(os.projectdir())
-- do install
os.vrunv(clib.program, argv)
-- restore old directory
os.cd(old_dir)
-- add a package marker file with install directory
local cache_dir = path.join(config.directory(), "clib", "cache", "packages")
local marker_filename = string.gsub(name, "%/", "=")
local marker_path = path.join(cache_dir, marker_filename)
dprint("writing clib marker file for %s to %s", name, marker_path)
io.save(marker_path, {includedirs = { abs_out }})
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/cmake/configurations.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file configurations.lua
--
-- get configurations
function main()
return
{
link_libraries = {description = "Set the cmake package dependencies, e.g. {\"abc::lib1\", \"abc::lib2\"}"},
include_directories = {description = "Set the cmake package include directories, e.g. {\"${ZLIB_INCLUDE_DIRS}\"}"},
search_mode = {description = "Set the cmake package search mode, e.g. {\"config\", \"module\"}"},
components = {description = "Set the cmake package components, e.g. {\"regex\", \"system\"}"},
moduledirs = {description = "Set the cmake modules directories."},
presets = {description = "Set the preset values, e.g. {Boost_USE_STATIC_LIB = true}"},
envs = {description = "Set the run environments of cmake, e.g. {CMAKE_PREFIX_PATH = \"xxx\"}"},
}
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/cmake/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_package.lua
--
-- imports
import("core.base.option")
import("core.base.hashset")
import("core.project.target")
import("lib.detect.find_tool")
-- exclude cmake internal definitions https://github.com/xmake-io/xmake/issues/5217
function _should_exclude(define)
local name = define:split("=")[1]
return table.contains({"CMAKE_INTDIR", "_DEBUG", "NDEBUG"}, name)
end
-- map xmake mode to cmake mode
function _cmake_mode(mode)
if mode == "debug" then return "Debug"
elseif mode == "releasedbg" then return "RelWithDebInfo"
elseif mode == "minsizerel" then return "MinSizeRel"
else return "Release"
end
end
-- find package
function _find_package(cmake, name, opt)
-- get work directory
local workdir = os.tmpfile() .. ".dir"
os.tryrm(workdir)
os.mkdir(workdir)
io.writefile(path.join(workdir, "test.cpp"), "")
-- generate CMakeLists.txt
local filepath = path.join(workdir, "CMakeLists.txt")
local cmakefile = io.open(filepath, "w")
if cmake.version then
cmakefile:print("cmake_minimum_required(VERSION %s)", cmake.version)
end
cmakefile:print("project(find_package)")
-- e.g. OpenCV 4.1.1, Boost COMPONENTS regex system
local requirestr = name
local configs = opt.configs or {}
if opt.require_version and opt.require_version ~= "latest" then
requirestr = requirestr .. " " .. opt.require_version
end
-- set search mode, e.g. config, module
-- it will be both mode if do not set this config.
-- e.g. https://cmake.org/cmake/help/latest/command/find_package.html#id4
if configs.search_mode then
requirestr = requirestr .. " " .. configs.search_mode:upper()
end
-- use opt.components is for backward compatibility
local componentstr = ""
local components = configs.components or opt.components
if components and #components > 0 then
componentstr = "COMPONENTS"
for _, component in ipairs(components) do
componentstr = componentstr .. " " .. component
end
end
local moduledirs = configs.moduledirs or opt.moduledirs
if moduledirs then
for _, moduledir in ipairs(moduledirs) do
cmakefile:print("list(APPEND CMAKE_MODULE_PATH \"%s\")", (moduledir:gsub("\\", "/")))
end
end
-- e.g. set(Boost_USE_STATIC_LIB ON)
local presets = configs.presets or opt.presets
if presets then
for k, v in pairs(presets) do
if type(v) == "boolean" then
cmakefile:print("set(%s %s)", k, v and "ON" or "OFF")
else
cmakefile:print("set(%s %s)", k, tostring(v))
end
end
end
local testname = "test_" .. name
cmakefile:print("find_package(%s REQUIRED %s)", requirestr, componentstr)
cmakefile:print("if(%s_FOUND)", name)
cmakefile:print(" add_executable(%s test.cpp)", testname)
-- setup include directories
local includedirs = ""
if configs.include_directories then
includedirs = table.concat(table.wrap(configs.include_directories), " ")
else
includedirs = ("${%s_INCLUDE_DIR} ${%s_INCLUDE_DIRS}"):format(name, name)
includedirs = includedirs .. (" ${%s_INCLUDE_DIR} ${%s_INCLUDE_DIRS}"):format(name:upper(), name:upper())
end
cmakefile:print(" target_include_directories(%s PRIVATE %s)", testname, includedirs)
-- reserved for backword compatibility
cmakefile:print(" target_include_directories(%s PRIVATE ${%s_CXX_INCLUDE_DIRS})",
testname, name)
-- setup link library/target
local linklibs = ""
if configs.link_libraries then
linklibs = table.concat(table.wrap(configs.link_libraries), " ")
else
linklibs = ("${%s_LIBRARY} ${%s_LIBRARIES} ${%s_LIBS}"):format(name, name, name)
linklibs = linklibs .. (" ${%s_LIBRARY} ${%s_LIBRARIES} ${%s_LIBS}"):format(name:upper(), name:upper(), name:upper())
end
cmakefile:print(" target_link_libraries(%s PRIVATE %s)", testname, linklibs)
cmakefile:print("endif(%s_FOUND)", name)
cmakefile:close()
if option.get("diagnosis") then
local cmakedata = io.readfile(filepath)
cprint("finding it from the generated CMakeLists.txt:\n${dim}%s", cmakedata)
end
-- run cmake
local envs = configs.envs or opt.envs or {}
envs.CMAKE_BUILD_TYPE = envs.CMAKE_BUILD_TYPE or _cmake_mode(opt.mode or "release")
try {function() return os.vrunv(cmake.program, {workdir}, {curdir = workdir, envs = envs}) end}
-- pares defines and includedirs for macosx/linux
local links
local linkdirs
local libfiles
local defines
local includedirs
local ldflags
local flagsfile = path.join(workdir, "CMakeFiles", testname .. ".dir", "flags.make")
if os.isfile(flagsfile) then
local flagsdata = io.readfile(flagsfile)
if flagsdata then
if option.get("diagnosis") then
cprint("finding includes from %s\n${dim}%s", flagsfile, flagsdata)
end
for _, line in ipairs(flagsdata:split("\n", {plain = true})) do
if line:find("CXX_INCLUDES =", 1, true) then
local has_include = false
local flags = os.argv(line:split("=", {plain = true})[2]:trim())
for _, flag in ipairs(flags) do
if has_include or (flag:startswith("-I") and #flag > 2) then
local includedir = has_include and flag or flag:sub(3)
if includedir and os.isdir(includedir) then
includedirs = includedirs or {}
table.insert(includedirs, includedir)
end
has_include = false
elseif flag == "-isystem" or flag == "-I" then
has_include = true
end
end
elseif line:find("CXX_DEFINES =", 1, true) then
defines = defines or {}
local flags = os.argv(line:split("=", {plain = true})[2]:trim())
for _, flag in ipairs(flags) do
if flag:startswith("-D") and #flag > 2 then
local define = flag:sub(3)
if define and not _should_exclude(define) then
table.insert(defines, define)
end
end
end
end
end
end
end
-- parse links and linkdirs for macosx/linux
local linkfile = path.join(workdir, "CMakeFiles", testname .. ".dir", "link.txt")
if os.isfile(linkfile) then
local linkdata = io.readfile(linkfile)
if linkdata then
if option.get("diagnosis") then
cprint("finding links from %s\n${dim}%s", linkfile, linkdata)
end
for _, line in ipairs(os.argv(linkdata)) do
local is_ldflags = false
local is_library = false
for _, suffix in ipairs({".so", ".dylib", ".dylib", ".tbd", ".lib"}) do
if line:startswith("-Wl,") then
is_ldflags = true
break
elseif line:find(suffix, 1, true) then
is_library = true
break
end
end
if is_ldflags then
ldflags = ldflags or {}
table.insert(ldflags, line)
elseif is_library then
-- strip library version suffix, e.g. libxxx.so.1.1 -> libxxx.so
if line:find(".so", 1, true) then
line = line:gsub("lib(.-)%.so%..+$", "lib%1.so")
end
-- get libfiles
if os.isfile(line) then
libfiles = libfiles or {}
table.insert(libfiles, line)
end
-- get links and linkdirs
local linkdir = path.directory(line)
if linkdir ~= "." then
linkdirs = linkdirs or {}
table.insert(linkdirs, linkdir)
end
local link = target.linkname(path.filename(line))
if link then
links = links or {}
table.insert(links, link)
end
-- is link? e.g. -lxxx
elseif line:startswith("-l") then
local link = line:sub(3):trim()
links = links or {}
table.insert(links, link)
end
end
end
end
-- pares includedirs and links/linkdirs for windows
local vcprojfile = path.join(workdir, testname .. ".vcxproj")
if os.isfile(vcprojfile) then
local vcprojdata = io.readfile(vcprojfile)
local vs_mode = envs.CMAKE_BUILD_TYPE or _cmake_mode(opt.mode or "release")
vcprojdata = vcprojdata:match("<ItemDefinitionGroup Condition=\"'$%(Configuration%)|$%(Platform%)'=='" .. vs_mode .. "|.->(.-)</ItemDefinitionGroup>")
if vcprojdata then
for _, line in ipairs(vcprojdata:split("\n", {plain = true})) do
local values = line:match("<AdditionalIncludeDirectories>(.+);%%%(AdditionalIncludeDirectories%)</AdditionalIncludeDirectories>")
if values then
includedirs = includedirs or {}
table.join2(includedirs, path.splitenv(values))
end
values = line:match("<AdditionalDependencies>(.+)</AdditionalDependencies>")
if values then
for _, library in ipairs(path.splitenv(values)) do
-- get libfiles
if os.isfile(library) then
libfiles = libfiles or {}
table.insert(libfiles, library)
end
-- get links and linkdirs
local linkdir = path.directory(library)
linkdir = path.translate(linkdir)
if linkdir ~= "." and not linkdir:startswith(workdir) then
linkdirs = linkdirs or {}
table.insert(linkdirs, linkdir)
local link = target.linkname(path.filename(library))
if link then
links = links or {}
table.insert(links, link)
end
end
end
end
values = line:match("<PreprocessorDefinitions>%%%(PreprocessorDefinitions%);(.+)</PreprocessorDefinitions>")
if values then
defines = defines or {}
values = path.splitenv(values)
for _, value in ipairs(values) do
if not _should_exclude(value) then
table.insert(defines, value)
end
end
end
end
end
end
-- remove work directory
os.tryrm(workdir)
-- get results
if links or includedirs then
local results = {}
results.links = table.reverse_unique(links)
results.ldflags = table.reverse_unique(ldflags)
results.linkdirs = table.unique(linkdirs)
results.defines = table.unique(defines)
results.libfiles = table.unique(libfiles)
results.includedirs = table.unique(includedirs)
return results
end
end
-- find package using the cmake package manager
--
-- e.g.
--
-- find_package("cmake::ZLIB")
-- find_package("cmake::OpenCV", {require_version = "4.1.1"})
-- find_package("cmake::Boost", {configs = {components = {"regex", "system"}, presets = {Boost_USE_STATIC_LIB = true}}})
-- find_package("cmake::Foo", {configs = {moduledirs = "xxx"}})
--
-- we can use add_requires with {system = true}
--
-- add_requires("cmake::ZLIB", {system = true})
-- add_requires("cmake::OpenCV 4.1.1", {system = true})
-- add_requires("cmake::Boost", {configs = {components = {"regex", "system"}, presets = {Boost_USE_STATIC_LIB = true}}})
-- add_requires("cmake::Foo", {configs = {moduledirs = "xxx"}})
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, require_version = "1.0",
-- configs = {
-- components = {"regex", "system"},
-- moduledirs = "xxx",
-- presets = {Boost_USE_STATIC_LIB = true},
-- envs = {CMAKE_PREFIX_PATH = "xxx"}})
--
function main(name, opt)
opt = opt or {}
local cmake = find_tool("cmake", {version = true})
if not cmake then
return
end
return _find_package(cmake, name, opt)
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/vcpkg/configurations.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file configurations.lua
--
-- get architecture for vcpkg
function arch(arch)
local archs = {
x86_64 = "x64",
i386 = "x86",
-- android: armeabi armeabi-v7a arm64-v8a x86 x86_64 mips mip64
-- Offers a doc: https://github.com/microsoft/vcpkg/tree/master/triplets
["armeabi-v7a"] = "arm-neon",
["arm64-v8a"] = "arm64",
-- ios: arm64 armv7 armv7s i386
armv7 = "arm",
armv7s = "arm",
arm64 = "arm64",
}
return archs[arch] or arch
end
-- get platform for vcpkg
function plat(plat)
local plats = {
macosx = "osx",
iphoneos = "ios",
bsd = "freebsd",
}
return plats[plat] or plat
end
-- get triplet
function triplet(configs, plat, arch)
configs = configs or {}
local triplet = arch .. "-" .. plat
if plat == "windows" and configs.shared ~= true then
triplet = triplet .. "-static"
if configs.runtimes and configs.runtimes:startswith("MD") then
triplet = triplet .. "-md"
end
elseif plat == "linux" then
-- x64-linux-dynamic
if arch == "x64" and configs.shared then
triplet = triplet .. "-dynamic"
end
elseif plat == "osx" then
-- x64-osx-dynamic
-- arm64-osx-dynamic
if (arch == "x64" or arch == "arm64") and configs.shared then
triplet = triplet .. "-dynamic"
end
elseif plat == "mingw" then
triplet = triplet .. (configs.shared ~= true and "-static" or "-dynamic")
end
return triplet
end
-- get configurations
function main()
return {
baseline = {description = "set the builtin baseline."},
features = {description = "set the features of dependency."},
default_features = {description = "enables or disables any defaults provided by the dependency.", default = true},
registries = {description = "set the registries in vcpkg-configuration.json"},
default_registries = {description = "set the default registries in vcpkg-configuration.json"}
}
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/vcpkg/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_package.lua
--
-- imports
import("lib.detect.find_file")
import("lib.detect.find_tool")
import("core.base.option")
import("core.project.config")
import("core.project.target")
import("detect.sdks.find_vcpkgdir")
import("package.manager.vcpkg.configurations")
import("package.manager.pkgconfig.find_package", {alias = "find_package_from_pkgconfig"})
-- we iterate over each pkgconfig file to extract the required data
function _find_package_from_pkgconfig(pkgconfig_files, opt)
opt = opt or {}
local foundpc = false
local result = {includedirs = {}, linkdirs = {}, links = {}}
for _, pkgconfig_file in ipairs(pkgconfig_files) do
local pkgconfig_dir = path.join(opt.installdir, path.directory(pkgconfig_file))
local pkgconfig_name = path.basename(pkgconfig_file)
local pcresult = find_package_from_pkgconfig(pkgconfig_name, {configdirs = pkgconfig_dir, linkdirs = opt.linkdirs})
-- the pkgconfig file has been parse successfully
if pcresult then
for _, includedir in ipairs(pcresult.includedirs) do
table.insert(result.includedirs, includedir)
end
for _, linkdir in ipairs(pcresult.linkdirs) do
table.insert(result.linkdirs, linkdir)
end
for _, link in ipairs(pcresult.links) do
table.insert(result.links, link)
end
-- version should be the same if a pacman package contains multiples .pc
result.version = pcresult.version
foundpc = true
end
end
if foundpc == true then
result.includedirs = table.unique(result.includedirs)
result.linkdirs = table.unique(result.linkdirs)
result.links = table.reverse_unique(result.links)
return result
end
end
function _find_package(vcpkgdir, name, opt)
-- get configs
local configs = opt.configs or {}
-- fix name, e.g. ffmpeg[x264] as ffmpeg
-- @see https://github.com/xmake-io/xmake/issues/925
name = name:gsub("%[.-%]", "")
-- init triplet
local arch = opt.arch
local plat = opt.plat
local mode = opt.mode
plat = configurations.plat(plat)
arch = configurations.arch(arch)
local triplet = configurations.triplet(configs, plat, arch)
-- get the vcpkg info directories
local infodirs = {}
if opt.installdir then
table.join2(infodirs, path.join(opt.installdir, "vcpkg_installed", "vcpkg", "info"))
end
table.join2(infodirs, path.join(vcpkgdir, "installed", "vcpkg", "info"))
-- find the package info file, e.g. zlib_1.2.11-3_x86-windows[-static].list
local infofile = find_file(format("%s_*_%s.list", name, triplet), infodirs)
if not infofile then
return
end
local installdir = path.directory(path.directory(path.directory(infofile)))
-- save includedirs, linkdirs and links
local result = nil
local pkgconfig_files = {}
local info = io.readfile(infofile)
if info then
for _, line in ipairs(info:split('\n')) do
line = line:trim()
if plat == "windows" then
line = line:lower()
end
-- get pkgconfig files
if line:find(triplet .. (mode == "debug" and "/debug" or "") .. "/lib/pkgconfig/", 1, true) and line:endswith(".pc") then
table.insert(pkgconfig_files, line)
end
-- get includedirs
if line:endswith("/include/") then
result = result or {}
result.includedirs = result.includedirs or {}
table.insert(result.includedirs, path.join(installdir, line))
end
-- get linkdirs and links
if (plat == "windows" and line:endswith(".lib")) or line:endswith(".a") or line:endswith(".so") then
if line:find(triplet .. (mode == "debug" and "/debug" or "") .. "/lib/", 1, true) then
result = result or {}
result.links = result.links or {}
result.linkdirs = result.linkdirs or {}
result.libfiles = result.libfiles or {}
table.insert(result.linkdirs, path.join(installdir, path.directory(line)))
table.insert(result.links, target.linkname(path.filename(line), {plat = plat}))
table.insert(result.libfiles, path.join(installdir, path.directory(line), path.filename(line)))
end
end
-- add shared library directory (/bin/) to linkdirs for running with PATH on windows
if plat == "windows" and line:endswith(".dll") then
if line:find(plat .. (mode == "debug" and "/debug" or "") .. "/bin/", 1, true) then
result = result or {}
result.linkdirs = result.linkdirs or {}
result.libfiles = result.libfiles or {}
table.insert(result.linkdirs, path.join(installdir, path.directory(line)))
table.insert(result.libfiles, path.join(installdir, path.directory(line), path.filename(line)))
end
end
end
end
-- find result from pkgconfig first
if #pkgconfig_files > 0 then
local pkgconfig_result = _find_package_from_pkgconfig(pkgconfig_files, {installdir = installdir, linkdirs = result and result.linkdirs})
if pkgconfig_result then
result = pkgconfig_result
end
end
-- save version
if result then
local infoname = path.basename(infofile)
local prefix = name
-- name maybe contains lua pattern characters, we need escape it. e.g. `-`
prefix = prefix:gsub("([%+%.%-%^%$%(%)%%])", "%%%1")
result.version = infoname:match(prefix .. "_(%d+%.?%d*%.?%d*.-)_" .. arch)
if not result.version then
result.version = infoname:match(prefix .. "_(%d+%.?%d*%.-)_" .. arch)
end
end
-- remove repeat
if result then
if result.linkdirs then
result.linkdirs = table.unique(result.linkdirs)
end
if result.includedirs then
result.includedirs = table.unique(result.includedirs)
end
end
return result
end
-- find package from the vcpkg package manager
--
-- @param name the package name, e.g. zlib, pcre
-- @param opt the options, e.g. {verbose = true)
--
function main(name, opt)
opt = opt or {}
local vcpkgdir = find_vcpkgdir()
if not vcpkgdir then
-- we need show warning if we do not try finding package and vcpkg root directory not found.
if not opt.try then
wprint("vcpkg root directory not found, maybe you need set $VCPKG_ROOT!")
end
return
end
-- do find package
return _find_package(vcpkgdir, name, opt)
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/vcpkg/install_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file install_package.lua
--
-- imports
import("core.base.option")
import("core.base.json")
import("core.base.semver")
import("lib.detect.find_tool")
import("package.manager.vcpkg.configurations")
-- need manifest mode?
function _need_manifest(opt)
local require_version = opt.require_version
if require_version ~= nil and require_version ~= "latest" then
return true
end
local configs = opt.configs
if configs and (configs.features or configs.default_features == false or configs.baseline) then
return true
end
end
-- install for classic mode
function _install_for_classic(vcpkg, name, opt)
-- get configs
local configs = opt.configs or {}
-- init triplet
local arch = opt.arch
local plat = opt.plat
plat = configurations.plat(plat)
arch = configurations.arch(arch)
local triplet = configurations.triplet(configs, plat, arch)
-- init argv
local argv = {"install", name .. ":" .. triplet}
if option.get("diagnosis") then
table.insert(argv, "--debug")
end
-- install package
os.vrunv(vcpkg, argv)
end
-- install for manifest mode
function _install_for_manifest(vcpkg, name, opt)
-- get configs
local configs = opt.configs or {}
-- init triplet
local arch = opt.arch
local plat = opt.plat
plat = configurations.plat(plat)
arch = configurations.arch(arch)
local triplet = configurations.triplet(configs, plat, arch)
-- init argv
local argv = {"--feature-flags=\"versions\"", "install", "--x-wait-for-lock", "--triplet", triplet}
if option.get("diagnosis") then
table.insert(argv, "--debug")
end
-- generate platform
local platform = plat .. " & " .. arch
-- generate dependencies
local require_version = opt.require_version
if require_version == "latest" then
require_version = nil
end
local minversion = require_version
if minversion and minversion:startswith(">=") then
minversion = minversion:sub(3)
end
local dependencies = {}
table.insert(dependencies, {
name = name,
["version>="] = minversion,
platform = platform,
features = configs.features,
["default-features"] = configs.default_features})
-- generate overrides to use fixed version
local overrides
if require_version and semver.is_valid(require_version) then
overrides = {{name = name, version = require_version}}
end
-- generate manifest, vcpkg.json
local baseline = configs.baseline or "44d94c2edbd44f0c01d66c2ad95eb6982a9a61bc" -- 2021.04.30
local manifest = {
name = "stub",
version = "1.0",
dependencies = dependencies,
["builtin-baseline"] = baseline,
overrides = overrides}
local installdir = assert(opt.installdir, "installdir not found!")
json.savefile(path.join(installdir, "vcpkg.json"), manifest)
if not os.isdir(installdir) then
os.mkdir(installdir)
end
if option.get("diagnosis") then
vprint(path.join(installdir, "vcpkg.json"))
vprint(manifest)
end
-- generate vcpkg-configuration.json
-- @see https://github.com/xmake-io/xmake/issues/2469
if configs.registries or configs.default_registries then
local configuration = {registries = configs.registries, ["default-registries"] = configs.default_registries}
json.savefile(path.join(installdir, "vcpkg-configuration.json"), configuration)
end
-- install package
os.vrunv(vcpkg, argv, {curdir = installdir})
end
-- install package
--
-- @param name the package name, e.g. pcre2, pcre2/libpcre2-8
-- @param opt the options, e.g. {verbose = true}
--
-- @return true or false
--
function main(name, opt)
-- attempt to find vcpkg
local vcpkg = find_tool("vcpkg")
if not vcpkg then
raise("vcpkg not found!")
end
-- do install
opt = opt or {}
if _need_manifest(opt) then
_install_for_manifest(vcpkg.program, name, opt)
else
_install_for_classic(vcpkg.program, name, opt)
end
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/vcpkg/search_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file search_package.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_tool")
-- search package using the vcpkg package manager
--
-- @param name the package name with pattern
--
function main(name)
-- attempt to find vcpkg
local vcpkg = find_tool("vcpkg")
if not vcpkg then
raise("vcpkg not found!")
end
-- search packages
local results = {}
local searchdata = os.iorunv(vcpkg.program, {"search", name})
for _, line in ipairs(searchdata:split("\n", {plain = true})) do
local version
local splitinfo = line:split("%s+", {limit = 2})
local packagename = splitinfo[1]
local description = splitinfo[2]
if description then
splitinfo = description:split("%s+", {limit = 2})
if #splitinfo == 2 and splitinfo[1]:find('.', 1, true) then
version = splitinfo[1]
description = splitinfo[2]
end
end
if packagename:find(name) and not packagename:find('%[.*' .. name .. '.*%]') then
table.insert(results, {name = "vcpkg::" .. packagename, version = version, description = description})
end
end
return results
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/xmake/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_package.lua
--
-- imports
import("core.base.global")
import("core.project.config")
import("core.project.option")
import("core.project.target")
import("core.package.package")
import("core.language.language")
import("lib.detect.find_file")
import("lib.detect.find_library")
-- deduplicate values
function _deduplicate_values(values)
for _, k in ipairs(table.keys(values)) do
local v = values[k]
if type(v) == "table" then
if k == "links" or k == "syslinks" or k == "frameworks" then
values[k] = table.reverse_unique(v)
else
values[k] = table.unique(v)
end
end
end
end
-- find package from the repository (maybe only include and no links)
function _find_package_from_repo(name, opt)
-- check options
if not opt.require_version or not opt.buildhash then
return
end
-- find the manifest file of package, e.g. ~/.xmake/packages/z/zlib/1.1.12/ed41d5327fad3fc06fe376b4a94f62ef/manifest.txt
local packagedirs = {}
if opt.installdir then
table.insert(packagedirs, opt.installdir)
else
table.insert(packagedirs, path.join(package.installdir(), name:lower():sub(1, 1), name:lower(), opt.require_version, opt.buildhash))
end
local manifest_file = find_file("manifest.txt", packagedirs)
if not manifest_file then
return
end
-- load manifest info
local manifest = io.load(manifest_file)
if not manifest then
return
end
-- get manifest variables
local vars = manifest.vars or {}
-- get install directory of this package
local installdir = path.directory(manifest_file)
-- save includedirs to result (maybe only include and no links)
local result = {}
local includedirs = {}
for _, includedir in ipairs(vars.includedirs) do
table.insert(includedirs, path.join(installdir, includedir))
end
if #includedirs == 0 and os.isdir(path.join(installdir, "include")) then
table.insert(includedirs, path.join(installdir, "include"))
end
if #includedirs > 0 then
result.includedirs = table.unique(includedirs)
end
-- get links and link directories
local links = {}
local linkdirs = {}
local components = opt.components
if vars.links then
table.join2(links, vars.links)
elseif components and manifest.components then
-- get links from components
local vars = manifest.components.vars
if vars then
for _, component_name in ipairs(components) do
local component_vars = vars[component_name]
if component_vars and component_vars.links then
table.join2(links, component_vars.links)
end
end
end
links = table.reverse_unique(links)
else
-- we scan links automatically
local symrefs = {}
local libfiles = {}
for _, libdir in ipairs(vars.linkdirs or "lib") do
for _, file in ipairs(os.files(path.join(installdir, libdir, "*"))) do
table.insert(libfiles, file)
if os.islink(file) then
local reallink = os.readlink(file)
if reallink then
symrefs[reallink] = file
end
end
end
end
local found = false
for _, file in ipairs(libfiles) do
if file:endswith(".lib") or file:endswith(".a") then
found = true
table.insert(links, target.linkname(path.filename(file), {plat = opt.plat}))
end
end
if not found then
for _, file in ipairs(libfiles) do
-- if this library file has been referenced (libfoo.so.1), e.g. libfoo.so -> libfoo.so.1,
-- we need ignore it and only use -lfoo
local filename = path.filename(file)
if not symrefs[filename] then
if file:endswith(".so") or file:match(".+%.so%..+$") or file:endswith(".dylib") then
table.insert(links, target.linkname(path.filename(file), {plat = opt.plat}))
end
end
end
end
end
if #links > 0 then
for _, libdir in ipairs(vars.linkdirs or "lib") do
table.insert(linkdirs, path.join(installdir, libdir))
end
end
-- get libfiles
local libfiles = {}
for _, libdir in ipairs(vars.linkdirs or "lib") do
for _, file in ipairs(os.files(path.join(installdir, libdir, "*"))) do
if file:endswith(".lib") or file:endswith(".a") then
result.static = true
table.insert(libfiles, file)
end
end
for _, file in ipairs(os.files(path.join(installdir, libdir, "*"))) do
if file:endswith(".so") or file:match(".+%.so%..+$") or file:endswith(".dylib") or file:endswith("*.dll") then
result.shared = true
table.insert(libfiles, file)
end
end
end
if opt.plat == "windows" or opt.plat == "mingw" then
local bindirs = opt.bindirs or "bin"
for _, bindir in ipairs(bindirs) do
for _, file in ipairs(os.files(path.join(installdir, bindir, "*.dll"))) do
result.shared = true
table.insert(libfiles, file)
end
end
-- @see https://github.com/xmake-io/xmake/issues/5325#issuecomment-2242513463
if not result.shared then
for _, file in ipairs(os.files(path.join(installdir, "**.dll"))) do
result.shared = true
table.insert(libfiles, file)
end
end
end
-- add root link directories
if #linkdirs == 0 then
table.insert(linkdirs, path.join(installdir, "lib"))
end
-- uses name as links directly e.g. libname.a
if #links == 0 then
links = table.wrap(name)
end
-- find library
for _, link in ipairs(links) do
local libinfo = find_library(link, linkdirs, {plat = opt.plat})
if libinfo then
if libinfo.kind == "shared" then
result.shared = true
end
if libinfo.kind == "static" then
result.static = true
end
result.links = table.join(result.links or {}, libinfo.link)
result.linkdirs = table.join(result.linkdirs or {}, libinfo.linkdir)
result.libfiles = table.join(result.libfiles or {}, path.join(libinfo.linkdir, libinfo.filename))
end
end
if result.libfiles then
result.libfiles = table.join(result.libfiles, libfiles)
end
-- inherit the other prefix variables
local components_base = {includedirs = table.clone(result.includedirs), linkdirs = table.clone(result.linkdirs)}
for name, values in pairs(vars) do
if name ~= "links" and name ~= "linkdirs" and name ~= "includedirs" then
result[name] = values
components_base[name] = table.clone(values)
end
end
-- get component values
if components and manifest.components then
local vars = manifest.components.vars
if vars then
_deduplicate_values(components_base)
result.components = result.components or {}
result.components.__base = components_base
for _, component_name in ipairs(components) do
local comp = vars[component_name]
if comp then
result.components[component_name] = comp
-- merge component values to root
for k, v in pairs(comp) do
if k ~= "links" then
result[k] = table.join(result[k] or {}, v)
end
end
end
end
end
end
-- deduplicate result
_deduplicate_values(result)
-- update the project references file
local projectdir = os.projectdir()
if projectdir and os.isdir(projectdir) then
local references_file = path.join(installdir, "references.txt")
local references = os.isfile(references_file) and io.load(references_file) or {}
references[projectdir] = os.date("%y%m%d")
io.save(references_file, references)
end
-- get version and license
result.version = manifest.version or path.filename(path.directory(path.directory(manifest_file)))
result.license = manifest.license
result.extras = manifest.extras
return result
end
-- find package from the package directories
function _find_package_from_packagedirs(name, opt)
-- get package path (e.g. name.pkg) in the package directories
local packagepath = nil
for _, dir in ipairs(table.wrap(opt.packagedirs)) do
local p = path.join(dir, name .. ".pkg")
if os.isdir(p) then
packagepath = p
break
end
end
if not packagepath then
return
end
-- get package file (e.g. name.pkg/xmake.lua)
local packagefile = path.join(packagepath, "xmake.lua")
if not os.isfile(packagefile) then
return
end
-- init interpreter
local interp = option.interpreter()
-- register filter handler
interp:filter():register("find_package", function (variable)
local maps = {
arch = opt.arch
, plat = opt.plat
, mode = opt.mode
}
return maps[variable]
end)
-- load script
local ok, errors = interp:load(packagefile)
if not ok then
raise(errors)
end
-- load the package from the the package file
local packageinfos, errors = interp:make("option", true, true)
if not packageinfos then
raise(errors)
end
-- unregister filter handler
interp:filter():register("find_package", nil)
-- get package info
local packageinfo = packageinfos[name]
if not packageinfo then
return
end
-- get linkdirs
local linkdirs = {}
for _, linkdir in ipairs(packageinfo:get("linkdirs")) do
table.insert(linkdirs, path.join(packagepath, linkdir))
end
if #linkdirs == 0 then
return
end
-- find library
local result = nil
for _, link in ipairs(packageinfo:get("links")) do
local libinfo = find_library(link, linkdirs, {plat = opt.plat})
if libinfo then
result = result or {}
result.links = table.join(result.links or {}, libinfo.link)
result.linkdirs = table.join(result.linkdirs or {}, libinfo.linkdir)
result.libfiles = table.join(result.libfiles or {}, path.join(libinfo.linkdir, libinfo.filename))
end
end
-- inherit other package info
if result then
result.includedirs = {}
for _, includedir in ipairs(packageinfo:get("includedirs")) do
table.insert(result.includedirs, path.join(packagepath, includedir))
end
for _, infoname in ipairs({"defines", "languages", "warnings"}) do
result[infoname] = packageinfo:get(infoname)
end
end
return result
end
-- find package using the xmake package manager
--
-- @param name the package name
-- @param opt the options, e.g. {verbose = true, version = "1.12.x", buildhash = "xxxxxx")
--
function main(name, opt)
-- find package from repository
local result = _find_package_from_repo(name, opt)
-- find package from the given package directories, e.g. packagedir/xxx.pkg
if not result and opt.packagedirs then
result = _find_package_from_packagedirs(name, opt)
end
return result
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/xmake/search_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file search_package.lua
--
-- imports
import("core.base.semver")
import("core.package.package", {alias = "core_package"})
import("private.action.require.impl.repository")
-- search package from name
function _search_package_from_name(packages, name, opt)
for _, packageinfo in ipairs(repository.searchdirs(name)) do
local package = core_package.load_from_repository(packageinfo.name, packageinfo.packagedir, {repo = packageinfo.repo})
if package then
local repo = package:repo()
local version
local versions = package:versions()
if versions then
versions = table.copy(versions)
table.sort(versions, function (a, b) return semver.compare(a, b) > 0 end)
if opt.require_version then
for _, ver in ipairs(versions) do
if semver.satisfies(ver, opt.require_version) then
version = ver
end
end
else
version = versions[1]
end
end
if not opt.require_version or version then
packages[package:name()] = {name = package:name(), version = version, description = package:get("description"), reponame = repo and repo:name()}
end
end
end
end
-- search package from description
function _search_package_from_description(packages, name, opt)
for _, packageinfo in ipairs(repository.searchdirs("*")) do
if not packages[packageinfo.name] then
local package = core_package.load_from_repository(packageinfo.name, packageinfo.packagedir, {repo = packageinfo.repo})
if package then
local description = package:description()
if description and description:find(string.ipattern(name)) then
local repo = package:repo()
local version
local versions = package:versions()
if versions then
versions = table.copy(versions)
table.sort(versions, function (a, b) return semver.compare(a, b) > 0 end)
if opt.require_version then
for _, ver in ipairs(versions) do
if semver.satisfies(ver, opt.require_version) then
version = ver
end
end
else
version = versions[1]
end
end
description = description:gsub(string.ipattern(name), function (w)
return "${bright}" .. w .. "${clear}"
end)
if not opt.require_version or version then
packages[package:name()] = {name = package:name(), version = version, description = description, reponame = repo and repo:name()}
end
end
end
end
end
end
-- search package using the xmake package manager
--
-- @param name the package name with pattern
-- @param opt the options, e.g. {require_version = "1.x"}
--
function main(name, opt)
opt = opt or {}
local packages = {}
_search_package_from_name(packages, name, opt)
if opt.description ~= false then
_search_package_from_description(packages, name, opt)
end
local results = {}
for name, info in table.orderpairs(packages) do
table.insert(results, info)
end
return results
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/brew/find_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_package.lua
--
-- imports
import("lib.detect.find_tool")
import("lib.detect.find_file")
import("lib.detect.find_path")
import("lib.detect.pkgconfig")
import("core.project.target")
import("package.manager.find_package")
import("private.core.base.is_cross")
-- get the root directory of the brew packages
function _brew_pkg_rootdir()
local brew_pkg_rootdir = _g.brew_pkg_rootdir
if brew_pkg_rootdir == nil then
local brew = find_tool("brew")
if brew then
brew_pkg_rootdir = try
{
function ()
return os.iorunv(brew.program, {"--prefix"})
end
} or "/usr/local"
end
if brew_pkg_rootdir then
brew_pkg_rootdir = brew_pkg_rootdir:trim()
end
_g.brew_pkg_rootdir = brew_pkg_rootdir or false
end
return brew_pkg_rootdir or nil
end
-- find package from pkg-config
function _find_package_from_pkgconfig(name, opt)
opt = opt or {}
local brew_pkg_rootdir = opt.brew_pkg_rootdir
-- parse name, e.g. pcre/libpcre16
local nameinfo = name:split('/')
local pcname = nameinfo[2] or nameinfo[1]
-- find package from pkg-config/*.pc,
-- but we cannot find it from `brew --prefix`/package, because `brew --prefix` is too slow (> 3s) when it's not found.
local result = nil
local paths = {}
table.insert(paths, path.join(brew_pkg_rootdir, nameinfo[1], "lib/pkgconfig"))
table.insert(paths, path.join(brew_pkg_rootdir, nameinfo[1], "share/pkgconfig"))
if opt.require_version then
table.insert(paths, path.join(brew_pkg_rootdir, nameinfo[1], opt.require_version, "lib/pkgconfig"))
table.insert(paths, path.join(brew_pkg_rootdir, nameinfo[1], opt.require_version, "share/pkgconfig"))
else
table.insert(paths, path.join(brew_pkg_rootdir, nameinfo[1], "*/lib/pkgconfig"))
table.insert(paths, path.join(brew_pkg_rootdir, nameinfo[1], "*/share/pkgconfig"))
end
local pcfile = find_file(pcname .. ".pc", paths)
if pcfile then
opt.configdirs = path.directory(pcfile)
result = find_package("pkgconfig::" .. pcname, opt)
if not result or not result.includedirs then
-- attempt to get includedir variable from pkg-config/xx.pc
local varinfo = pkgconfig.variables(pcname, "includedir", opt)
if varinfo and varinfo.includedir then
result = result or {}
result.version = pkgconfig.version(pcname, opt)
result.includedirs = varinfo.includedir
end
end
end
return result
end
-- find package from the brew package manager
--
-- @param name the package name, e.g. zlib, pcre/libpcre16
-- @param opt the options, e.g. {verbose = true, version = "1.12.x")
--
function main(name, opt)
opt = opt or {}
if is_cross(opt.plat, opt.arch) then
return
end
-- find the prefix directory of brew
local brew_pkg_rootdir = _brew_pkg_rootdir()
if not brew_pkg_rootdir then
return
end
brew_pkg_rootdir = path.join(brew_pkg_rootdir, opt.plat == "macosx" and "Cellar" or "opt")
-- find package from pkg-config
local result = _find_package_from_pkgconfig(name,
table.join(opt, {brew_pkg_rootdir = brew_pkg_rootdir}))
-- find components
local components
local components_extsources = opt.components_extsources
for _, comp in ipairs(opt.components) do
local extsource = components_extsources and components_extsources[comp]
if extsource then
local component_result = _find_package_from_pkgconfig(extsource,
table.join(opt, {brew_pkg_rootdir = brew_pkg_rootdir}))
if component_result then
components = components or {}
components[comp] = component_result
end
end
end
if components then
result = result or {}
result.components = components
components.__base = {}
end
-- find package from xxx/lib, xxx/include
if not result then
local nameinfo = name:split('/')
local pkgdir
if is_host("linux") then
-- /home/linuxbrew/.linuxbrew/opt/llvm
pkgdir = find_path("lib", path.join(brew_pkg_rootdir, nameinfo[1]))
else
-- /usr/local/Cellar/llvm/16.0.6
pkgdir = find_path("lib", path.join(brew_pkg_rootdir, nameinfo[1], "*"))
end
if pkgdir then
local links = {}
for _, libfile in ipairs(os.files(path.join(pkgdir, "lib", "*.a"))) do
table.insert(links, target.linkname(path.filename(libfile), {plat = opt.plat}))
end
for _, libfile in ipairs(os.files(path.join(pkgdir, "lib", opt.plat == "macosx" and "*.dylib" or "*.so"))) do
if not os.islink(libfile) then
table.insert(links, target.linkname(path.filename(libfile), {plat = opt.plat}))
end
end
opt.links = links
opt.linkdirs = path.join(pkgdir, "lib")
opt.includedirs = path.join(pkgdir, "include")
result = find_package("system::" .. name, opt)
end
end
return result
end
|
0 | repos/xmake/xmake/modules/package/manager | repos/xmake/xmake/modules/package/manager/brew/install_package.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file install_package.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_tool")
-- install package
--
-- @param name the package name, e.g. pcre2, pcre2/libpcre2-8
-- @param opt the options, e.g. {verbose = true}
--
-- @return true or false
--
function main(name, opt)
-- find brew
local brew = find_tool("brew")
if not brew then
raise("brew not found!")
end
-- check architecture
if opt.arch ~= os.arch() then
raise("cannot install package(%s) for arch(%s)!", name, opt.arch)
end
-- init argv
local argv = {"install", name:split('/')[1]}
if opt.verbose or option.get("verbose") then
table.insert(argv, "--verbose")
end
-- install package
os.vrunv(brew.program, argv)
end
|
0 | repos/xmake/xmake/modules/package | repos/xmake/xmake/modules/package/tools/nmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file nmake.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("core.tool.toolchain")
import("lib.detect.find_tool")
-- get msvc
function _get_msvc(package)
local msvc = package:toolchain("msvc")
assert(msvc:check(), "vs not found!") -- we need to check vs envs if it has been not checked yet
return msvc
end
-- get the build environments
function buildenvs(package, opt)
return os.joinenvs(_get_msvc(package):runenvs())
end
-- do make
function make(package, argv, opt)
opt = opt or {}
local program
local runenvs = opt.envs or buildenvs(package)
local tool = find_tool("nmake", {envs = runenvs})
if tool then
program = tool.program
end
assert(program, "nmake not found!")
os.vrunv(program, argv or {}, {envs = runenvs, curdir = opt.curdir})
end
-- build package
function build(package, configs, opt)
opt = opt or {}
local argv = {}
if option.get("verbose") then
table.insert(argv, "VERBOSE=1")
end
for name, value in pairs(configs) do
value = tostring(value):trim()
if value ~= "" then
if type(name) == "number" then
table.insert(argv, value)
else
table.insert(argv, name .. "=" .. value)
end
end
end
-- do build
make(package, argv, opt)
end
-- install package
function install(package, configs, opt)
-- do build
opt = opt or {}
build(package, configs, opt)
-- do install
local argv = {"install"}
if option.get("verbose") then
table.insert(argv, "VERBOSE=1")
table.insert(argv, "V=1")
end
make(package, argv, opt)
end
|
0 | repos/xmake/xmake/modules/package | repos/xmake/xmake/modules/package/tools/msbuild.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file msbuild.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("core.project.project")
import("core.tool.toolchain")
import("lib.detect.find_tool")
import("private.utils.upgrade_vsproj")
import("private.utils.toolchain", {alias = "toolchain_utils"})
-- get the number of parallel jobs
function _get_parallel_njobs(opt)
return opt.jobs or option.get("jobs") or tostring(os.default_njob())
end
-- get msvc
function _get_msvc(package)
local msvc = package:toolchain("msvc")
assert(msvc:check(), "vs not found!") -- we need to check vs envs if it has been not checked yet
return msvc
end
-- get msvc run environments
function _get_msvc_runenvs(package)
return os.joinenvs(_get_msvc(package):runenvs())
end
-- get vs arch
function _get_vsarch(package)
local arch = package:arch()
if arch == 'x86' or arch == 'i386' then return "Win32" end
if arch == 'x86_64' then return "x64" end
if arch:startswith('arm64') then return "ARM64" end
if arch:startswith('arm') then return "ARM" end
return arch
end
-- get configs
function _get_configs(package, configs, opt)
local jobs = _get_parallel_njobs(opt)
configs = configs or {}
local configs_str = string.serialize(configs, {indent = false, strip = true})
table.insert(configs, "-nologo")
table.insert(configs, (jobs ~= nil and format("-m:%d", jobs) or "-m"))
if not configs_str:find("p:Configuration=", 1, true) then
table.insert(configs, "-p:Configuration=" .. (package:is_debug() and "Debug" or "Release"))
end
if not configs_str:find("p:Platform=", 1, true) then
table.insert(configs, "-p:Platform=" .. _get_vsarch(package))
end
if not configs_str:find("p:PlatformToolset=", 1, true) then
local vs_toolset = toolchain_utils.get_vs_toolset_ver(_get_msvc(package):config("vs_toolset") or config.get("vs_toolset"))
if vs_toolset then
table.insert(configs, "/p:PlatformToolset=" .. vs_toolset)
end
end
if project.policy("package.msbuild.multi_tool_task") or package:policy("package.msbuild.multi_tool_task") then
table.insert(configs, "/p:UseMultiToolTask=true")
table.insert(configs, "/p:EnforceProcessCountAcrossBuilds=true")
if jobs then
table.insert(configs, format("/p:MultiProcMaxCount=%d", jobs))
end
end
return configs
end
-- get the build environments
function buildenvs(package, opt)
return _get_msvc_runenvs(package)
end
-- build package
function build(package, configs, opt)
opt = opt or {}
-- pass configurations
local argv = {}
for name, value in pairs(_get_configs(package, configs, opt)) do
value = tostring(value):trim()
if value ~= "" then
if type(name) == "number" then
table.insert(argv, value)
else
table.insert(argv, name .. "=" .. value)
end
end
end
-- upgrade vs solution file?
-- @see https://github.com/xmake-io/xmake/issues/3871
if opt.upgrade then
local msvc = _get_msvc(package)
for _, value in ipairs(opt.upgrade) do
upgrade_vsproj.upgrade(value, table.join(opt, {msvc = msvc}))
end
end
-- do build
local envs = opt.envs or buildenvs(package, opt)
local msbuild = find_tool("msbuild", {envs = envs})
os.vrunv(msbuild.program, argv, {envs = envs})
end
|
0 | repos/xmake/xmake/modules/package | repos/xmake/xmake/modules/package/tools/jom.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file jom.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("core.tool.toolchain")
import("lib.detect.find_tool")
-- get the number of parallel jobs
function _get_parallel_njobs(opt)
return opt.jobs or option.get("jobs") or tostring(os.default_njob())
end
-- get msvc
function _get_msvc(package)
local msvc = package:toolchain("msvc")
assert(msvc:check(), "vs not found!") -- we need to check vs envs if it has been not checked yet
return msvc
end
-- get the build environments
function buildenvs(package, opt)
return os.joinenvs(_get_msvc(package):runenvs())
end
-- do make
function make(package, argv, opt)
opt = opt or {}
local program
local runenvs = opt.envs or buildenvs(package)
local tool = find_tool("jom", {envs = runenvs})
if tool then
program = tool.program
end
assert(program, "jom not found!")
os.vrunv(program, argv or {}, {envs = runenvs, curdir = opt.curdir})
end
-- build package
function build(package, configs, opt)
opt = opt or {}
local argv = {}
if option.get("verbose") then
table.insert(argv, "VERBOSE=1")
end
local jobs = _get_parallel_njobs(opt)
local jom_argv = {"/K"}
if jobs then
table.insert(jom_argv, "/J")
table.insert(jom_argv, tostring(jobs))
end
configs = table.join(jom_argv, configs)
for name, value in pairs(configs) do
value = tostring(value):trim()
if value ~= "" then
if type(name) == "number" then
table.insert(argv, value)
else
table.insert(argv, name .. "=" .. value)
end
end
end
-- do build
make(package, argv, opt)
end
-- install package
function install(package, configs, opt)
-- do build
opt = opt or {}
build(package, configs, opt)
-- do install
local argv = {"install"}
if option.get("verbose") then
table.insert(argv, "VERBOSE=1")
table.insert(argv, "V=1")
end
make(package, argv, opt)
end
|
0 | repos/xmake/xmake/modules/package | repos/xmake/xmake/modules/package/tools/ninja.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file ninja.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_tool")
function _default_argv(package, configs, opt)
opt = opt or {}
local buildir = opt.buildir or os.curdir()
local njob = opt.jobs or option.get("jobs") or tostring(os.default_njob())
local argv = {}
local targets = table.wrap(opt.target)
if #targets ~= 0 then
table.join2(argv, targets)
end
table.insert(argv, "-C")
table.insert(argv, buildir)
if option.get("diagnosis") then
table.insert(argv, "-v")
end
table.insert(argv, "-j")
table.insert(argv, njob)
if configs then
table.join2(argv, configs)
end
return argv
end
-- build package
function build(package, configs, opt)
opt = opt or {}
local argv = {}
local ninja = assert(find_tool("ninja"), "ninja not found!")
table.join2(argv, _default_argv(package, configs, opt))
os.vrunv(ninja.program, argv, {envs = opt.envs})
end
-- install package
function install(package, configs, opt)
opt = opt or {}
local argv = {"install"}
local ninja = assert(find_tool("ninja"), "ninja not found!")
table.join2(argv, _default_argv(package, configs, opt))
os.vrunv(ninja.program, argv, {envs = opt.envs})
end
|
0 | repos/xmake/xmake/modules/package | repos/xmake/xmake/modules/package/tools/bazel.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file bazel.lua
--
-- imports
import("core.base.option")
import("core.tool.toolchain")
import("lib.detect.find_tool")
-- get configs
function _get_configs(package, configs)
local configs = configs or {}
return configs
end
-- get the build environments
function buildenvs(package, opt)
end
-- build package
function build(package, configs, opt)
opt = opt or {}
local bazel = assert(find_tool("bazel"), "bazel not found!")
local argv = {"build"}
configs = _get_configs(package, configs)
if configs then
table.join2(argv, configs)
end
os.vrunv(bazel.program, argv, {envs = opt.envs or buildenvs(package, opt)})
end
|
0 | repos/xmake/xmake/modules/package | repos/xmake/xmake/modules/package/tools/cmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file cmake.lua
--
-- imports
import("core.base.option")
import("core.base.semver")
import("core.tool.toolchain")
import("core.project.config")
import("core.project.project")
import("lib.detect.find_file")
import("lib.detect.find_tool")
import("package.tools.ninja")
import("package.tools.msbuild")
import("detect.sdks.find_emsdk")
import("private.utils.toolchain", {alias = "toolchain_utils"})
-- get the number of parallel jobs
function _get_parallel_njobs(opt)
return opt.jobs or option.get("jobs") or tostring(os.default_njob())
end
-- translate paths
function _translate_paths(paths)
if is_host("windows") then
if type(paths) == "string" then
return (paths:gsub("\\", "/"))
elseif type(paths) == "table" then
local result = {}
for _, p in ipairs(paths) do
table.insert(result, (p:gsub("\\", "/")))
end
return result
end
end
return paths
end
-- translate bin path
function _translate_bin_path(bin_path)
if is_host("windows") and bin_path then
bin_path = bin_path:gsub("\\", "/")
if not bin_path:find(string.ipattern("%.exe$")) and
not bin_path:find(string.ipattern("%.cmd$")) and
not bin_path:find(string.ipattern("%.bat$")) then
bin_path = bin_path .. ".exe"
end
end
return bin_path
end
-- get pkg-config, we need force to find it, because package install environments will be changed
function _get_pkgconfig(package)
-- meson need fullpath pkgconfig
-- @see https://github.com/xmake-io/xmake/issues/5474
local dep = package:dep("pkgconf") or package:dep("pkg-config")
if dep then
local suffix = dep:is_plat("windows", "mingw") and ".exe" or ""
local pkgconf = path.join(dep:installdir("bin"), "pkgconf" .. suffix)
if os.isfile(pkgconf) then
return pkgconf
end
local pkgconfig = path.join(dep:installdir("bin"), "pkg-config" .. suffix)
if os.isfile(pkgconfig) then
return pkgconfig
end
end
if package:is_plat("windows") then
local pkgconf = find_tool("pkgconf", {force = true})
if pkgconf then
return pkgconf.program
end
end
local pkgconfig = find_tool("pkg-config", {force = true})
if pkgconfig then
return pkgconfig.program
end
end
-- is the toolchain compatible with the host?
function _is_toolchain_compatible_with_host(package)
for _, name in ipairs(package:config("toolchains")) do
if toolchain_utils.is_compatible_with_host(name) then
return true
end
end
end
-- get msvc
function _get_msvc(package)
local msvc = package:toolchain("msvc")
assert(msvc:check(), "vs not found!") -- we need to check vs envs if it has been not checked yet
return msvc
end
-- get msvc run environments
function _get_msvc_runenvs(package)
return os.joinenvs(_get_msvc(package):runenvs())
end
-- get cflags from package deps
function _get_cflags_from_packagedeps(package, opt)
local values
for _, depname in ipairs(opt.packagedeps) do
local dep = type(depname) ~= "string" and depname or package:dep(depname)
if dep then
local fetchinfo = dep:fetch()
if fetchinfo then
if values then
values = values .. fetchinfo
else
values = fetchinfo
end
end
end
end
-- @see https://github.com/xmake-io/xmake-repo/pull/4973#issuecomment-2295890196
local result = {}
if values then
if values.defines then
table.join2(result, toolchain_utils.map_compflags_for_package(package, "cxx", "define", values.defines))
end
if values.includedirs then
table.join2(result, _translate_paths(toolchain_utils.map_compflags_for_package(package, "cxx", "includedir", values.includedirs)))
end
if values.sysincludedirs then
table.join2(result, _translate_paths(toolchain_utils.map_compflags_for_package(package, "cxx", "sysincludedir", values.sysincludedirs)))
end
end
return result
end
-- get ldflags from package deps
function _get_ldflags_from_packagedeps(package, opt)
local values
for _, depname in ipairs(opt.packagedeps) do
local dep = type(depname) ~= "string" and depname or package:dep(depname)
if dep then
local fetchinfo = dep:fetch()
if fetchinfo then
if values then
values = values .. fetchinfo
else
values = fetchinfo
end
end
end
end
local result = {}
if values then
if values.linkdirs then
table.join2(result, _translate_paths(toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "linkdir", values.linkdirs)))
end
if values.links then
table.join2(result, toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "link", values.links))
end
if values.syslinks then
table.join2(result, _translate_paths(toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "syslink", values.syslinks)))
end
if values.frameworks then
table.join2(result, toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "framework", values.frameworks))
end
end
return result
end
-- get cflags
function _get_cflags(package, opt)
opt = opt or {}
local result = {}
if opt.cross then
table.join2(result, package:build_getenv("cflags"))
table.join2(result, package:build_getenv("cxflags"))
table.join2(result, toolchain_utils.map_compflags_for_package(package, "c", "define", package:build_getenv("defines")))
table.join2(result, toolchain_utils.map_compflags_for_package(package, "c", "includedir", package:build_getenv("includedirs")))
table.join2(result, toolchain_utils.map_compflags_for_package(package, "c", "sysincludedir", package:build_getenv("sysincludedirs")))
end
table.join2(result, package:config("cflags"))
table.join2(result, package:config("cxflags"))
if opt.cflags then
table.join2(result, opt.cflags)
end
if opt.cxflags then
table.join2(result, opt.cxflags)
end
if package:config("lto") then
table.join2(result, package:_generate_lto_configs("cc").cflags)
end
if package:config("asan") then
table.join2(result, package:_generate_sanitizer_configs("address", "cc").cflags)
end
table.join2(result, _get_cflags_from_packagedeps(package, opt))
if #result > 0 then
return os.args(_translate_paths(result))
end
end
-- get cxxflags
function _get_cxxflags(package, opt)
opt = opt or {}
local result = {}
if opt.cross then
table.join2(result, package:build_getenv("cxxflags"))
table.join2(result, package:build_getenv("cxflags"))
table.join2(result, toolchain_utils.map_compflags_for_package(package, "cxx", "define", package:build_getenv("defines")))
table.join2(result, toolchain_utils.map_compflags_for_package(package, "cxx", "includedir", package:build_getenv("includedirs")))
table.join2(result, toolchain_utils.map_compflags_for_package(package, "cxx", "sysincludedir", package:build_getenv("sysincludedirs")))
end
table.join2(result, package:config("cxxflags"))
table.join2(result, package:config("cxflags"))
if opt.cxxflags then
table.join2(result, opt.cflags)
end
if opt.cxflags then
table.join2(result, opt.cxflags)
end
if package:config("lto") then
table.join2(result, package:_generate_lto_configs("cxx").cxxflags)
end
if package:config("asan") then
table.join2(result, package:_generate_sanitizer_configs("address", "cxx").cxxflags)
end
table.join2(result, _get_cflags_from_packagedeps(package, opt))
if #result > 0 then
return os.args(_translate_paths(result))
end
end
-- get asflags
function _get_asflags(package, opt)
opt = opt or {}
local result = {}
if opt.cross then
table.join2(result, package:build_getenv("asflags"))
table.join2(result, toolchain_utils.map_compflags_for_package(package, "as", "define", package:build_getenv("defines")))
table.join2(result, toolchain_utils.map_compflags_for_package(package, "as", "includedir", package:build_getenv("includedirs")))
table.join2(result, toolchain_utils.map_compflags_for_package(package, "as", "sysincludedir", package:build_getenv("sysincludedirs")))
end
table.join2(result, package:config("asflags"))
if opt.asflags then
table.join2(result, opt.asflags)
end
if #result > 0 then
return os.args(_translate_paths(result))
end
end
-- get ldflags
function _get_ldflags(package, opt)
opt = opt or {}
local result = {}
if opt.cross then
table.join2(result, package:build_getenv("ldflags"))
table.join2(result, toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "link", package:build_getenv("links")))
table.join2(result, toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "syslink", package:build_getenv("syslinks")))
table.join2(result, toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "linkdir", package:build_getenv("linkdirs")))
end
table.join2(result, package:config("ldflags"))
if package:config("lto") then
table.join2(result, package:_generate_lto_configs().ldflags)
end
if package:config("asan") then
table.join2(result, package:_generate_sanitizer_configs("address").ldflags)
end
table.join2(result, _get_ldflags_from_packagedeps(package, opt))
if opt.ldflags then
table.join2(result, opt.ldflags)
end
if #result > 0 then
return os.args(_translate_paths(result))
end
end
-- get shflags
function _get_shflags(package, opt)
opt = opt or {}
local result = {}
if opt.cross then
table.join2(result, package:build_getenv("shflags"))
table.join2(result, toolchain_utils.map_linkflags_for_package(package, "shared", {"cxx"}, "link", package:build_getenv("links")))
table.join2(result, toolchain_utils.map_linkflags_for_package(package, "shared", {"cxx"}, "syslink", package:build_getenv("syslinks")))
table.join2(result, toolchain_utils.map_linkflags_for_package(package, "shared", {"cxx"}, "linkdir", package:build_getenv("linkdirs")))
end
table.join2(result, package:config("shflags"))
if package:config("lto") then
table.join2(result, package:_generate_lto_configs().shflags)
end
if package:config("asan") then
table.join2(result, package:_generate_sanitizer_configs("address").shflags)
end
table.join2(result, _get_ldflags_from_packagedeps(package, opt))
if opt.shflags then
table.join2(result, opt.shflags)
end
if #result > 0 then
return os.args(_translate_paths(result))
end
end
-- get cmake version
function _get_cmake_version()
local cmake_version = _g.cmake_version
if not cmake_version then
local cmake = find_tool("cmake", {version = true})
if cmake and cmake.version then
cmake_version = semver.new(cmake.version)
end
_g.cmake_version = cmake_version
end
return cmake_version
end
function _get_cmake_system_processor(package)
-- on Windows, CMAKE_SYSTEM_PROCESSOR comes from PROCESSOR_ARCHITECTURE
-- on other systems it's the output of uname -m
if package:is_plat("windows") then
local archs = {
x86 = "x86",
x64 = "AMD64",
x86_64 = "AMD64",
arm = "ARM",
arm64 = "ARM64",
arm64ec = "ARM64EC"
}
return archs[package:arch()] or package:arch()
end
return package:arch()
end
-- get mingw32 make
function _get_mingw32_make(package)
local mingw = package:build_getenv("mingw") or package:build_getenv("sdk")
if mingw then
local mingw_make = _translate_bin_path(path.join(mingw, "bin", "mingw32-make.exe"))
if os.isfile(mingw_make) then
return mingw_make
end
end
end
-- get ninja
function _get_ninja(package)
local ninja = find_tool("ninja")
if ninja then
return ninja.program
end
end
-- https://github.com/xmake-io/xmake-repo/pull/1096
function _fix_cxx_compiler_cmake(package, envs)
local cxx = envs.CMAKE_CXX_COMPILER
if cxx and package:has_tool("cxx", "clang", "gcc") then
local dir = path.directory(cxx)
local name = path.filename(cxx)
name = name:gsub("clang$", "clang++")
name = name:gsub("clang%-", "clang++-")
name = name:gsub("clang%.", "clang++.")
name = name:gsub("gcc$", "g++")
name = name:gsub("gcc%-", "g++-")
name = name:gsub("gcc%.", "g++.")
if dir and dir ~= "." then
cxx = path.join(dir, name)
else
cxx = name
end
envs.CMAKE_CXX_COMPILER = _translate_bin_path(cxx)
end
end
-- insert configs from envs
function _insert_configs_from_envs(configs, envs, opt)
opt = opt or {}
local configs_str = opt._configs_str
for k, v in pairs(envs) do
if configs_str and configs_str:find(k, 1, true) then
-- use user custom configuration
else
table.insert(configs, "-D" .. k .. "=" .. v)
end
end
end
-- get configs for generic
function _get_configs_for_generic(package, configs, opt)
local cflags = _get_cflags(package, opt)
if cflags then
table.insert(configs, "-DCMAKE_C_FLAGS=" .. cflags)
end
local cxxflags = _get_cxxflags(package, opt)
if cxxflags then
table.insert(configs, "-DCMAKE_CXX_FLAGS=" .. cxxflags)
end
local asflags = _get_asflags(package, opt)
if asflags then
table.insert(configs, "-DCMAKE_ASM_FLAGS=" .. asflags)
end
local ldflags = _get_ldflags(package, opt)
if ldflags then
table.insert(configs, "-DCMAKE_EXE_LINKER_FLAGS=" .. ldflags)
end
local shflags = _get_shflags(package, opt)
if shflags then
table.insert(configs, "-DCMAKE_SHARED_LINKER_FLAGS=" .. shflags)
end
if package:config("pic") ~= false then
table.insert(configs, "-DCMAKE_POSITION_INDEPENDENT_CODE=ON")
end
if not package:use_external_includes() then
table.insert(configs, "-DCMAKE_NO_SYSTEM_FROM_IMPORTED=ON")
end
end
-- get configs for windows
function _get_configs_for_windows(package, configs, opt)
local cmake_generator = opt.cmake_generator
if not cmake_generator or cmake_generator:find("Visual Studio", 1, true) then
table.insert(configs, "-A")
if package:is_arch("x86", "i386") then
table.insert(configs, "Win32")
elseif package:is_arch("arm64") then
table.insert(configs, "ARM64")
elseif package:is_arch("arm64ec") then
table.insert(configs, "ARM64EC")
elseif package:is_arch("arm.*") then
table.insert(configs, "ARM")
else
table.insert(configs, "x64")
end
local vs_toolset = toolchain_utils.get_vs_toolset_ver(_get_msvc(package):config("vs_toolset") or config.get("vs_toolset"))
if vs_toolset then
table.insert(configs, "-DCMAKE_GENERATOR_TOOLSET=" .. vs_toolset)
end
end
-- use clang-cl
if package:has_tool("cc", "clang_cl") then
table.insert(configs, "-DCMAKE_C_COMPILER=" .. _translate_bin_path(package:build_getenv("cc")))
end
if package:has_tool("cxx", "clang_cl") then
table.insert(configs, "-DCMAKE_CXX_COMPILER=" .. _translate_bin_path(package:build_getenv("cxx")))
end
-- we maybe need patch `cmake_policy(SET CMP0091 NEW)` to enable this argument for some packages
-- @see https://cmake.org/cmake/help/latest/policy/CMP0091.html#policy:CMP0091
-- https://github.com/xmake-io/xmake-repo/pull/303
if package:has_runtime("MT") then
table.insert(configs, "-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded")
elseif package:has_runtime("MTd") then
table.insert(configs, "-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreadedDebug")
elseif package:has_runtime("MD") then
table.insert(configs, "-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreadedDLL")
elseif package:has_runtime("MDd") then
table.insert(configs, "-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreadedDebugDLL")
end
if not opt._configs_str:find("CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY") then
table.insert(configs, "-DCMAKE_COMPILE_PDB_OUTPUT_DIRECTORY=pdb")
end
_get_configs_for_generic(package, configs, opt)
end
-- get configs for android
-- https://developer.android.google.cn/ndk/guides/cmake
function _get_configs_for_android(package, configs, opt)
opt = opt or {}
local ndk = get_config("ndk")
if ndk and os.isdir(ndk) then
local ndk_sdkver = get_config("ndk_sdkver")
table.insert(configs, "-DCMAKE_TOOLCHAIN_FILE=" .. path.join(ndk, "build/cmake/android.toolchain.cmake"))
table.insert(configs, "-DANDROID_USE_LEGACY_TOOLCHAIN_FILE=OFF")
table.insert(configs, "-DANDROID_ABI=" .. package:arch())
if ndk_sdkver then
table.insert(configs, "-DANDROID_PLATFORM=android-" .. ndk_sdkver)
table.insert(configs, "-DANDROID_NATIVE_API_LEVEL=" .. ndk_sdkver)
end
-- https://cmake.org/cmake/help/latest/variable/CMAKE_ANDROID_STL_TYPE.html
local runtime = package:runtimes()
if runtime then
table.insert(configs, "-DCMAKE_ANDROID_STL_TYPE=" .. runtime)
end
if is_host("windows") and opt.cmake_generator ~= "Ninja" then
local make = path.join(ndk, "prebuilt", "windows-x86_64", "bin", "make.exe")
if os.isfile(make) then
table.insert(configs, "-DCMAKE_MAKE_PROGRAM=" .. make)
end
end
-- avoid find and add system include/library path
-- @see https://github.com/xmake-io/xmake/issues/2037
table.insert(configs, "-DCMAKE_FIND_ROOT_PATH_MODE_PACKAGE=BOTH")
table.insert(configs, "-DCMAKE_FIND_ROOT_PATH_MODE_LIBRARY=BOTH")
table.insert(configs, "-DCMAKE_FIND_ROOT_PATH_MODE_INCLUDE=BOTH")
table.insert(configs, "-DCMAKE_FIND_ROOT_PATH_MODE_PROGRAM=NEVER")
end
_get_configs_for_generic(package, configs, opt)
end
-- get configs for appleos
function _get_configs_for_appleos(package, configs, opt)
opt = opt or {}
local envs = {}
opt.cross = true
envs.CMAKE_C_FLAGS = _get_cflags(package, opt)
envs.CMAKE_CXX_FLAGS = _get_cxxflags(package, opt)
envs.CMAKE_ASM_FLAGS = _get_asflags(package, opt)
envs.CMAKE_STATIC_LINKER_FLAGS = table.concat(table.wrap(package:build_getenv("arflags")), ' ')
envs.CMAKE_EXE_LINKER_FLAGS = _get_ldflags(package, opt)
envs.CMAKE_SHARED_LINKER_FLAGS = _get_shflags(package, opt)
-- https://cmake.org/cmake/help/v3.17/manual/cmake-toolchains.7.html#id25
if package:is_plat("watchos") then
envs.CMAKE_SYSTEM_NAME = "watchOS"
if package:is_arch("x86_64", "i386") then
envs.CMAKE_OSX_SYSROOT = "watchsimulator"
end
elseif package:is_plat("iphoneos") then
envs.CMAKE_SYSTEM_NAME = "iOS"
if package:is_arch("x86_64", "i386") then
envs.CMAKE_OSX_SYSROOT = "iphonesimulator"
end
elseif package:is_cross() then
envs.CMAKE_SYSTEM_NAME = "Darwin"
envs.CMAKE_SYSTEM_PROCESSOR = _get_cmake_system_processor(package)
end
envs.CMAKE_OSX_ARCHITECTURES = package:arch()
envs.CMAKE_FIND_ROOT_PATH_MODE_PACKAGE = "BOTH"
envs.CMAKE_FIND_ROOT_PATH_MODE_LIBRARY = "BOTH"
envs.CMAKE_FIND_ROOT_PATH_MODE_INCLUDE = "BOTH"
envs.CMAKE_FIND_ROOT_PATH_MODE_FRAMEWORK = "BOTH"
envs.CMAKE_FIND_ROOT_PATH_MODE_PROGRAM = "NEVER"
-- avoid install bundle targets
envs.CMAKE_MACOSX_BUNDLE = "NO"
_insert_configs_from_envs(configs, envs, opt)
end
-- get configs for mingw
function _get_configs_for_mingw(package, configs, opt)
opt = opt or {}
opt.cross = true
local envs = {}
local sdkdir = package:build_getenv("mingw") or package:build_getenv("sdk")
envs.CMAKE_C_COMPILER = _translate_bin_path(package:build_getenv("cc"))
envs.CMAKE_CXX_COMPILER = _translate_bin_path(package:build_getenv("cxx"))
envs.CMAKE_ASM_COMPILER = _translate_bin_path(package:build_getenv("as"))
envs.CMAKE_AR = _translate_bin_path(package:build_getenv("ar"))
envs.CMAKE_RANLIB = _translate_bin_path(package:build_getenv("ranlib"))
envs.CMAKE_RC_COMPILER = _translate_bin_path(package:build_getenv("mrc"))
envs.CMAKE_C_FLAGS = _get_cflags(package, opt)
envs.CMAKE_CXX_FLAGS = _get_cxxflags(package, opt)
envs.CMAKE_ASM_FLAGS = _get_asflags(package, opt)
envs.CMAKE_STATIC_LINKER_FLAGS = table.concat(table.wrap(package:build_getenv("arflags")), ' ')
envs.CMAKE_EXE_LINKER_FLAGS = _get_ldflags(package, opt)
envs.CMAKE_SHARED_LINKER_FLAGS = _get_shflags(package, opt)
envs.CMAKE_SYSTEM_NAME = "Windows"
envs.CMAKE_SYSTEM_PROCESSOR = _get_cmake_system_processor(package)
-- avoid find and add system include/library path
-- @see https://github.com/xmake-io/xmake/issues/2037
envs.CMAKE_FIND_ROOT_PATH = sdkdir
envs.CMAKE_FIND_ROOT_PATH_MODE_PACKAGE = "BOTH"
envs.CMAKE_FIND_ROOT_PATH_MODE_LIBRARY = "BOTH"
envs.CMAKE_FIND_ROOT_PATH_MODE_INCLUDE = "BOTH"
envs.CMAKE_FIND_ROOT_PATH_MODE_PROGRAM = "NEVER"
-- avoid add -isysroot on macOS
envs.CMAKE_OSX_SYSROOT = ""
-- Avoid cmake to add the flags -search_paths_first and -headerpad_max_install_names on macOS
envs.HAVE_FLAG_SEARCH_PATHS_FIRST = "0"
-- CMAKE_MAKE_PROGRAM may be required for some CMakeLists.txt (libcurl)
if is_subhost("windows") and opt.cmake_generator ~= "Ninja" then
envs.CMAKE_MAKE_PROGRAM = _get_mingw32_make(package)
end
if opt.cmake_generator == "Ninja" then
envs.CMAKE_MAKE_PROGRAM = "ninja"
end
_fix_cxx_compiler_cmake(package, envs)
_insert_configs_from_envs(configs, envs, opt)
end
-- get configs for wasm
function _get_configs_for_wasm(package, configs, opt)
opt = opt or {}
local emsdk = find_emsdk()
assert(emsdk and emsdk.emscripten, "emscripten not found!")
local emscripten_cmakefile = find_file("Emscripten.cmake", path.join(emsdk.emscripten, "cmake/Modules/Platform"))
assert(emscripten_cmakefile, "Emscripten.cmake not found!")
table.insert(configs, "-DCMAKE_TOOLCHAIN_FILE=" .. emscripten_cmakefile)
if is_subhost("windows") then
if opt.cmake_generator == "Ninja" then
local ninja = _get_ninja(package)
if ninja then
table.insert(configs, "-DCMAKE_MAKE_PROGRAM=" .. ninja)
end
else
local mingw_make = _get_mingw32_make(package)
if mingw_make then
table.insert(configs, "-DCMAKE_MAKE_PROGRAM=" .. mingw_make)
end
end
end
_get_configs_for_generic(package, configs, opt)
end
-- get configs for cross
function _get_configs_for_cross(package, configs, opt)
opt = opt or {}
opt.cross = true
local envs = {}
local sdkdir = _translate_paths(package:build_getenv("sdk"))
envs.CMAKE_C_COMPILER = _translate_bin_path(package:build_getenv("cc"))
envs.CMAKE_CXX_COMPILER = _translate_bin_path(package:build_getenv("cxx"))
envs.CMAKE_ASM_COMPILER = _translate_bin_path(package:build_getenv("as"))
envs.CMAKE_AR = _translate_bin_path(package:build_getenv("ar"))
_fix_cxx_compiler_cmake(package, envs)
-- @note The link command line is set in Modules/CMake{C,CXX,Fortran}Information.cmake and defaults to using the compiler, not CMAKE_LINKER,
-- so we need to set CMAKE_CXX_LINK_EXECUTABLE to use CMAKE_LINKER as linker.
--
-- https://github.com/xmake-io/xmake-repo/pull/1039
-- https://stackoverflow.com/questions/1867745/cmake-use-a-custom-linker/25274328#25274328
-- https://github.com/xmake-io/xmake-repo/pull/2134#issuecomment-1573195810
local ld = _translate_bin_path(package:build_getenv("ld"))
if package:has_tool("ld", "gxx", "clangxx") then
envs.CMAKE_CXX_LINK_EXECUTABLE = ld .. " <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>"
end
envs.CMAKE_RANLIB = _translate_bin_path(package:build_getenv("ranlib"))
envs.CMAKE_C_FLAGS = _get_cflags(package, opt)
envs.CMAKE_CXX_FLAGS = _get_cxxflags(package, opt)
envs.CMAKE_ASM_FLAGS = _get_asflags(package, opt)
envs.CMAKE_STATIC_LINKER_FLAGS = table.concat(table.wrap(package:build_getenv("arflags")), ' ')
envs.CMAKE_EXE_LINKER_FLAGS = _get_ldflags(package, opt)
envs.CMAKE_SHARED_LINKER_FLAGS = _get_shflags(package, opt)
-- we don't need to set it as cross compilation if we just pass toolchain
-- https://github.com/xmake-io/xmake/issues/2170
if package:is_cross() then
local system_name = package:targetos() or "Linux"
if system_name == "linux" then
system_name = "Linux"
end
envs.CMAKE_SYSTEM_NAME = system_name
else
if package:config("pic") ~= false then
table.insert(configs, "-DCMAKE_POSITION_INDEPENDENT_CODE=ON")
end
end
-- avoid find and add system include/library path
-- @see https://github.com/xmake-io/xmake/issues/2037
envs.CMAKE_FIND_ROOT_PATH = sdkdir
envs.CMAKE_FIND_ROOT_PATH_MODE_PACKAGE = "BOTH"
envs.CMAKE_FIND_ROOT_PATH_MODE_LIBRARY = "BOTH"
envs.CMAKE_FIND_ROOT_PATH_MODE_INCLUDE = "BOTH"
envs.CMAKE_FIND_ROOT_PATH_MODE_PROGRAM = "NEVER"
-- avoid add -isysroot on macOS
envs.CMAKE_OSX_SYSROOT = ""
-- avoid cmake to add the flags -search_paths_first and -headerpad_max_install_names on macOS
envs.HAVE_FLAG_SEARCH_PATHS_FIRST = "0"
-- avoids finding host include/library path
envs.CMAKE_FIND_USE_CMAKE_SYSTEM_PATH = "0"
envs.CMAKE_FIND_USE_INSTALL_PREFIX = "0"
_insert_configs_from_envs(configs, envs, opt)
end
-- get configs for host toolchain
function _get_configs_for_host_toolchain(package, configs, opt)
opt = opt or {}
opt.cross = true
local envs = {}
local sdkdir = _translate_paths(package:build_getenv("sdk"))
envs.CMAKE_C_COMPILER = _translate_bin_path(package:build_getenv("cc"))
envs.CMAKE_CXX_COMPILER = _translate_bin_path(package:build_getenv("cxx"))
envs.CMAKE_ASM_COMPILER = _translate_bin_path(package:build_getenv("as"))
envs.CMAKE_RC_COMPILER = _translate_bin_path(package:build_getenv("mrc"))
envs.CMAKE_AR = _translate_bin_path(package:build_getenv("ar"))
_fix_cxx_compiler_cmake(package, envs)
-- @note The link command line is set in Modules/CMake{C,CXX,Fortran}Information.cmake and defaults to using the compiler, not CMAKE_LINKER,
-- so we need set CMAKE_CXX_LINK_EXECUTABLE to use CMAKE_LINKER as linker.
--
-- https://github.com/xmake-io/xmake-repo/pull/1039
-- https://stackoverflow.com/questions/1867745/cmake-use-a-custom-linker/25274328#25274328
-- https://github.com/xmake-io/xmake-repo/pull/2134#issuecomment-1573195810
local ld = _translate_bin_path(package:build_getenv("ld"))
if package:has_tool("ld", "gxx", "clangxx") then
envs.CMAKE_CXX_LINK_EXECUTABLE = ld .. " <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>"
end
envs.CMAKE_RANLIB = _translate_bin_path(package:build_getenv("ranlib"))
envs.CMAKE_C_FLAGS = _get_cflags(package, opt)
envs.CMAKE_CXX_FLAGS = _get_cxxflags(package, opt)
envs.CMAKE_ASM_FLAGS = _get_asflags(package, opt)
envs.CMAKE_STATIC_LINKER_FLAGS = table.concat(table.wrap(package:build_getenv("arflags")), ' ')
envs.CMAKE_EXE_LINKER_FLAGS = _get_ldflags(package, opt)
envs.CMAKE_SHARED_LINKER_FLAGS = _get_shflags(package, opt)
-- we don't need to set it as cross compilation if we just pass toolchain
-- https://github.com/xmake-io/xmake/issues/2170
if package:is_cross() then
envs.CMAKE_SYSTEM_NAME = "Linux"
else
if package:config("pic") ~= false then
table.insert(configs, "-DCMAKE_POSITION_INDEPENDENT_CODE=ON")
end
end
_insert_configs_from_envs(configs, envs, opt)
end
-- get cmake generator for msvc
function _get_cmake_generator_for_msvc(package)
local vsvers =
{
["2022"] = "17",
["2019"] = "16",
["2017"] = "15",
["2015"] = "14",
["2013"] = "12",
["2012"] = "11",
["2010"] = "10",
["2008"] = "9"
}
local vs = _get_msvc(package):config("vs") or config.get("vs")
assert(vsvers[vs], "Unknown Visual Studio version: '" .. tostring(vs) .. "' set in project.")
return "Visual Studio " .. vsvers[vs] .. " " .. vs
end
-- get configs for cmake generator
function _get_configs_for_generator(package, configs, opt)
opt = opt or {}
configs = configs or {}
local cmake_generator = opt.cmake_generator
if cmake_generator then
if cmake_generator:find("Visual Studio", 1, true) then
cmake_generator = _get_cmake_generator_for_msvc(package)
end
table.insert(configs, "-G")
table.insert(configs, cmake_generator)
if cmake_generator:find("Ninja", 1, true) then
local jobs = _get_parallel_njobs(opt)
local linkjobs = opt.linkjobs or option.get("linkjobs")
if linkjobs then
table.insert(configs, "-DCMAKE_JOB_POOL_COMPILE:STRING=compile")
table.insert(configs, "-DCMAKE_JOB_POOL_LINK:STRING=link")
table.insert(configs, ("-DCMAKE_JOB_POOLS:STRING=compile=%s;link=%s"):format(jobs, linkjobs))
end
end
elseif package:is_plat("mingw") and is_subhost("msys") then
table.insert(configs, "-G")
table.insert(configs, "MSYS Makefiles")
elseif package:is_plat("mingw") and is_subhost("windows") then
table.insert(configs, "-G")
table.insert(configs, "MinGW Makefiles")
elseif package:is_plat("windows") then
table.insert(configs, "-G")
table.insert(configs, _get_cmake_generator_for_msvc(package))
elseif package:is_plat("wasm") and is_subhost("windows") then
table.insert(configs, "-G")
table.insert(configs, "MinGW Makefiles")
else
table.insert(configs, "-G")
table.insert(configs, "Unix Makefiles")
end
end
-- get configs for installation
function _get_configs_for_install(package, configs, opt)
-- @see https://cmake.org/cmake/help/v3.14/module/GNUInstallDirs.html
-- LIBDIR: object code libraries (lib or lib64 or lib/<multiarch-tuple> on Debian)
--
table.insert(configs, "-DCMAKE_INSTALL_PREFIX=" .. package:installdir())
if not opt._configs_str:find("CMAKE_INSTALL_LIBDIR") then
table.insert(configs, "-DCMAKE_INSTALL_LIBDIR:PATH=lib")
end
end
function _get_default_flags(package, configs, buildtype, opt)
-- The default flags are different for different platforms
-- @see https://github.com/xmake-io/xmake-repo/pull/4038#issuecomment-2116489448
local cachekey = buildtype .. package:plat() .. package:arch()
local cmake_default_flags = _g.cmake_default_flags and _g.cmake_default_flags[cachekey]
if not cmake_default_flags then
local tmpdir = path.join(os.tmpdir() .. ".dir", package:name(), package:mode())
local dummy_cmakelist = path.join(tmpdir, "CMakeLists.txt")
io.writefile(dummy_cmakelist, format([[
message(STATUS "CMAKE_C_FLAGS is ${CMAKE_C_FLAGS}")
message(STATUS "CMAKE_C_FLAGS_%s is ${CMAKE_C_FLAGS_%s}")
message(STATUS "CMAKE_CXX_FLAGS is ${CMAKE_CXX_FLAGS}")
message(STATUS "CMAKE_CXX_FLAGS_%s is ${CMAKE_CXX_FLAGS_%s}")
message(STATUS "CMAKE_EXE_LINKER_FLAGS is ${CMAKE_EXE_LINKER_FLAGS}")
message(STATUS "CMAKE_EXE_LINKER_FLAGS_%s is ${CMAKE_EXE_LINKER_FLAGS_%s}")
message(STATUS "CMAKE_SHARED_LINKER_FLAGS is ${CMAKE_SHARED_LINKER_FLAGS}")
message(STATUS "CMAKE_SHARED_LINKER_FLAGS_%s is ${CMAKE_SHARED_LINKER_FLAGS_%s}")
message(STATUS "CMAKE_STATIC_LINKER_FLAGS is ${CMAKE_STATIC_LINKER_FLAGS}")
message(STATUS "CMAKE_STATIC_LINKER_FLAGS_%s is ${CMAKE_STATIC_LINKER_FLAGS_%s}")
]], buildtype, buildtype, buildtype, buildtype, buildtype, buildtype, buildtype, buildtype, buildtype, buildtype))
local runenvs = opt.envs or buildenvs(package)
local cmake = find_tool("cmake")
local _configs = table.join(configs, "-S " .. path.directory(dummy_cmakelist), "-B " .. tmpdir)
local outdata = try{ function() return os.iorunv(cmake.program, _configs, {envs = runenvs}) end}
if outdata then
cmake_default_flags = {}
cmake_default_flags.cflags = outdata:match("CMAKE_C_FLAGS is (.-)\n") or " "
cmake_default_flags.cflags = cmake_default_flags.cflags .. " " .. outdata:match(format("CMAKE_C_FLAGS_%s is (.-)\n", buildtype)):replace("/MDd", ""):replace("/MD", "")
cmake_default_flags.cxxflags = outdata:match("CMAKE_CXX_FLAGS is (.-)\n") or " "
cmake_default_flags.cxxflags = cmake_default_flags.cxxflags .. " " .. outdata:match(format("CMAKE_CXX_FLAGS_%s is (.-)\n", buildtype)):replace("/MDd", ""):replace("/MD", "")
cmake_default_flags.ldflags = outdata:match("CMAKE_EXE_LINKER_FLAGS is (.-)\n") or " "
cmake_default_flags.ldflags = cmake_default_flags.ldflags .. " " .. outdata:match(format("CMAKE_EXE_LINKER_FLAGS_%s is (.-)\n", buildtype))
cmake_default_flags.shflags = outdata:match("CMAKE_SHARED_LINKER_FLAGS is (.-)\n") or " "
cmake_default_flags.shflags = cmake_default_flags.shflags .. " " .. outdata:match(format("CMAKE_SHARED_LINKER_FLAGS_%s is (.-)\n", buildtype))
cmake_default_flags.arflags = outdata:match("CMAKE_STATIC_LINKER_FLAGS is (.-)\n") or " "
cmake_default_flags.arflags = cmake_default_flags.arflags .. " " ..outdata:match(format("CMAKE_STATIC_LINKER_FLAGS_%s is (.-)\n", buildtype))
_g.cmake_default_flags = _g.cmake_default_flags or {}
_g.cmake_default_flags[cachekey] = cmake_default_flags
end
os.rm(tmpdir)
end
return cmake_default_flags
end
function _get_cmake_buildtype(package)
local cmake_buildtype_map = {
debug = "DEBUG",
release = "RELEASE",
releasedbg = "RELWITHDEBINFO"
}
local buildtype = package:mode()
return cmake_buildtype_map[buildtype] or "RELEASE"
end
function _get_envs_for_default_flags(package, configs, opt)
local buildtype = _get_cmake_buildtype(package)
local envs = {}
local default_flags = _get_default_flags(package, configs, buildtype, opt)
if default_flags then
if not opt.cxxflags and not opt.cxflags then
envs[format("CMAKE_CXX_FLAGS_%s", buildtype)] = default_flags.cxxflags
end
if not opt.cflags and not opt.cxflags then
envs[format("CMAKE_C_FLAGS_%s", buildtype)] = default_flags.cflags
end
if not opt.ldflags then
envs[format("CMAKE_EXE_LINKER_FLAGS_%s", buildtype)] = default_flags.ldflags
end
if not opt.arflags then
envs[format("CMAKE_STATIC_LINKER_FLAGS_%s", buildtype)] = default_flags.arflags
end
if not opt.shflags then
envs[format("CMAKE_SHARED_LINKER_FLAGS_%s", buildtype)] = default_flags.shflags
end
end
return envs
end
function _get_envs_for_runtime_flags(package, configs, opt)
local buildtype = _get_cmake_buildtype(package)
local envs = {}
local runtimes = package:runtimes()
if runtimes then
envs[format("CMAKE_C_FLAGS_%s", buildtype)] = toolchain_utils.map_compflags_for_package(package, "c", "runtime", runtimes)
envs[format("CMAKE_CXX_FLAGS_%s", buildtype)] = toolchain_utils.map_compflags_for_package(package, "cxx", "runtime", runtimes)
envs[format("CMAKE_EXE_LINKER_FLAGS_%s", buildtype)] = toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "runtime", runtimes)
envs[format("CMAKE_STATIC_LINKER_FLAGS_%s", buildtype)] = toolchain_utils.map_linkflags_for_package(package, "static", {"cxx"}, "runtime", runtimes)
envs[format("CMAKE_SHARED_LINKER_FLAGS_%s", buildtype)] = toolchain_utils.map_linkflags_for_package(package, "shared", {"cxx"}, "runtime", runtimes)
end
return envs
end
function _get_configs(package, configs, opt)
configs = configs or {}
opt._configs_str = string.serialize(configs, {indent = false, strip = true})
_get_configs_for_install(package, configs, opt)
_get_configs_for_generator(package, configs, opt)
if package:is_plat("windows") then
_get_configs_for_windows(package, configs, opt)
elseif package:is_plat("android") then
_get_configs_for_android(package, configs, opt)
elseif package:is_plat("iphoneos", "watchos") or
-- for cross-compilation on macOS, @see https://github.com/xmake-io/xmake/issues/2804
(package:is_plat("macosx") and (get_config("appledev") or not package:is_arch(os.subarch()))) then
_get_configs_for_appleos(package, configs, opt)
elseif package:is_plat("mingw") then
_get_configs_for_mingw(package, configs, opt)
elseif package:is_plat("wasm") then
_get_configs_for_wasm(package, configs, opt)
elseif package:is_cross() then
_get_configs_for_cross(package, configs, opt)
elseif package:config("toolchains") then
-- we still need find system libraries,
-- it just pass toolchain environments if the toolchain is compatible with host
if _is_toolchain_compatible_with_host(package) then
_get_configs_for_host_toolchain(package, configs, opt)
else
_get_configs_for_cross(package, configs, opt)
end
else
_get_configs_for_generic(package, configs, opt)
end
local envs = _get_envs_for_default_flags(package, configs, opt)
local runtime_envs = _get_envs_for_runtime_flags(package, configs, opt)
if runtime_envs then
envs = envs or {}
for name, value in pairs(runtime_envs) do
envs[name] = (envs[name] or " ") .. " " .. table.concat(value, " ")
end
end
_insert_configs_from_envs(configs, envs or {}, opt)
return configs
end
-- Fix pdb issue, if multiple CL.EXE write to the same .PDB file, please use /FS
-- @see https://github.com/xmake-io/xmake/issues/5353
function _fix_pdbdir_for_ninja(package)
if package:is_plat("windows") and package:has_tool("cxx", "cl") then
local pdbdir = "pdb"
if not os.isdir(pdbdir) then
os.mkdir(pdbdir)
end
end
end
-- enter build directory
function _enter_buildir(package, opt)
local buildir = opt.buildir or package:buildir()
os.mkdir(path.join(buildir, "install"))
return os.cd(buildir)
end
-- get build environments
function buildenvs(package, opt)
-- we need to bind msvc environments manually
-- @see https://github.com/xmake-io/xmake/issues/1057
opt = opt or {}
local envs = {}
if package:is_plat("windows") then
envs = _get_msvc_runenvs(package)
end
-- we need to pass pkgconf for windows/mingw without msys2/cygwin
if package:is_plat("windows", "mingw") and is_subhost("windows") then
local pkgconf = _get_pkgconfig(package)
if pkgconf then
envs.PKG_CONFIG = pkgconf
end
end
-- add environments for cmake/find_packages
-- and we need also find them from private libraries,
-- @see https://github.com/xmake-io/xmake-repo/pull/2553
local CMAKE_LIBRARY_PATH = {}
local CMAKE_INCLUDE_PATH = {}
local CMAKE_PREFIX_PATH = {}
local PKG_CONFIG_PATH = {}
for _, dep in ipairs(package:librarydeps({private = true})) do
if dep:is_system() then
local fetchinfo = dep:fetch()
if fetchinfo then
table.join2(CMAKE_LIBRARY_PATH, fetchinfo.linkdirs)
table.join2(CMAKE_INCLUDE_PATH, fetchinfo.includedirs)
table.join2(CMAKE_INCLUDE_PATH, fetchinfo.sysincludedirs)
end
else
table.join2(CMAKE_PREFIX_PATH, dep:installdir())
local pkgconfig = path.join(dep:installdir(), "lib", "pkgconfig")
if os.isdir(pkgconfig) then
table.insert(PKG_CONFIG_PATH, pkgconfig)
end
pkgconfig = path.join(dep:installdir(), "share", "pkgconfig")
if os.isdir(pkgconfig) then
table.insert(PKG_CONFIG_PATH, pkgconfig)
end
end
end
envs.CMAKE_LIBRARY_PATH = path.joinenv(CMAKE_LIBRARY_PATH)
envs.CMAKE_INCLUDE_PATH = path.joinenv(CMAKE_INCLUDE_PATH)
envs.CMAKE_PREFIX_PATH = path.joinenv(CMAKE_PREFIX_PATH)
envs.PKG_CONFIG_PATH = path.joinenv(PKG_CONFIG_PATH)
return envs
end
-- do build for msvc
function _build_for_msvc(package, configs, opt)
local allbuild = os.isfile("ALL_BUILD.vcxproj") and "ALL_BUILD.vcxproj" or "ALL_BUILD.vcproj"
assert(os.isfile(allbuild), "ALL_BUILD project not found!")
msbuild.build(package, {allbuild, "-t:Rebuild"})
end
-- do build for make
function _build_for_make(package, configs, opt)
local argv = {}
local targets = table.wrap(opt.target)
if #targets ~= 0 then
table.join2(argv, targets)
end
local jobs = _get_parallel_njobs(opt)
table.insert(argv, "-j" .. jobs)
if option.get("diagnosis") then
table.insert(argv, "VERBOSE=1")
end
if is_host("bsd") then
os.vrunv("gmake", argv)
elseif is_subhost("windows") and package:is_plat("mingw") then
local mingw_make = assert(_get_mingw32_make(package), "mingw32-make.exe not found!")
os.vrunv(mingw_make, argv)
elseif package:is_plat("android") and is_host("windows") then
local make
local ndk = get_config("ndk")
if ndk then
make = path.join(ndk, "prebuilt", "windows-x86_64", "bin", "make.exe")
end
if not make or not os.isfile(make) then
make = "make"
end
os.vrunv(make, argv)
else
os.vrunv("make", argv)
end
end
-- do build for ninja
function _build_for_ninja(package, configs, opt)
opt = opt or {}
_fix_pdbdir_for_ninja(package)
ninja.build(package, {}, {envs = opt.envs or buildenvs(package, opt),
jobs = opt.jobs,
target = opt.target})
end
-- do build for cmake/build
function _build_for_cmakebuild(package, configs, opt)
local cmake = assert(find_tool("cmake"), "cmake not found!")
local argv = {"--build", os.curdir()}
if opt.config then
table.insert(argv, "--config")
table.insert(argv, opt.config)
end
local targets = table.wrap(opt.target)
if #targets ~= 0 then
table.insert(argv, "--target")
if #targets > 1 then
-- https://stackoverflow.com/questions/47553569/how-can-i-build-multiple-targets-using-cmake-build
if _get_cmake_version():ge("3.15") then
table.join2(argv, targets)
else
raise("Build multiple targets need cmake >=3.15")
end
else
table.insert(argv, targets[1])
end
end
os.vrunv(cmake.program, argv, {envs = opt.envs or buildenvs(package)})
end
-- do install for msvc
function _install_for_msvc(package, configs, opt)
local allbuild = os.isfile("ALL_BUILD.vcxproj") and "ALL_BUILD.vcxproj" or "ALL_BUILD.vcproj"
assert(os.isfile(allbuild), "ALL_BUILD project not found!")
msbuild.build(package, {allbuild, "-t:Rebuild", "/nr:false"})
local projfile = os.isfile("INSTALL.vcxproj") and "INSTALL.vcxproj" or "INSTALL.vcproj"
if os.isfile(projfile) then
msbuild.build(package, {projfile})
os.trycp("install/bin", package:installdir())
os.trycp("install/lib", package:installdir()) -- perhaps only headers library
os.trycp("install/share", package:installdir())
os.trycp("install/include", package:installdir())
else
os.trycp("**.dll", package:installdir("bin"))
os.trycp("**.lib", package:installdir("lib"))
os.trycp("**.exp", package:installdir("lib"))
if package:config("shared") or not package:is_library() then
os.trycp("**.pdb", package:installdir("bin"))
else
os.trycp("**.pdb", package:installdir("lib"))
end
end
end
-- do install for make
function _install_for_make(package, configs, opt)
local jobs = _get_parallel_njobs(opt)
local argv = {"-j" .. jobs}
if option.get("diagnosis") then
table.insert(argv, "VERBOSE=1")
end
if is_host("bsd") then
os.vrunv("gmake", argv)
os.vrunv("gmake", {"install"})
elseif is_subhost("windows") and package:is_plat("mingw", "wasm") then
local mingw_make = assert(_get_mingw32_make(package), "mingw32-make.exe not found!")
os.vrunv(mingw_make, argv)
os.vrunv(mingw_make, {"install"})
elseif package:is_plat("android") and is_host("windows") then
local make
local ndk = get_config("ndk")
if ndk then
make = path.join(ndk, "prebuilt", "windows-x86_64", "bin", "make.exe")
end
if not make or not os.isfile(make) then
make = "make"
end
os.vrunv(make, argv)
os.vrunv(make, {"install"})
else
os.vrunv("make", argv)
os.vrunv("make", {"install"})
end
end
-- do install for ninja
function _install_for_ninja(package, configs, opt)
opt = opt or {}
_fix_pdbdir_for_ninja(package)
ninja.install(package, {}, {envs = opt.envs or buildenvs(package, opt),
jobs = opt.jobs,
target = opt.target})
end
-- do install for cmake/build
function _install_for_cmakebuild(package, configs, opt)
opt = opt or {}
local cmake = assert(find_tool("cmake"), "cmake not found!")
local argv = {"--build", os.curdir()}
if opt.config then
table.insert(argv, "--config")
table.insert(argv, opt.config)
end
os.vrunv(cmake.program, argv, {envs = opt.envs or buildenvs(package)})
os.vrunv(cmake.program, {"--install", os.curdir()})
end
-- get cmake generator
function _get_cmake_generator(package, opt)
opt = opt or {}
local cmake_generator = opt.cmake_generator
if not cmake_generator then
if project.policy("package.cmake_generator.ninja") or package:policy("package.cmake_generator.ninja") then
cmake_generator = "Ninja"
end
if not cmake_generator then
if package:has_tool("cc", "clang_cl") or package:has_tool("cxx", "clang_cl") then
cmake_generator = "Ninja"
elseif is_subhost("windows") and package:is_plat("mingw", "wasm") then
local ninja = _get_ninja(package)
if ninja then
cmake_generator = "Ninja"
end
end
end
local cmake_generator_env = os.getenv("CMAKE_GENERATOR")
if not cmake_generator and cmake_generator_env then
cmake_generator = cmake_generator_env
end
if cmake_generator then
opt.cmake_generator = cmake_generator
end
end
return cmake_generator
end
function configure(package, configs, opt)
opt = opt or {}
local oldir = _enter_buildir(package, opt)
-- pass configurations
local argv = {}
for name, value in pairs(_get_configs(package, configs, opt)) do
value = tostring(value):trim()
if type(name) == "number" then
if value ~= "" then
table.insert(argv, value)
end
else
table.insert(argv, "-D" .. name .. "=" .. value)
end
end
table.insert(argv, oldir)
-- do configure
local cmake = assert(find_tool("cmake"), "cmake not found!")
os.vrunv(cmake.program, argv, {envs = opt.envs or buildenvs(package, opt)})
os.cd(oldir)
end
-- build package
function build(package, configs, opt)
opt = opt or {}
local cmake_generator = _get_cmake_generator(package, opt)
-- do configure
configure(package, configs, opt)
-- do build
local oldir = _enter_buildir(package, opt)
if opt.cmake_build then
_build_for_cmakebuild(package, configs, opt)
elseif cmake_generator then
if cmake_generator:find("Visual Studio", 1, true) then
_build_for_msvc(package, configs, opt)
elseif cmake_generator == "Ninja" then
_build_for_ninja(package, configs, opt)
elseif cmake_generator:find("Makefiles", 1, true) then
_build_for_make(package, configs, opt)
else
raise("unknown cmake generator(%s)!", cmake_generator)
end
else
if package:is_plat("windows") then
_build_for_msvc(package, configs, opt)
else
_build_for_make(package, configs, opt)
end
end
os.cd(oldir)
end
-- install package
function install(package, configs, opt)
opt = opt or {}
local cmake_generator = _get_cmake_generator(package, opt)
-- do configure
configure(package, configs, opt)
-- do build and install
local oldir = _enter_buildir(package, opt)
if opt.cmake_build then
_install_for_cmakebuild(package, configs, opt)
elseif cmake_generator then
if cmake_generator:find("Visual Studio", 1, true) then
_install_for_msvc(package, configs, opt)
elseif cmake_generator == "Ninja" then
_install_for_ninja(package, configs, opt)
elseif cmake_generator:find("Makefiles", 1, true) then
_install_for_make(package, configs, opt)
else
raise("unknown cmake generator(%s)!", cmake_generator)
end
else
if package:is_plat("windows") then
_install_for_msvc(package, configs, opt)
else
_install_for_make(package, configs, opt)
end
end
if package:is_plat("windows") and os.isdir("pdb") then
if package:config("shared") or not package:is_library() then
os.trycp("pdb/**.pdb", package:installdir("bin"))
else
os.trycp("pdb/**.pdb", package:installdir("lib"))
end
end
os.cd(oldir)
end
|
0 | repos/xmake/xmake/modules/package | repos/xmake/xmake/modules/package/tools/make.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file make.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("lib.detect.find_tool")
import("private.utils.toolchain", {alias = "toolchain_utils"})
-- translate bin path
function _translate_bin_path(bin_path)
if is_host("windows") and bin_path then
return bin_path:gsub("\\", "/") .. ".exe"
end
return bin_path
end
-- get the build environments
function buildenvs(package)
local envs = {}
local cflags = table.join(table.wrap(package:build_getenv("cxflags")), package:build_getenv("cflags"))
local cxxflags = table.join(table.wrap(package:build_getenv("cxflags")), package:build_getenv("cxxflags"))
local asflags = table.copy(table.wrap(package:config("asflags")))
local ldflags = table.copy(table.wrap(package:config("ldflags")))
local shflags = table.copy(table.wrap(package:config("shflags")))
local runtimes = package:runtimes()
if runtimes then
table.join2(cxxflags, toolchain_utils.map_compflags_for_package(package, "cxx", "runtime", runtimes))
table.join2(ldflags, toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "runtime", runtimes))
table.join2(shflags, toolchain_utils.map_linkflags_for_package(package, "shared", {"cxx"}, "runtime", runtimes))
end
if package:is_plat(os.host()) then
if package:is_plat("linux") and package:is_arch("i386") then
table.insert(cflags, "-m32")
table.insert(cxxflags, "-m32")
table.insert(asflags, "-m32")
table.insert(ldflags, "-m32")
end
envs.CFLAGS = table.concat(cflags, ' ')
envs.CXXFLAGS = table.concat(cxxflags, ' ')
envs.ASFLAGS = table.concat(asflags, ' ')
envs.LDFLAGS = table.concat(ldflags, ' ')
envs.SHFLAGS = table.concat(shflags, ' ')
else
envs.CC = _translate_bin_path(package:build_getenv("cc"))
envs.CXX = _translate_bin_path(package:build_getenv("cxx"))
envs.AS = _translate_bin_path(package:build_getenv("as"))
envs.AR = _translate_bin_path(package:build_getenv("ar"))
envs.LD = _translate_bin_path(package:build_getenv("ld"))
envs.LDSHARED = _translate_bin_path(package:build_getenv("sh"))
envs.CPP = _translate_bin_path(package:build_getenv("cpp"))
envs.RANLIB = _translate_bin_path(package:build_getenv("ranlib"))
envs.CFLAGS = table.concat(cflags, ' ')
envs.CXXFLAGS = table.concat(cxxflags, ' ')
envs.ASFLAGS = table.concat(asflags, ' ')
envs.ARFLAGS = table.concat(table.wrap(package:build_getenv("arflags")), ' ')
envs.LDFLAGS = table.concat(ldflags, ' ')
envs.SHFLAGS = table.concat(shflags, ' ')
end
local ACLOCAL_PATH = {}
local PKG_CONFIG_PATH = {}
for _, dep in ipairs(package:librarydeps({private = true})) do
local pkgconfig = path.join(dep:installdir(), "lib", "pkgconfig")
if os.isdir(pkgconfig) then
table.insert(PKG_CONFIG_PATH, pkgconfig)
end
pkgconfig = path.join(dep:installdir(), "share", "pkgconfig")
if os.isdir(pkgconfig) then
table.insert(PKG_CONFIG_PATH, pkgconfig)
end
end
-- some binary packages contain it too. e.g. libtool
for _, dep in ipairs(package:orderdeps()) do
local aclocal = path.join(dep:installdir(), "share", "aclocal")
if os.isdir(aclocal) then
table.insert(ACLOCAL_PATH, aclocal)
end
end
envs.ACLOCAL_PATH = path.joinenv(ACLOCAL_PATH)
envs.PKG_CONFIG_PATH = path.joinenv(PKG_CONFIG_PATH)
-- some Makefile use ComSpec to detect Windows (e.g. Makefiles generated by Premake) and require this env
if is_subhost("windows") then
envs.ComSpec = os.getenv("ComSpec")
end
return envs
end
-- do make
function make(package, argv, opt)
opt = opt or {}
local program
local runenvs = opt.envs or buildenvs(package)
if package:is_plat("mingw") and is_subhost("windows") then
local mingw = assert(package:build_getenv("mingw") or package:build_getenv("sdk"), "mingw not found!")
program = path.join(mingw, "bin", "mingw32-make.exe")
else
local tool = find_tool("make", {envs = runenvs})
if tool then
program = tool.program
end
end
assert(program, "make not found!")
os.vrunv(program, argv or {}, {envs = runenvs, curdir = opt.curdir})
end
-- build package
function build(package, configs, opt)
opt = opt or {}
-- pass configurations
local njob = opt.jobs or option.get("jobs") or tostring(os.default_njob())
local argv = {"-j" .. njob}
if option.get("verbose") then
table.insert(argv, "VERBOSE=1")
table.insert(argv, "V=1")
end
for name, value in pairs(configs) do
value = tostring(value):trim()
if value ~= "" then
if type(name) == "number" then
table.insert(argv, value)
else
table.insert(argv, name .. "=" .. value)
end
end
end
-- do build
make(package, argv, opt)
end
-- install package
function install(package, configs, opt)
-- do build
opt = opt or {}
build(package, configs, opt)
-- do install
local argv = {"install"}
if option.get("verbose") then
table.insert(argv, "VERBOSE=1")
table.insert(argv, "V=1")
end
make(package, argv, opt)
end
|
0 | repos/xmake/xmake/modules/package | repos/xmake/xmake/modules/package/tools/meson.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file meson.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("core.tool.toolchain")
import("lib.detect.find_tool")
import("private.utils.executable_path")
import("private.utils.toolchain", {alias = "toolchain_utils"})
-- get build directory
function _get_buildir(package, opt)
if opt and opt.buildir then
return opt.buildir
else
_g.buildir = _g.buildir or package:buildir()
return _g.buildir
end
end
-- get pkg-config, we need force to find it, because package install environments will be changed
function _get_pkgconfig(package)
-- meson need fullpath pkgconfig
-- @see https://github.com/xmake-io/xmake/issues/5474
local dep = package:dep("pkgconf") or package:dep("pkg-config")
if dep then
local suffix = dep:is_plat("windows", "mingw") and ".exe" or ""
local pkgconf = path.join(dep:installdir("bin"), "pkgconf" .. suffix)
if os.isfile(pkgconf) then
return pkgconf
end
local pkgconfig = path.join(dep:installdir("bin"), "pkg-config" .. suffix)
if os.isfile(pkgconfig) then
return pkgconfig
end
end
if package:is_plat("windows") then
local pkgconf = find_tool("pkgconf", {force = true})
if pkgconf then
return pkgconf.program
end
end
local pkgconfig = find_tool("pkg-config", {force = true})
if pkgconfig then
return pkgconfig.program
end
end
-- translate flags
function _translate_flags(package, flags)
if package:is_plat("android") then
local flags_new = {}
for _, flag in ipairs(flags) do
if flag:startswith("-gcc-toolchain ") or flag:startswith("-target ") or flag:startswith("-isystem ") then
table.join2(flags_new, flag:split(" ", {limit = 2}))
else
table.insert(flags_new, flag)
end
end
flags = flags_new
elseif package:is_plat("windows") then
for idx, flag in ipairs(flags) do
-- @see https://github.com/xmake-io/xmake/issues/4407
if flag:startswith("-libpath:") then
flags[idx] = flag:gsub("%-libpath:", "/libpath:")
end
end
end
return flags
end
function _insert_cross_configs(package, file, opt)
-- host machine
file:print("[host_machine]")
if opt.host_machine then
file:print("%s", opt.host_machine)
elseif package:is_plat("iphoneos", "macosx") then
local cpu
local cpu_family
if package:is_arch("arm64") then
cpu = "aarch64"
cpu_family = "aarch64"
elseif package:is_arch("armv7") then
cpu = "arm"
cpu_family = "arm"
elseif package:is_arch("x64", "x86_64") then
cpu = "x86_64"
cpu_family = "x86_64"
elseif package:is_arch("x86", "i386") then
cpu = "i686"
cpu_family = "x86"
else
raise("unsupported arch(%s)", package:arch())
end
file:print("system = 'darwin'")
file:print("cpu_family = '%s'", cpu_family)
file:print("cpu = '%s'", cpu)
file:print("endian = 'little'")
elseif package:is_plat("android") then
local cpu
local cpu_family
if package:is_arch("arm64-v8a") then
cpu = "aarch64"
cpu_family = "aarch64"
elseif package:is_arch("armeabi-v7a") then
cpu = "arm"
cpu_family = "arm"
elseif package:is_arch("x64", "x86_64") then
cpu = "x86_64"
cpu_family = "x86_64"
elseif package:is_arch("x86", "i386") then
cpu = "i686"
cpu_family = "x86"
else
raise("unsupported arch(%s)", package:arch())
end
file:print("system = 'android'")
file:print("cpu_family = '%s'", cpu_family)
file:print("cpu = '%s'", cpu)
file:print("endian = 'little'")
elseif package:is_plat("mingw") then
local cpu
local cpu_family
if package:is_arch("x64", "x86_64") then
cpu = "x86_64"
cpu_family = "x86_64"
elseif package:is_arch("x86", "i386") then
cpu = "i686"
cpu_family = "x86"
else
raise("unsupported arch(%s)", package:arch())
end
file:print("system = 'windows'")
file:print("cpu_family = '%s'", cpu_family)
file:print("cpu = '%s'", cpu)
file:print("endian = 'little'")
elseif package:is_plat("windows") then
local cpu
local cpu_family
if package:is_arch("arm64", "arm64ec") then
cpu = "aarch64"
cpu_family = "aarch64"
elseif package:is_arch("x86") then
cpu = "x86"
cpu_family = "x86"
elseif package:is_arch("x64") then
cpu = "x86_64"
cpu_family = "x86_64"
else
raise("unsupported arch(%s)", package:arch())
end
file:print("system = 'windows'")
file:print("cpu_family = '%s'", cpu_family)
file:print("cpu = '%s'", cpu)
file:print("endian = 'little'")
elseif package:is_plat("wasm") then
file:print("system = 'emscripten'")
file:print("cpu_family = 'wasm32'")
file:print("cpu = 'wasm32'")
file:print("endian = 'little'")
else
local cpu = package:arch()
if package:is_arch("arm64") or package:is_arch("aarch64") then
cpu = "aarch64"
elseif package:is_arch("arm.*") then
cpu = "arm"
end
local cpu_family = cpu
file:print("system = '%s'", package:targetos() or "linux")
file:print("cpu_family = '%s'", cpu_family)
file:print("cpu = '%s'", cpu)
file:print("endian = 'little'")
end
end
-- is the toolchain compatible with the host?
function _is_toolchain_compatible_with_host(package)
for _, name in ipairs(package:config("toolchains")) do
if toolchain_utils.is_compatible_with_host(name) then
return true
end
end
end
-- get cross file
function _get_configs_file(package, opt)
opt = opt or {}
local configsfile = path.join(_get_buildir(package, opt), "configs_file.txt")
if not os.isfile(configsfile) then
local file = io.open(configsfile, "w")
-- binaries
file:print("[binaries]")
local cc = package:build_getenv("cc")
if cc then
file:print("c=['%s']", executable_path(cc))
end
local cxx = package:build_getenv("cxx")
if cxx then
-- https://github.com/xmake-io/xmake/discussions/4979
if package:has_tool("cxx", "clang", "gcc") then
local dir = path.directory(cxx)
local name = path.filename(cxx)
name = name:gsub("clang$", "clang++")
name = name:gsub("clang%-", "clang++-") -- clang-xx
name = name:gsub("clang%.", "clang++.") -- clang.exe
name = name:gsub("gcc$", "g++")
name = name:gsub("gcc%-", "g++-")
name = name:gsub("gcc%.", "g++.")
if dir and dir ~= "." then
cxx = path.join(dir, name)
else
cxx = name
end
end
file:print("cpp=['%s']", executable_path(cxx))
end
local ld = package:build_getenv("ld")
if ld then
file:print("ld=['%s']", executable_path(ld))
end
-- we cannot pass link.exe to ar for msvc, it will raise `unknown linker`
if not package:is_plat("windows") then
local ar = package:build_getenv("ar")
if ar then
file:print("ar=['%s']", executable_path(ar))
end
end
local strip = package:build_getenv("strip")
if strip then
file:print("strip=['%s']", executable_path(strip))
end
local ranlib = package:build_getenv("ranlib")
if ranlib then
file:print("ranlib=['%s']", executable_path(ranlib))
end
if package:is_plat("mingw") then
local mrc = package:build_getenv("mrc")
if mrc then
file:print("windres=['%s']", executable_path(mrc))
end
end
local cmake = find_tool("cmake")
if cmake then
file:print("cmake=['%s']", executable_path(cmake.program))
end
local pkgconfig = _get_pkgconfig(package)
if pkgconfig then
file:print("pkgconfig=['%s']", executable_path(pkgconfig))
end
file:print("")
-- built-in options
file:print("[built-in options]")
local cflags = table.join(table.wrap(package:build_getenv("cxflags")), package:build_getenv("cflags"))
local cxxflags = table.join(table.wrap(package:build_getenv("cxflags")), package:build_getenv("cxxflags"))
local asflags = table.wrap(package:build_getenv("asflags"))
local arflags = table.wrap(package:build_getenv("arflags"))
local ldflags = table.wrap(package:build_getenv("ldflags"))
local shflags = table.wrap(package:build_getenv("shflags"))
table.join2(cflags, opt.cflags)
table.join2(cflags, opt.cxflags)
table.join2(cxxflags, opt.cxxflags)
table.join2(cxxflags, opt.cxflags)
table.join2(asflags, opt.asflags)
table.join2(ldflags, opt.ldflags)
table.join2(shflags, opt.shflags)
table.join2(cflags, _get_cflags_from_packagedeps(package, opt))
table.join2(cxxflags, _get_cflags_from_packagedeps(package, opt))
table.join2(ldflags, _get_ldflags_from_packagedeps(package, opt))
table.join2(shflags, _get_ldflags_from_packagedeps(package, opt))
-- add runtimes flags
for _, runtime in ipairs(package:runtimes()) do
if not runtime:startswith("M") then
table.join2(cxxflags, toolchain_utils.map_compflags_for_package(package, "cxx", "runtime", {runtime}))
table.join2(ldflags, toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "runtime", {runtime}))
table.join2(shflags, toolchain_utils.map_linkflags_for_package(package, "shared", {"cxx"}, "runtime", {runtime}))
end
end
if #cflags > 0 then
file:print("c_args=['%s']", table.concat(cflags, "', '"))
end
if #cxxflags > 0 then
file:print("cpp_args=['%s']", table.concat(cxxflags, "', '"))
end
local linkflags = table.join(ldflags or {}, shflags)
if #linkflags > 0 then
file:print("c_link_args=['%s']", table.concat(linkflags, "', '"))
file:print("cpp_link_args=['%s']", table.concat(linkflags, "', '"))
end
if package:is_cross() or opt.cross then
file:print("")
_insert_cross_configs(package, file, opt)
file:print("")
end
file:close()
end
return configsfile
end
-- get configs
function _get_configs(package, configs, opt)
-- add prefix
configs = configs or {}
table.insert(configs, "--prefix=" .. (opt.prefix or package:installdir()))
table.insert(configs, "--libdir=lib")
-- set build type
table.insert(configs, "-Dbuildtype=" .. (package:debug() and "debug" or "release"))
-- add -fpic
if package:is_plat("linux") and package:config("pic") ~= false then
table.insert(configs, "-Db_staticpic=true")
end
-- add lto
if package:config("lto") then
table.insert(configs, "-Db_lto=true")
end
-- add asan
if package:config("asan") then
table.insert(configs, "-Db_sanitize=address")
end
-- add vs runtimes flags
if package:is_plat("windows") then
if package:has_runtime("MT") then
table.insert(configs, "-Db_vscrt=mt")
elseif package:has_runtime("MTd") then
table.insert(configs, "-Db_vscrt=mtd")
elseif package:has_runtime("MD") then
table.insert(configs, "-Db_vscrt=md")
elseif package:has_runtime("MDd") then
table.insert(configs, "-Db_vscrt=mdd")
end
end
-- add cross file
if package:is_cross() or package:is_plat("mingw") then
table.insert(configs, "--cross-file=" .. _get_configs_file(package, opt))
elseif package:config("toolchains") then
if _is_toolchain_compatible_with_host(package) then
table.insert(configs, "--native-file=" .. _get_configs_file(package, opt))
else
table.insert(configs, "--cross-file=" .. _get_configs_file(package, table.join2(opt, {cross = true})))
end
end
-- add build directory
table.insert(configs, _get_buildir(package, opt))
return configs
end
-- get msvc
function _get_msvc(package)
local msvc = package:toolchain("msvc")
assert(msvc:check(), "vs not found!") -- we need to check vs envs if it has been not checked yet
return msvc
end
-- get msvc run environments
function _get_msvc_runenvs(package)
return os.joinenvs(_get_msvc(package):runenvs())
end
-- fix libname on windows
function _fix_libname_on_windows(package)
for _, lib in ipairs(os.files(path.join(package:installdir("lib"), "lib*.a"))) do
os.mv(lib, (lib:gsub("(.+)\\lib(.-)%.a", "%1\\%2.lib")))
end
end
-- get cflags from package deps
function _get_cflags_from_packagedeps(package, opt)
local values
for _, depname in ipairs(opt.packagedeps) do
local dep = type(depname) ~= "string" and depname or package:dep(depname)
if dep then
local fetchinfo = dep:fetch()
if fetchinfo then
if values then
values = values .. fetchinfo
else
values = fetchinfo
end
end
end
end
-- @see https://github.com/xmake-io/xmake-repo/pull/4973#issuecomment-2295890196
local result = {}
if values then
if values.defines then
table.join2(result, toolchain_utils.map_compflags_for_package(package, "cxx", "define", values.defines))
end
if values.includedirs then
table.join2(result, toolchain_utils.map_compflags_for_package(package, "cxx", "includedir", values.includedirs))
end
if values.sysincludedirs then
table.join2(result, toolchain_utils.map_compflags_for_package(package, "cxx", "sysincludedir", values.sysincludedirs))
end
end
return _translate_flags(package, result)
end
-- get ldflags from package deps
function _get_ldflags_from_packagedeps(package, opt)
local values
for _, depname in ipairs(opt.packagedeps) do
local dep = type(depname) ~= "string" and depname or package:dep(depname)
if dep then
local fetchinfo = dep:fetch()
if fetchinfo then
if values then
values = values .. fetchinfo
else
values = fetchinfo
end
end
end
end
local result = {}
if values then
if values.linkdirs then
table.join2(result, toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "linkdir", values.linkdirs))
end
if values.links then
table.join2(result, toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "link", values.links))
end
if values.syslinks then
table.join2(result, toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "syslink", values.syslinks))
end
if values.frameworks then
table.join2(result, toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "framework", values.frameworks))
end
end
return _translate_flags(package, result)
end
-- get the build environments
function buildenvs(package, opt)
local envs = {}
opt = opt or {}
if package:is_plat(os.host()) then
local cflags = table.join(table.wrap(package:config("cxflags")), package:config("cflags"))
local cxxflags = table.join(table.wrap(package:config("cxflags")), package:config("cxxflags"))
local asflags = table.wrap(package:config("asflags"))
local ldflags = table.wrap(package:config("ldflags"))
local shflags = table.wrap(package:config("shflags"))
table.join2(cflags, opt.cflags)
table.join2(cflags, opt.cxflags)
table.join2(cxxflags, opt.cxxflags)
table.join2(cxxflags, opt.cxflags)
table.join2(asflags, opt.asflags)
table.join2(ldflags, opt.ldflags)
table.join2(shflags, opt.shflags)
table.join2(cflags, _get_cflags_from_packagedeps(package, opt))
table.join2(cxxflags, _get_cflags_from_packagedeps(package, opt))
table.join2(ldflags, _get_ldflags_from_packagedeps(package, opt))
table.join2(shflags, _get_ldflags_from_packagedeps(package, opt))
envs.CFLAGS = table.concat(cflags, ' ')
envs.CXXFLAGS = table.concat(cxxflags, ' ')
envs.ASFLAGS = table.concat(asflags, ' ')
envs.LDFLAGS = table.concat(ldflags, ' ')
envs.SHFLAGS = table.concat(shflags, ' ')
if package:is_plat("windows") then
envs = os.joinenvs(envs, _get_msvc_runenvs(package))
local pkgconf = _get_pkgconfig(package)
if pkgconf then
envs.PKG_CONFIG = pkgconf
end
end
end
local ACLOCAL_PATH = {}
local PKG_CONFIG_PATH = {}
for _, dep in ipairs(package:librarydeps({private = true})) do
local pkgconfig = path.join(dep:installdir(), "lib", "pkgconfig")
if os.isdir(pkgconfig) then
table.insert(PKG_CONFIG_PATH, pkgconfig)
end
pkgconfig = path.join(dep:installdir(), "share", "pkgconfig")
if os.isdir(pkgconfig) then
table.insert(PKG_CONFIG_PATH, pkgconfig)
end
end
-- some binary packages contain it too. e.g. libtool
for _, dep in ipairs(package:orderdeps()) do
local aclocal = path.join(dep:installdir(), "share", "aclocal")
if os.isdir(aclocal) then
table.insert(ACLOCAL_PATH, aclocal)
end
end
envs.ACLOCAL_PATH = path.joinenv(ACLOCAL_PATH)
envs.PKG_CONFIG_PATH = path.joinenv(PKG_CONFIG_PATH)
return envs
end
-- generate build files for ninja
function generate(package, configs, opt)
-- init options
opt = opt or {}
-- pass configurations
-- TODO: support more backends https://mesonbuild.com/Commands.html#setup
local argv = {"setup"}
for name, value in pairs(_get_configs(package, configs, opt)) do
value = tostring(value):trim()
if value ~= "" then
if type(name) == "number" then
table.insert(argv, value)
else
table.insert(argv, "--" .. name .. "=" .. value)
end
end
end
-- do configure
local meson = assert(find_tool("meson"), "meson not found!")
os.vrunv(meson.program, argv, {envs = opt.envs or buildenvs(package, opt)})
end
-- build package
function build(package, configs, opt)
-- generate build files
opt = opt or {}
generate(package, configs, opt)
-- configurate build
local buildir = _get_buildir(package, opt)
local njob = opt.jobs or option.get("jobs") or tostring(os.default_njob())
local argv = {"compile", "-C", buildir}
if option.get("diagnosis") then
table.insert(argv, "-v")
end
table.insert(argv, "-j")
table.insert(argv, njob)
-- do build
local meson = assert(find_tool("meson"), "meson not found!")
os.vrunv(meson.program, argv, {envs = opt.envs or buildenvs(package, opt)})
end
-- install package
function install(package, configs, opt)
-- do build
opt = opt or {}
build(package, configs, opt)
-- configure install
local buildir = _get_buildir(package, opt)
local argv = {"install", "-C", buildir}
-- do install
local meson = assert(find_tool("meson"), "meson not found!")
os.vrunv(meson.program, argv, {envs = opt.envs or buildenvs(package, opt)})
-- fix static libname on windows
if package:is_plat("windows") and not package:config("shared") then
_fix_libname_on_windows(package)
end
end
|
0 | repos/xmake/xmake/modules/package | repos/xmake/xmake/modules/package/tools/xmake.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- imports
import("core.base.option")
import("core.base.global")
import("core.tool.toolchain")
import("core.project.project")
import("core.package.repository")
import("private.action.require.impl.package", {alias = "require_package"})
import("private.utils.toolchain", {alias = "toolchain_utils"})
-- get config from toolchains
function _get_config_from_toolchains(package, name)
for _, toolchain_inst in ipairs(package:toolchains()) do
local value = toolchain_inst:config(name)
if value ~= nil then
return value
end
end
end
-- is the toolchain compatible with the host?
function _is_toolchain_compatible_with_host(package)
for _, name in ipairs(package:config("toolchains")) do
if toolchain_utils.is_compatible_with_host(name) then
return true
end
end
end
-- get configs for qt
function _get_configs_for_qt(package, configs, opt)
local names = {"qt", "qt_sdkver"}
for _, name in ipairs(names) do
local value = get_config(name)
if value ~= nil then
table.insert(configs, "--" .. name .. "=" .. tostring(value))
end
end
end
-- get configs for vcpkg
function _get_configs_for_vcpkg(package, configs, opt)
local names = {"vcpkg"}
for _, name in ipairs(names) do
local value = get_config(name)
if value ~= nil then
table.insert(configs, "--" .. name .. "=" .. tostring(value))
end
end
end
-- get configs for windows
function _get_configs_for_windows(package, configs, opt)
local names = {"vs", "vs_toolset"}
for _, name in ipairs(names) do
local value = get_config(name)
if value ~= nil then
table.insert(configs, "--" .. name .. "=" .. tostring(value))
end
end
-- pass runtimes from package configs
local runtimes = package:config("runtimes")
if runtimes then
table.insert(configs, "--runtimes=" .. runtimes)
end
_get_configs_for_qt(package, configs, opt)
_get_configs_for_vcpkg(package, configs, opt)
-- we can switch some toolchains, e.g. llvm/clang
if package:config("toolchains") and _is_toolchain_compatible_with_host(package) then
_get_configs_for_host_toolchain(package, configs, opt)
end
end
-- get configs for appleos
function _get_configs_for_appleos(package, configs, opt)
local xcode = get_config("xcode")
if xcode then
table.insert(configs, "--xcode=" .. xcode)
end
local xcode_sdkver = get_config("xcode_sdkver")
if xcode_sdkver then
table.insert(configs, "--xcode_sdkver=" .. xcode_sdkver)
end
local target_minver = get_config("target_minver")
if target_minver then
table.insert(configs, "--target_minver=" .. target_minver)
end
local appledev = get_config("appledev")
if appledev then
table.insert(configs, "--appledev=" .. appledev)
end
local runtimes = package:config("runtimes")
if runtimes then
table.insert(configs, "--runtimes=" .. runtimes)
end
_get_configs_for_qt(package, configs, opt)
_get_configs_for_vcpkg(package, configs, opt)
end
-- get configs for android
function _get_configs_for_android(package, configs, opt)
local names = {"ndk", "ndk_sdkver", "ndk_stdcxx", "ndk_cxxstl"}
for _, name in ipairs(names) do
local value = get_config(name)
if value ~= nil then
table.insert(configs, "--" .. name .. "=" .. tostring(value))
end
end
_get_configs_for_qt(package, configs, opt)
_get_configs_for_vcpkg(package, configs, opt)
end
-- get configs for mingw
function _get_configs_for_mingw(package, configs, opt)
local names = {"mingw", "sdk", "ld", "sh", "ar", "cc", "cxx", "mm", "mxx"}
for _, name in ipairs(names) do
local value = get_config(name)
if value ~= nil then
table.insert(configs, "--" .. name .. "=" .. tostring(value))
end
end
local runtimes = package:config("runtimes")
if runtimes then
table.insert(configs, "--runtimes=" .. runtimes)
end
_get_configs_for_qt(package, configs, opt)
_get_configs_for_vcpkg(package, configs, opt)
end
-- get configs for generic, e.g. linux, macosx, bsd host platforms
function _get_configs_for_generic(package, configs, opt)
local names = {"ld", "sh", "ar", "cc", "cxx", "mm", "mxx"}
if package:is_plat("macosx") then
table.join2(names, "xcode", "xcode_sdkver", "target_minver", "appledev")
end
for _, name in ipairs(names) do
local value = get_config(name)
if value ~= nil then
table.insert(configs, "--" .. name .. "=" .. tostring(value))
end
end
local runtimes = package:config("runtimes")
if runtimes then
table.insert(configs, "--runtimes=" .. runtimes)
end
_get_configs_for_qt(package, configs, opt)
_get_configs_for_vcpkg(package, configs, opt)
end
-- get configs for host toolchain
function _get_configs_for_host_toolchain(package, configs, opt)
local bindir = _get_config_from_toolchains(package, "bindir") or get_config("bin")
if bindir then
table.insert(configs, "--bin=" .. bindir)
end
local sdkdir = _get_config_from_toolchains(package, "sdkdir") or get_config("sdk")
if sdkdir then
table.insert(configs, "--sdk=" .. sdkdir)
end
local runtimes = package:config("runtimes")
if runtimes then
table.insert(configs, "--runtimes=" .. runtimes)
end
local toolchain_name = get_config("toolchain")
if toolchain_name then
table.insert(configs, "--toolchain=" .. toolchain_name)
end
_get_configs_for_qt(package, configs, opt)
_get_configs_for_vcpkg(package, configs, opt)
end
-- get configs for cross
function _get_configs_for_cross(package, configs, opt)
local cross = _get_config_from_toolchains(package, "cross") or get_config("cross")
if cross then
table.insert(configs, "--cross=" .. cross)
end
local bindir = _get_config_from_toolchains(package, "bindir") or get_config("bin")
if bindir then
table.insert(configs, "--bin=" .. bindir)
end
local sdkdir = _get_config_from_toolchains(package, "sdkdir") or get_config("sdk")
if sdkdir then
table.insert(configs, "--sdk=" .. sdkdir)
end
local runtimes = package:config("runtimes")
if runtimes then
table.insert(configs, "--runtimes=" .. runtimes)
end
local toolchain_name = get_config("toolchain")
if toolchain_name then
table.insert(configs, "--toolchain=" .. toolchain_name)
end
local names = {"ld", "sh", "ar", "cc", "cxx", "mm", "mxx"}
for _, name in ipairs(names) do
local value = get_config(name)
if value ~= nil then
table.insert(configs, "--" .. name .. "=" .. tostring(value))
end
end
end
-- get configs
function _get_configs(package, configs, opt)
opt = opt or {}
local configs = configs or {}
local cflags = table.join(table.wrap(package:config("cflags")), get_config("cflags"))
local cxflags = table.join(table.wrap(package:config("cxflags")), get_config("cxflags"))
local cxxflags = table.join(table.wrap(package:config("cxxflags")), get_config("cxxflags"))
local asflags = table.join(table.wrap(package:config("asflags")), get_config("asflags"))
local ldflags = table.join(table.wrap(package:config("ldflags")), get_config("ldflags"))
local shflags = table.join(table.wrap(package:config("shflags")), get_config("shflags"))
table.insert(configs, "--plat=" .. package:plat())
table.insert(configs, "--arch=" .. package:arch())
if configs.mode == nil then
table.insert(configs, "--mode=" .. (package:is_debug() and "debug" or "release"))
end
if configs.kind == nil then
table.insert(configs, "--kind=" .. (package:config("shared") and "shared" or "static"))
end
if package:is_plat("windows") then
_get_configs_for_windows(package, configs, opt)
elseif package:is_plat("android") then
_get_configs_for_android(package, configs, opt)
elseif package:is_plat("iphoneos", "watchos", "appletvos") or
-- for cross-compilation on macOS, @see https://github.com/xmake-io/xmake/issues/2804
(package:is_plat("macosx") and (get_config("appledev") or not package:is_arch(os.subarch()))) then
_get_configs_for_appleos(package, configs, opt)
elseif package:is_plat("mingw") then
_get_configs_for_mingw(package, configs, opt)
elseif package:is_cross() then
_get_configs_for_cross(package, configs, opt)
elseif package:config("toolchains") then
-- we still need find system libraries,
-- it just pass toolchain environments if the toolchain is compatible with host
if _is_toolchain_compatible_with_host(package) then
_get_configs_for_host_toolchain(package, configs, opt)
else
_get_configs_for_cross(package, configs, opt)
end
else
_get_configs_for_generic(package, configs, opt)
end
local policies = get_config("policies")
if package:config("lto") and (not policies or not policies:find("build.optimization.lto", 1, true)) then
if policies then
policies = policies .. ",build.optimization.lto"
else
policies = "build.optimization.lto"
end
end
if package:config("asan") and (not policies or not policies:find("build.sanitizer.address", 1, true)) then
if policies then
policies = policies .. ",build.sanitizer.address"
else
policies = "build.sanitizer.address"
end
end
if not package:use_external_includes() and (not policies or not policies:find("package.include_external_headers", 1, true)) then
if policies then
policies = policies .. ",package.include_external_headers:n"
else
policies = "package.include_external_headers:n"
end
end
if policies then
table.insert(configs, "--policies=" .. policies)
end
if not package:is_plat("windows", "mingw") and package:config("pic") ~= false then
table.insert(cxflags, "-fPIC")
end
if cflags and #cflags > 0 then
table.insert(configs, "--cflags=" .. table.concat(cflags, ' '))
end
if cxflags and #cxflags > 0 then
table.insert(configs, "--cxflags=" .. table.concat(cxflags, ' '))
end
if cxxflags and #cxxflags > 0 then
table.insert(configs, "--cxxflags=" .. table.concat(cxxflags, ' '))
end
if asflags and #asflags > 0 then
table.insert(configs, "--asflags=" .. table.concat(asflags, ' '))
end
if ldflags and #ldflags > 0 then
table.insert(configs, "--ldflags=" .. table.concat(ldflags, ' '))
end
if shflags and #shflags > 0 then
table.insert(configs, "--shflags=" .. table.concat(shflags, ' '))
end
local buildir = opt.buildir or package:buildir()
if buildir then
table.insert(configs, "--buildir=" .. buildir)
end
return configs
end
-- maybe in project?
-- @see https://github.com/xmake-io/xmake/issues/3720
function _maybe_in_project(package)
local dir = package:sourcedir() or package:cachedir()
local parentdir = path.directory(dir)
while parentdir and os.isdir(parentdir) do
if os.isfile(path.join(parentdir, "xmake.lua")) then
return true
end
parentdir = path.directory(parentdir)
end
end
-- set some builtin global options from the parent xmake
function _set_builtin_argv(package, argv)
-- if the package cache directory is modified,
-- we need to force the project directory to be specified to avoid interference by the upper level xmake.lua.
-- and we also need to put `-P` in the first argument to avoid option.parse() parsing errors
if _maybe_in_project(package) then
table.insert(argv, "-P")
table.insert(argv, os.curdir())
end
for _, name in ipairs({"diagnosis", "verbose", "quiet", "yes", "confirm", "root"}) do
local value = option.get(name)
if type(value) == "boolean" then
table.insert(argv, "--" .. name)
elseif value ~= nil then
table.insert(argv, "--" .. name .. "=" .. value)
end
end
end
-- get require info of package
function _get_package_requireinfo(packagename)
if os.isfile(os.projectfile()) then
local requires_str, requires_extra = project.requires_str()
local requireitems = require_package.load_requires(requires_str, requires_extra)
for _, requireitem in ipairs(requireitems) do
local requireinfo = requireitem.info or {}
local requirename = requireinfo.alias or requireitem.name
if requirename == packagename then
return requireinfo
end
end
end
end
-- get package toolchains envs
function _get_package_toolchains_envs(envs, package, opt)
opt = opt or {}
local toolchains = package:config("toolchains")
if toolchains then
-- pass toolchains name and their package configurations
local toolchain_packages = {}
local toolchains_custom = {}
for _, name in ipairs(toolchains) do
local toolchain_inst = toolchain.load(name, {plat = package:plat(), arch = package:arch()})
if toolchain_inst then
table.join2(toolchain_packages, toolchain_inst:config("packages"))
if not toolchain_inst:is_builtin() then
table.insert(toolchains_custom, toolchain_inst)
end
end
end
local rcfile_path = os.tmpfile() .. ".lua"
local rcfile = io.open(rcfile_path, 'w')
if #toolchain_packages > 0 then
for _, packagename in ipairs(toolchain_packages) do
local requireinfo = _get_package_requireinfo(packagename)
if requireinfo then
requireinfo.originstr = nil
rcfile:print("add_requires(\"%s\", %s)", packagename, string.serialize(requireinfo, {strip = true, indent = false}))
else
rcfile:print("add_requires(\"%s\")", packagename)
end
end
end
rcfile:print("add_toolchains(\"%s\")", table.concat(table.wrap(toolchains), '", "'))
rcfile:close()
table.insert(envs.XMAKE_RCFILES, rcfile_path)
-- pass custom toolchains definition in project
for _, toolchain_inst in ipairs(toolchains_custom) do
-- we must load it first
-- @see https://github.com/xmake-io/xmake/issues/3774
if toolchain_inst:check() then
toolchain_inst:load()
local toolchains_file = os.tmpfile()
dprint("passing toolchain(%s) to %s", toolchain_inst:name(), toolchains_file)
local ok, errors = toolchain_inst:savefile(toolchains_file)
if not ok then
raise("save toolchain failed, %s", errors or "unknown")
end
envs.XMAKE_TOOLCHAIN_DATAFILES = envs.XMAKE_TOOLCHAIN_DATAFILES or {}
table.insert(envs.XMAKE_TOOLCHAIN_DATAFILES, toolchains_file)
end
end
end
end
-- get require paths
function _get_package_requirepaths(requirepaths, package, dep, rootpath)
for _, plaindep in ipairs(package:plaindeps()) do
local subpath = table.join(rootpath, plaindep:name())
if plaindep == dep then
table.insert(requirepaths, table.concat(subpath, "."))
else
_get_package_requirepaths(requirepaths, plaindep, dep, subpath)
end
end
end
-- get package depconfs envs
-- @see https://github.com/xmake-io/xmake/issues/3952
function _get_package_depconfs_envs(envs, package, opt)
local policy = package:policy("package.xmake.pass_depconfs")
if policy == nil then
policy = project.policy("package.xmake.pass_depconfs")
end
if policy == false then
return
end
local requireconfs = {}
for _, dep in ipairs(package:librarydeps()) do
local requireinfo = dep:requireinfo()
if requireinfo and (requireinfo.override or (requireinfo.configs and not table.empty(requireinfo.configs))) then
local requirepaths = {}
_get_package_requirepaths(requirepaths, package, dep, {})
if #requirepaths > 0 then
table.insert(requireconfs, {requirepaths = requirepaths, requireinfo = requireinfo})
end
end
end
if #requireconfs > 0 then
local rcfile_path = os.tmpfile() .. ".lua"
local rcfile = io.open(rcfile_path, 'w')
for _, requireconf in ipairs(requireconfs) do
for _, requirepath in ipairs(requireconf.requirepaths) do
rcfile:print("add_requireconfs(\"%s\", %s)", requirepath, string.serialize(requireconf.requireinfo, {strip = true, indent = false}))
end
end
rcfile:close()
table.insert(envs.XMAKE_RCFILES, rcfile_path)
end
end
-- get the build environments
function buildenvs(package, opt)
local envs = {XMAKE_RCFILES = {}}
table.join2(envs.XMAKE_RCFILES, os.getenv("XMAKE_RCFILES"))
_get_package_toolchains_envs(envs, package, opt)
_get_package_depconfs_envs(envs, package, opt)
-- we should avoid using $XMAKE_CONFIGDIR outside to cause conflicts
envs.XMAKE_CONFIGDIR = os.curdir()
envs.XMAKE_IN_XREPO = "1"
envs.XMAKE_IN_PROJECT_GENERATOR = ""
return envs
end
-- install package
function install(package, configs, opt)
-- get build environments
opt = opt or {}
local envs = opt.envs or buildenvs(package)
-- pass local repositories
for _, repo in ipairs(repository.repositories()) do
local repo_argv = {"repo"}
_set_builtin_argv(package, repo_argv)
table.join2(repo_argv, {"--add", repo:name(), repo:directory()})
os.vrunv(os.programfile(), repo_argv, {envs = envs})
end
-- pass configurations
-- we need to put `-P` in the first argument of _set_builtin_argv() to avoid option.parse() parsing errors
local argv = {"f"}
_set_builtin_argv(package, argv)
table.insert(argv, "-y")
table.insert(argv, "-c")
for name, value in pairs(_get_configs(package, configs, opt)) do
value = tostring(value):trim()
if type(name) == "number" then
if value ~= "" then
table.insert(argv, value)
end
else
table.insert(argv, "--" .. name .. "=" .. value)
end
end
-- do configure
os.vrunv(os.programfile(), argv, {envs = envs})
-- do build
argv = {"build"}
_set_builtin_argv(package, argv)
local njob = opt.jobs or option.get("jobs")
if njob then
table.insert(argv, "--jobs=" .. njob)
end
local target = table.wrap(opt.target)
if #target ~= 0 then
table.join2(argv, target)
end
os.vrunv(os.programfile(), argv, {envs = envs})
-- do install
argv = {"install", "-y", "--nopkgs", "-o", package:installdir()}
_set_builtin_argv(package, argv)
local targets = table.wrap(opt.target)
if #targets ~= 0 then
table.join2(argv, targets)
end
os.vrunv(os.programfile(), argv, {envs = envs})
end
|
0 | repos/xmake/xmake/modules/package | repos/xmake/xmake/modules/package/tools/autoconf.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file autoconf.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("core.tool.toolchain")
import("core.cache.memcache")
import("lib.detect.find_tool")
import("private.utils.toolchain", {alias = "toolchain_utils"})
-- translate paths
function _translate_paths(paths)
if paths and is_host("windows") then
if type(paths) == "string" then
return path.unix(paths)
elseif type(paths) == "table" then
local result = {}
for _, p in ipairs(paths) do
table.insert(result, path.unix(p))
end
return result
end
end
return paths
end
-- translate cygwin paths
function _translate_cygwin_paths(paths)
if type(paths) == "string" then
return path.cygwin(paths)
elseif type(paths) == "table" then
local result = {}
for _, p in ipairs(paths) do
table.insert(result, path.cygwin(p))
end
return result
end
return paths
end
-- translate windows bin path
function _translate_windows_bin_path(bin_path)
if bin_path then
local argv = os.argv(bin_path)
argv[1] = path.unix(argv[1]) .. ".exe"
return os.args(argv)
end
end
-- get msvc
function _get_msvc(package)
local msvc = package:toolchain("msvc")
assert(msvc:check(), "vs not found!") -- we need to check vs envs if it has been not checked yet
return msvc
end
-- get msvc run environments
function _get_msvc_runenvs(package)
return os.joinenvs(_get_msvc(package):runenvs())
end
-- get memcache
function _memcache()
return memcache.cache("package.tools.autoconf")
end
-- has `--with-pic`?
function _has_with_pic(package)
local has_with_pic = _memcache():get2(tostring(package), "with_pic")
if has_with_pic == nil then
local result = try {function() return os.iorunv("./configure", {"--help"}, {shell = true}) end}
if result and result:find("--with-pic", 1, true) then
has_with_pic = true
end
has_with_pic = has_with_pic or false
_memcache():set2(tostring(package), "with_pic", has_with_pic)
end
return has_with_pic
end
-- get configs
function _get_configs(package, configs)
-- add prefix
local configs = configs or {}
table.insert(configs, "--prefix=" .. _translate_paths(package:installdir()))
-- add host for cross-complation
if not configs.host and package:is_cross() then
if package:is_plat("iphoneos", "macosx") then
local triples =
{
arm64 = "aarch64-apple-darwin",
arm64e = "aarch64-apple-darwin",
armv7 = "armv7-apple-darwin",
armv7s = "armv7s-apple-darwin",
i386 = "i386-apple-darwin",
x86_64 = "x86_64-apple-darwin"
}
table.insert(configs, "--host=" .. (triples[package:arch()] or triples.arm64))
elseif package:is_plat("android") then
-- @see https://developer.android.com/ndk/guides/other_build_systems#autoconf
local triples =
{
["armv5te"] = "arm-linux-androideabi", -- deprecated
["armv7-a"] = "arm-linux-androideabi", -- deprecated
["armeabi"] = "arm-linux-androideabi", -- removed in ndk r17
["armeabi-v7a"] = "arm-linux-androideabi",
["arm64-v8a"] = "aarch64-linux-android",
i386 = "i686-linux-android", -- deprecated
x86 = "i686-linux-android",
x86_64 = "x86_64-linux-android",
mips = "mips-linux-android", -- removed in ndk r17
mips64 = "mips64-linux-android" -- removed in ndk r17
}
table.insert(configs, "--host=" .. (triples[package:arch()] or triples["armeabi-v7a"]))
elseif package:is_plat("mingw") then
local triples =
{
i386 = "i686-w64-mingw32",
x86_64 = "x86_64-w64-mingw32"
}
table.insert(configs, "--host=" .. (triples[package:arch()] or triples.i386))
elseif package:is_plat("linux") then
local triples =
{
["arm64-v8a"] = "aarch64-linux-gnu",
arm64 = "aarch64-linux-gnu",
i386 = "i686-linux-gnu",
x86_64 = "x86_64-linux-gnu",
armv7 = "arm-linux-gnueabihf",
mips = "mips-linux-gnu",
mips64 = "mips64-linux-gnu",
mipsel = "mipsel-linux-gnu",
mips64el = "mips64el-linux-gnu",
loong64 = "loongarch64-linux-gnu"
}
table.insert(configs, "--host=" .. (triples[package:arch()] or triples.i386))
elseif package:is_plat("cross") and package:targetos() then
local host = package:arch()
if package:is_arch("arm64") then
host = "aarch64"
elseif package:is_arch("arm.*") then
host = "arm"
end
host = host .. "-" .. package:targetos()
table.insert(configs, "--host=" .. host)
end
end
if package:is_plat("linux", "bsd") and
package:config("pic") ~= false and _has_with_pic(package) then
table.insert(configs, "--with-pic")
end
return configs
end
-- get cflags from package deps
function _get_cflags_from_packagedeps(package, opt)
local values
for _, depname in ipairs(opt.packagedeps) do
local dep = type(depname) ~= "string" and depname or package:dep(depname)
if dep then
local fetchinfo = dep:fetch()
if fetchinfo then
if values then
values = values .. fetchinfo
else
values = fetchinfo
end
end
end
end
-- @see https://github.com/xmake-io/xmake-repo/pull/4973#issuecomment-2295890196
local result = {}
if values then
if values.defines then
table.join2(result, toolchain_utils.map_compflags_for_package(package, "cxx", "define", values.defines))
end
if values.includedirs then
table.join2(result, _translate_paths(toolchain_utils.map_compflags_for_package(package, "cxx", "includedir", values.includedirs)))
end
if values.sysincludedirs then
table.join2(result, _translate_paths(toolchain_utils.map_compflags_for_package(package, "cxx", "sysincludedir", values.sysincludedirs)))
end
end
return result
end
-- get ldflags from package deps
function _get_ldflags_from_packagedeps(package, opt)
local values
for _, depname in ipairs(opt.packagedeps) do
local dep = type(depname) ~= "string" and depname or package:dep(depname)
if dep then
local fetchinfo = dep:fetch()
if fetchinfo then
if values then
values = values .. fetchinfo
else
values = fetchinfo
end
end
end
end
local result = {}
if values then
if values.linkdirs then
table.join2(result, _translate_paths(toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "linkdir", values.linkdirs)))
end
if values.links then
table.join2(result, toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "link", values.links))
end
if values.syslinks then
table.join2(result, _translate_paths(toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "syslink", values.syslinks)))
end
if values.frameworks then
table.join2(result, toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "framework", values.frameworks))
end
end
return result
end
-- get the build environments
function buildenvs(package, opt)
opt = opt or {}
local envs = {}
local cross = false
local cflags, cxxflags, cppflags, asflags, ldflags, shflags, arflags
if not package:is_cross() and not package:config("toolchains") then
cppflags = {}
cflags = table.join(table.wrap(package:config("cxflags")), package:config("cflags"))
cxxflags = table.join(table.wrap(package:config("cxflags")), package:config("cxxflags"))
asflags = table.copy(table.wrap(package:config("asflags")))
ldflags = table.copy(table.wrap(package:config("ldflags")))
shflags = table.copy(table.wrap(package:config("shflags")))
if package:is_plat("linux") and package:is_arch("i386") then
table.insert(cflags, "-m32")
table.insert(cxxflags, "-m32")
table.insert(asflags, "-m32")
table.insert(ldflags, "-m32")
table.insert(shflags, "-m32")
end
table.join2(cflags, opt.cflags)
table.join2(cflags, opt.cxflags)
table.join2(cxxflags, opt.cxxflags)
table.join2(cxxflags, opt.cxflags)
table.join2(cppflags, opt.cppflags) -- @see https://github.com/xmake-io/xmake/issues/1688
table.join2(asflags, opt.asflags)
table.join2(ldflags, opt.ldflags)
table.join2(shflags, opt.shflags)
table.join2(cflags, _get_cflags_from_packagedeps(package, opt))
table.join2(cxxflags, _get_cflags_from_packagedeps(package, opt))
table.join2(cppflags, _get_cflags_from_packagedeps(package, opt))
table.join2(ldflags, _get_ldflags_from_packagedeps(package, opt))
table.join2(shflags, _get_ldflags_from_packagedeps(package, opt))
else
cross = true
cppflags = {}
cflags = table.join(table.wrap(package:build_getenv("cxflags")), package:build_getenv("cflags"))
cxxflags = table.join(table.wrap(package:build_getenv("cxflags")), package:build_getenv("cxxflags"))
asflags = table.copy(table.wrap(package:build_getenv("asflags")))
ldflags = table.copy(table.wrap(package:build_getenv("ldflags")))
shflags = table.copy(table.wrap(package:build_getenv("shflags")))
arflags = table.copy(table.wrap(package:build_getenv("arflags")))
local defines = package:build_getenv("defines")
local includedirs = package:build_getenv("includedirs")
local sysincludedirs = package:build_getenv("sysincludedirs")
local links = package:build_getenv("links")
local syslinks = package:build_getenv("syslinks")
local linkdirs = package:build_getenv("linkdirs")
table.join2(cflags, opt.cflags)
table.join2(cflags, opt.cxflags)
table.join2(cxxflags, opt.cxxflags)
table.join2(cxxflags, opt.cxflags)
table.join2(cppflags, opt.cppflags) -- @see https://github.com/xmake-io/xmake/issues/1688
table.join2(asflags, opt.asflags)
table.join2(ldflags, opt.ldflags)
table.join2(shflags, opt.shflags)
table.join2(arflags, opt.arflags)
table.join2(cflags, _get_cflags_from_packagedeps(package, opt))
table.join2(cxxflags, _get_cflags_from_packagedeps(package, opt))
table.join2(cppflags, _get_cflags_from_packagedeps(package, opt))
table.join2(ldflags, _get_ldflags_from_packagedeps(package, opt))
table.join2(cflags, toolchain_utils.map_compflags_for_package(package, "c", "define", defines))
table.join2(cflags, toolchain_utils.map_compflags_for_package(package, "c", "includedir", includedirs))
table.join2(cflags, toolchain_utils.map_compflags_for_package(package, "c", "sysincludedir", sysincludedirs))
table.join2(asflags, toolchain_utils.map_compflags_for_package(package, "as", "define", defines))
table.join2(asflags, toolchain_utils.map_compflags_for_package(package, "as", "includedir", includedirs))
table.join2(asflags, toolchain_utils.map_compflags_for_package(package, "as", "sysincludedir", sysincludedirs))
table.join2(cxxflags, toolchain_utils.map_compflags_for_package(package, "cxx", "define", defines))
table.join2(cxxflags, toolchain_utils.map_compflags_for_package(package, "cxx", "includedir", includedirs))
table.join2(cxxflags, toolchain_utils.map_compflags_for_package(package, "cxx", "sysincludedir", sysincludedirs))
table.join2(ldflags, toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "link", links))
table.join2(ldflags, toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "syslink", syslinks))
table.join2(ldflags, toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "linkdir", linkdirs))
table.join2(shflags, toolchain_utils.map_linkflags_for_package(package, "shared", {"cxx"}, "link", links))
table.join2(shflags, toolchain_utils.map_linkflags_for_package(package, "shared", {"cxx"}, "syslink", syslinks))
table.join2(shflags, toolchain_utils.map_linkflags_for_package(package, "shared", {"cxx"}, "linkdir", linkdirs))
envs.CC = package:build_getenv("cc")
envs.AS = package:build_getenv("as")
envs.AR = package:build_getenv("ar")
envs.LD = package:build_getenv("ld")
envs.LDSHARED = package:build_getenv("sh")
envs.CPP = package:build_getenv("cpp")
envs.RANLIB = package:build_getenv("ranlib")
end
if package:is_plat("linux", "bsd") and
package:config("pic") ~= false and not _has_with_pic(package) then
table.insert(cflags, "-fPIC")
table.insert(cxxflags, "-fPIC")
end
if package:config("lto") then
table.join2(cflags, package:_generate_lto_configs("cc").cflags)
table.join2(cxxflags, package:_generate_lto_configs("cxx").cxxflags)
table.join2(ldflags, package:_generate_lto_configs().ldflags)
end
local runtimes = package:runtimes()
if runtimes then
table.join2(cxxflags, toolchain_utils.map_compflags_for_package(package, "cxx", "runtime", runtimes))
table.join2(ldflags, toolchain_utils.map_linkflags_for_package(package, "binary", {"cxx"}, "runtime", runtimes))
table.join2(shflags, toolchain_utils.map_linkflags_for_package(package, "shared", {"cxx"}, "runtime", runtimes))
end
if package:config("asan") then
table.join2(cflags, package:_generate_sanitizer_configs("address", "cc").cflags)
table.join2(cxxflags, package:_generate_sanitizer_configs("address", "cxx").cxxflags)
table.join2(ldflags, package:_generate_sanitizer_configs("address").ldflags)
table.join2(shflags, package:_generate_sanitizer_configs("address").shflags)
end
if cflags then
envs.CFLAGS = table.concat(_translate_paths(cflags), ' ')
end
if cxxflags then
envs.CXXFLAGS = table.concat(_translate_paths(cxxflags), ' ')
end
if cppflags then
envs.CPPFLAGS = table.concat(_translate_paths(cppflags), ' ')
end
if asflags then
envs.ASFLAGS = table.concat(_translate_paths(asflags), ' ')
end
if arflags then
envs.ARFLAGS = table.concat(_translate_paths(arflags), ' ')
end
if ldflags or shflags then
-- autoconf does not use SHFLAGS
envs.LDFLAGS = table.concat(_translate_paths(table.join(ldflags or {}, shflags)), ' ')
end
-- cross-compilation? pass the full build environments
if cross then
if package:is_plat("mingw") then
-- fix linker error, @see https://github.com/xmake-io/xmake/issues/574
-- libtool: line 1855: lib: command not found
envs.ARFLAGS = nil
local ld = envs.LD
if ld then
if ld:endswith("x86_64-w64-mingw32-g++") then
envs.LD = path.join(path.directory(ld), is_host("windows") and "ld" or "x86_64-w64-mingw32-ld")
elseif ld:endswith("i686-w64-mingw32-g++") then
envs.LD = path.join(path.directory(ld), is_host("windows") and "ld" or "i686-w64-mingw32-ld")
end
end
else
if package:is_plat("macosx") then
-- force to apply shflags on macosx https://gmplib.org/manual/Known-Build-Problems
envs.CC = envs.CC .. " -arch " .. package:arch()
end
if package:is_plat("cross") or package:has_tool("ar", "ar", "emar") then
-- only for cross-toolchain
envs.CXX = package:build_getenv("cxx")
if not envs.ARFLAGS or envs.ARFLAGS == "" then
envs.ARFLAGS = "-cr"
end
end
end
-- we should use ld as linker
--
-- @see
-- https://github.com/xmake-io/xmake-repo/pull/1043
-- https://github.com/libexpat/libexpat/issues/312
-- https://github.com/xmake-io/xmake/issues/2195
local ld = envs.LD
if ld and package:has_tool("ld", "clang", "clangxx", "gcc", "gxx") then
local dir = path.directory(ld)
local name = path.filename(ld)
name = name:gsub("clang%+%+$", "ld")
name = name:gsub("clang%+%+%-%d+", "ld")
name = name:gsub("clang$", "ld")
name = name:gsub("clang%-%d+", "ld")
name = name:gsub("gcc$", "ld")
name = name:gsub("gcc-%d+", "ld")
name = name:gsub("g%+%+$", "ld")
name = name:gsub("g%+%+%-%d+", "ld")
envs.LD = dir and path.join(dir, name) or name
end
-- we need use clang++ as cxx, autoconf will use it as linker
-- https://github.com/xmake-io/xmake/issues/2170
local cxx = envs.CXX
if cxx and package:has_tool("cxx", "clang", "gcc") then
local dir = path.directory(cxx)
local name = path.filename(cxx)
name = name:gsub("clang$", "clang++")
name = name:gsub("clang%-", "clang++-")
name = name:gsub("gcc$", "g++")
name = name:gsub("gcc%-", "g++-")
envs.CXX = dir and path.join(dir, name) or name
end
elseif package:is_plat("windows") and not package:config("toolchains") then
envs.PATH = os.getenv("PATH") -- we need to reserve PATH on msys2
envs = os.joinenvs(envs, _get_msvc(package):runenvs())
end
if is_host("windows") then
envs.CC = _translate_windows_bin_path(envs.CC)
envs.AS = _translate_windows_bin_path(envs.AS)
envs.AR = _translate_windows_bin_path(envs.AR)
envs.LD = _translate_windows_bin_path(envs.LD)
envs.LDSHARED = _translate_windows_bin_path(envs.LDSHARED)
envs.CPP = _translate_windows_bin_path(envs.CPP)
envs.RANLIB = _translate_windows_bin_path(envs.RANLIB)
end
local ACLOCAL_PATH = {}
local PKG_CONFIG_PATH = {}
for _, dep in ipairs(package:librarydeps({private = true})) do
local pkgconfig = path.join(dep:installdir(), "lib", "pkgconfig")
if os.isdir(pkgconfig) then
table.insert(PKG_CONFIG_PATH, pkgconfig)
end
pkgconfig = path.join(dep:installdir(), "share", "pkgconfig")
if os.isdir(pkgconfig) then
table.insert(PKG_CONFIG_PATH, pkgconfig)
end
end
-- some binary packages contain it too. e.g. libtool
for _, dep in ipairs(package:orderdeps()) do
local aclocal = path.join(dep:installdir(), "share", "aclocal")
if os.isdir(aclocal) then
table.insert(ACLOCAL_PATH, aclocal)
end
end
envs.ACLOCAL_PATH = path.joinenv(ACLOCAL_PATH)
-- fix PKG_CONFIG_PATH for windows/msys2
-- @see https://github.com/xmake-io/xmake-repo/issues/3442
if package:is_plat("windows") then
-- pkg-config can only support for unix path and env seperator on msys/cygwin
PKG_CONFIG_PATH = _translate_cygwin_paths(PKG_CONFIG_PATH)
envs.PKG_CONFIG_PATH = path.joinenv(PKG_CONFIG_PATH, ":")
else
envs.PKG_CONFIG_PATH = path.joinenv(PKG_CONFIG_PATH)
end
return envs
end
-- get the autogen environments
function autogen_envs(package, opt)
opt = opt or {}
local envs = {NOCONFIGURE = "yes"}
local ACLOCAL_PATH = {}
local PKG_CONFIG_PATH = {}
for _, dep in ipairs(package:librarydeps({private = true})) do
local pkgconfig = path.join(dep:installdir(), "lib", "pkgconfig")
if os.isdir(pkgconfig) then
table.insert(PKG_CONFIG_PATH, pkgconfig)
end
pkgconfig = path.join(dep:installdir(), "share", "pkgconfig")
if os.isdir(pkgconfig) then
table.insert(PKG_CONFIG_PATH, pkgconfig)
end
end
-- some binary packages contain it too. e.g. libtool
for _, dep in ipairs(package:orderdeps()) do
local aclocal = path.join(dep:installdir(), "share", "aclocal")
if os.isdir(aclocal) then
table.insert(ACLOCAL_PATH, aclocal)
end
end
envs.ACLOCAL_PATH = path.joinenv(ACLOCAL_PATH)
envs.PKG_CONFIG_PATH = path.joinenv(PKG_CONFIG_PATH)
return envs
end
-- configure package
function configure(package, configs, opt)
-- init options
opt = opt or {}
-- generate configure file
if not os.isfile("configure") then
if os.isfile("autogen.sh") then
os.vrunv("./autogen.sh", {}, {shell = true, envs = autogen_envs(package, opt)})
elseif os.isfile("configure.ac") or os.isfile("configure.in") then
local autoreconf = find_tool("autoreconf")
assert(autoreconf, "autoreconf not found!")
os.vrunv(autoreconf.program, {"--install", "--symlink"}, {shell = true, envs = autogen_envs(package, opt)})
end
end
-- get envs
local envs = opt.envs or buildenvs(package, opt)
-- pass configurations
local argv = {}
for name, value in pairs(_get_configs(package, configs)) do
value = tostring(value):trim()
if value ~= "" then
if type(name) == "number" then
table.insert(argv, value)
else
table.insert(argv, "--" .. name .. "=" .. value)
end
end
end
-- do configure
os.vrunv("./configure", argv, {shell = true, envs = envs})
end
-- do make
function make(package, argv, opt)
opt = opt or {}
local program
if package:is_plat("mingw") and is_subhost("windows") then
local mingw = assert(package:build_getenv("mingw") or package:build_getenv("sdk"), "mingw not found!")
program = path.join(mingw, "bin", "mingw32-make.exe")
else
local tool = find_tool("make")
if tool then
program = tool.program
end
end
assert(program, "make not found!")
if package:is_plat("windows") then
local envs = opt.envs or buildenvs(package, opt)
os.vrunv(program, argv, {envs = envs})
else
os.vrunv(program, argv)
end
end
-- build package
function build(package, configs, opt)
-- do configure
configure(package, configs, opt)
-- do make and install
opt = opt or {}
local njob = opt.jobs or option.get("jobs") or tostring(os.default_njob())
local argv = {"-j" .. njob}
if option.get("diagnosis") then
table.insert(argv, "V=1")
end
if opt.makeconfigs then
for name, value in pairs(opt.makeconfigs) do
value = tostring(value):trim()
if value ~= "" then
if type(name) == "number" then
table.insert(argv, value)
else
table.insert(argv, name .. "=" .. value)
end
end
end
end
make(package, argv, opt)
end
-- install package
function install(package, configs, opt)
-- do build
opt = opt or {}
build(package, configs, opt)
-- do install
local argv = {"install"}
if option.get("diagnosis") then
table.insert(argv, "V=1")
end
if opt.makeconfigs then
for name, value in pairs(opt.makeconfigs) do
value = tostring(value):trim()
if value ~= "" then
if type(name) == "number" then
table.insert(argv, value)
else
table.insert(argv, name .. "=" .. value)
end
end
end
end
make(package, argv, opt)
end
|
0 | repos/xmake/xmake/modules/package | repos/xmake/xmake/modules/package/tools/scons.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author PucklaMotzer09
-- @file scons.lua
--
-- imports
import("core.base.option")
import("core.base.hashset")
import("core.tool.toolchain")
import("lib.detect.find_tool")
-- get configs
function _get_configs(package, configs)
local configs = configs or {}
local items = hashset.new()
for _, item in ipairs(configs) do
local name = item:split("=")[1]
items:insert(name)
end
if not items:has("target") then
table.insert(configs, "target=" .. (package:is_debug() and "debug" or "release"))
end
if not items:has("use_mingw") then
table.insert(configs, "use_mingw=" .. (package:is_plat("mingw", "cygwin", "msys") and "yes" or "no"))
end
if not items:has("platform") then
if package:is_plat("android") then
local scons_android_arch = "armv7"
if package:is_arch("arm64-v8a") then
scons_android_arch = "arm64v8"
end
table.insert(configs, "platform=android")
table.insert(configs, "android_arch=" .. scons_android_arch)
elseif package:is_plat("iphoneos") then
table.insert(configs, "platform=ios")
table.insert(configs, "ios_arch=" .. package:arch())
elseif package:is_plat("macosx") then
table.insert(configs, "platform=osx")
elseif package:is_plat("windows", "mingw", "cygwin", "msys") then
table.insert(configs, "platform=windows")
elseif package:is_plat("linux") then
table.insert(configs, "platform=linux")
elseif package:is_plat("bsd") then
table.insert(configs, "platform=freebsd")
end
end
if not items:has("bits") and package:is_plat("x86_64", "x86", "i386", "x64") then
table.insert("bits=" .. (package:is_arch("x86", "i386") and "32" or "64"))
end
return configs
end
-- get the build environments
function buildenvs(package, opt)
opt = opt or {}
local envs = {}
if package:is_plat("android") then
local ndk = toolchain.load("ndk", {plat = package:plat(), arch = package:arch()})
envs.ANDROID_NDK_ROOT = ndk:config("ndk")
end
local ACLOCAL_PATH = {}
local PKG_CONFIG_PATH = {}
for _, dep in ipairs(package:librarydeps({private = true})) do
local pkgconfig = path.join(dep:installdir(), "lib", "pkgconfig")
if os.isdir(pkgconfig) then
table.insert(PKG_CONFIG_PATH, pkgconfig)
end
pkgconfig = path.join(dep:installdir(), "share", "pkgconfig")
if os.isdir(pkgconfig) then
table.insert(PKG_CONFIG_PATH, pkgconfig)
end
end
-- some binary packages contain it too. e.g. libtool
for _, dep in ipairs(package:orderdeps()) do
local aclocal = path.join(dep:installdir(), "share", "aclocal")
if os.isdir(aclocal) then
table.insert(ACLOCAL_PATH, aclocal)
end
end
envs.ACLOCAL_PATH = path.joinenv(ACLOCAL_PATH)
envs.PKG_CONFIG_PATH = path.joinenv(PKG_CONFIG_PATH)
return envs
end
-- build package
function build(package, configs, opt)
opt = opt or {}
local buildir = opt.buildir or os.curdir()
local njob = opt.jobs or option.get("jobs") or tostring(os.default_njob())
local scons = assert(find_tool("scons"), "scons not found!")
local argv = {"-C", buildir, "-j", njob}
configs = _get_configs(package, configs)
if configs then
table.join2(argv, configs)
end
os.vrunv(scons.program, argv, {envs = opt.envs or buildenvs(package, opt)})
end
|
0 | repos/xmake/xmake/modules/package | repos/xmake/xmake/modules/package/tools/gn.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file gn.lua
--
-- imports
import("core.base.option")
import("core.tool.toolchain")
import("lib.detect.find_tool")
import("package.tools.ninja")
-- get build directory
function _get_buildir(opt)
if opt and opt.buildir then
return opt.buildir
else
_g.buildir = _g.buildir or ("build_" .. hash.uuid4():split('%-')[1])
return _g.buildir
end
end
-- get configs
function _get_configs(package, configs, opt)
configs = configs or {}
if not package:is_plat("windows") then
configs.cc = package:build_getenv("cc")
configs.cxx = package:build_getenv("cxx")
end
if package:is_plat("macosx") then
configs.extra_ldflags = {"-lstdc++"}
local xcode = toolchain.load("xcode", {plat = package:plat(), arch = package:arch()})
configs.xcode_sysroot = xcode:config("xcode_sysroot")
end
if package:is_plat("linux") then
configs.target_os = "linux"
elseif package:is_plat("macosx") then
configs.target_os = "mac"
elseif package:is_plat("windows") then
configs.target_os = "win"
elseif package:is_plat("iphoneos") then
configs.target_os = "ios"
elseif package:is_plat("android") then
configs.target_os = "android"
end
if package:is_arch("x86", "i386") then
configs.target_cpu = "x86"
elseif package:is_arch("x64", "x86_64") then
configs.target_cpu = "x64"
elseif package:is_arch("arm64", "arm64-v8a") then
configs.target_cpu = "arm64"
elseif package:is_arch("arm.*") then
configs.target_cpu = "arm"
end
if configs.is_debug == nil then
configs.is_debug = package:is_debug() and true or false
end
return configs
end
-- get msvc
function _get_msvc(package)
local msvc = package:toolchain("msvc")
assert(msvc:check(), "vs not found!") -- we need to check vs envs if it has been not checked yet
return msvc
end
-- get the build environments
function buildenvs(package, opt)
local envs = {}
if package:is_plat("windows") then
envs = os.joinenvs(_get_msvc(package):runenvs())
end
return envs
end
-- generate build files for ninja
function generate(package, configs, opt)
-- init options
opt = opt or {}
-- pass configurations
local argv = {}
local args = {}
table.insert(argv, "gen")
table.insert(argv, _get_buildir(opt))
for name, value in pairs(_get_configs(package, configs, opt)) do
if type(value) == "string" then
table.insert(args, name .. "=\"" .. value .. "\"")
elseif type(value) == "table" then
table.insert(args, name .. "=[\"" .. table.concat(value, "\",\"") .. "\"]")
else
table.insert(args, name .. "=" .. tostring(value))
end
end
table.insert(argv, "--args=" .. table.concat(args, ' '))
-- do configure
local gn = assert(find_tool("gn"), "gn not found!")
os.vrunv(gn.program, argv, {envs = opt.envs or buildenvs(package)})
end
-- build package
function build(package, configs, opt)
-- generate build files
opt = opt or {}
generate(package, configs, opt)
-- do build
local buildir = _get_buildir(opt)
ninja.build(package, {}, {buildir = buildir, envs = opt.envs or buildenvs(package, opt)})
end
-- install package
function install(package, configs, opt)
-- generate build files
opt = opt or {}
generate(package, configs, opt)
-- do build and install
local buildir = _get_buildir(opt)
ninja.install(package, {}, {buildir = buildir, envs = opt.envs or buildenvs(package, opt)})
end
|
0 | repos/xmake/xmake/modules | repos/xmake/xmake/modules/cli/amalgamate.lua | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file amalgamate.lua
--
-- imports
import("core.base.option")
import("core.base.graph")
import("core.project.config")
import("core.project.task")
import("core.project.project")
-- the options
local options =
{
{'u', "uniqueid", "kv", nil, "Set the unique id." },
{'o', "outputdir", "kv", nil, "Set the output directory."},
{nil, "target", "v", nil, "The target name." }
}
-- get include files
function _get_include_files(target, filepath)
local includes = {}
local sourcecode = io.readfile(filepath)
sourcecode = sourcecode:gsub("/%*.-%*/", "")
sourcecode = sourcecode:gsub("//.-\n", "\n")
sourcecode:gsub("#include%s+\"(.-)\"", function (include)
table.insert(includes, include)
end)
includes = table.unique(includes)
local includefiles = {}
local filedir = path.directory(filepath)
local includedirs = table.join(filedir, target:get("includedirs"))
for _, include in ipairs(includes) do
local result
for _, includedir in ipairs(includedirs) do
local includefile = path.join(includedir, include)
if os.isfile(includefile) then
includefile = path.normalize(path.absolute(includefile, os.projectdir()))
result = includefile
break
end
end
if result then
table.insert(includefiles, result)
else
wprint("#include \"%s\" not found in %s", include, filepath)
end
end
return includefiles
end
-- generate include graph
function _generate_include_graph(target, inputpaths, gh, marked)
for _, inputpath in ipairs(inputpaths) do
if not marked[inputpath] then
marked[inputpath] = true
local includefiles = _get_include_files(target, inputpath)
for _, includefile in ipairs(includefiles) do
gh:add_edge(inputpath, includefile)
end
if includefiles and #includefiles > 0 then
_generate_include_graph(target, includefiles, gh, marked)
end
end
end
end
-- generate file
function _generate_file(target, inputpaths, outputpath, uniqueid)
-- generate include graph
local gh = graph.new(true)
for idx, inputpath in ipairs(inputpaths) do
inputpath = path.normalize(path.absolute(inputpath, os.projectdir()))
inputpaths[idx] = inputpath
gh:add_edge("__root__", inputpath)
end
_generate_include_graph(target, inputpaths, gh, {})
-- sort file paths and remove root path
local filepaths = gh:topological_sort()
table.remove(filepaths, 1)
-- generate amalgamate file
local outputfile = io.open(outputpath, "w")
for _, filepath in irpairs(filepaths) do
cprint(" ${color.dump.reference}+${clear} %s", filepath)
if uniqueid then
outputfile:print("#define %s %s", uniqueid, "unity_" .. hash.uuid():split("-", {plain = true})[1])
end
outputfile:write(io.readfile(filepath))
if uniqueid then
outputfile:print("#undef %s", uniqueid)
end
end
outputfile:close()
cprint("${bright}%s generated!", outputpath)
end
-- generate code
function _generate_amalgamate_code(target, opt)
-- only for library/binary
if not target:is_library() and not target:is_binary() then
return
end
-- generate source code
local outputdir = opt.outputdir
local uniqueid = opt.uniqueid
for _, sourcebatch in pairs(target:sourcebatches()) do
local rulename = sourcebatch.rulename
if rulename == "c.build" or rulename == "c++.build" then
local outputpath = path.join(outputdir, target:name() .. (sourcekind == "cxx" and ".cpp" or ".c"))
_generate_file(target, sourcebatch.sourcefiles, outputpath, uniqueid)
end
end
-- generate header file
local srcheaders = target:headerfiles(includedir)
if srcheaders and #srcheaders > 0 then
local outputpath = path.join(outputdir, target:name() .. ".h")
_generate_file(target, srcheaders, outputpath, uniqueid)
end
end
-- generate amalgamate code
--
-- https://github.com/xmake-io/xmake/issues/1438
--
function main(...)
-- parse arguments
local argv = table.pack(...)
local args = option.parse(argv, options, "Generate amalgamate code.",
"",
"Usage: xmake l cli.amalgamate [options]")
-- config first
task.run("config")
-- generate amalgamate code
args.outputdir = args.outputdir or config.buildir()
if args.target then
local target = assert(project.target(args.target), "target(%s): not found!", args.target)
_generate_amalgamate_code(target, args)
else
for _, target in ipairs(project.ordertargets()) do
_generate_amalgamate_code(target, args)
end
end
end
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.