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/private/service | repos/xmake/xmake/modules/private/service/remote_build/client.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 client.lua
--
-- imports
import("core.base.tty")
import("core.base.bytes")
import("core.base.base64")
import("core.base.socket")
import("core.base.option")
import("core.base.scheduler")
import("core.project.config", {alias = "project_config"})
import("lib.detect.find_tool")
import("private.service.client_config", {alias = "config"})
import("private.service.message")
import("private.service.client")
import("private.service.stream", {alias = "socket_stream"})
import("private.service.remote_build.filesync", {alias = "new_filesync"})
-- define module
local remote_build_client = remote_build_client or client()
local super = remote_build_client:class()
-- init client
function remote_build_client:init()
super.init(self)
-- init address
local address = assert(config.get("remote_build.connect"), "config(remote_build.connect): not found!")
self:address_set(address)
-- get project directory
local projectdir = os.projectdir()
local projectfile = os.projectfile()
if projectfile and os.isfile(projectfile) and projectdir then
self._PROJECTDIR = projectdir
self._WORKDIR = path.join(project_config.directory(), "service", "remote_build")
else
raise("we need to enter a project directory with xmake.lua first!")
end
-- init filesync
local filesync = new_filesync(self:projectdir(), path.join(self:workdir(), "manifest.txt"))
filesync:ignorefiles_add(".git/**")
filesync:ignorefiles_add(".xmake/**")
self._FILESYNC = filesync
-- init timeout
self._SEND_TIMEOUT = config.get("remote_build.send_timeout") or config.get("send_timeout") or -1
self._RECV_TIMEOUT = config.get("remote_build.recv_timeout") or config.get("recv_timeout") or -1
self._CONNECT_TIMEOUT = config.get("remote_build.connect_timeout") or config.get("connect_timeout") or 10000
end
-- get class
function remote_build_client:class()
return remote_build_client
end
-- connect to the remote server
function remote_build_client:connect()
if self:is_connected() then
print("%s: has been connected!", self)
return
end
-- Do we need user authorization?
local token = config.get("remote_build.token")
if not token and self:user() then
-- get user password
cprint("Please input user ${bright}%s${clear} password to connect <%s:%d>:", self:user(), self:addr(), self:port())
io.flush()
local pass = (io.read() or ""):trim()
assert(pass ~= "", "password is empty!")
-- compute user authorization
token = base64.encode(self:user() .. ":" .. pass)
token = hash.md5(bytes(token))
end
-- do connect
local addr = self:addr()
local port = self:port()
local sock = assert(socket.connect(addr, port, {timeout = self:connect_timeout()}), "%s: server unreachable!", self)
local session_id = self:session_id()
local ok = false
local errors
cprint("${dim}%s: connect %s:%d ..", self, addr, port)
if sock then
local stream = socket_stream(sock, {send_timeout = self:send_timeout(), recv_timeout = self:recv_timeout()})
if stream:send_msg(message.new_connect(session_id, {token = token})) and stream:flush() then
local msg = stream:recv_msg()
if msg then
vprint(msg:body())
if msg:success() then
ok = true
else
errors = msg:errors()
end
end
end
end
if ok then
cprint("${dim}%s: connected!", self)
else
cprint("${dim}%s: connect %s:%d failed, %s", self, addr, port, errors or "unknown")
end
-- update status
local status = self:status()
status.addr = addr
status.port = port
status.token = token
status.connected = ok
status.session_id = session_id
self:status_save()
-- sync files
if ok then
self:sync()
end
end
-- disconnect server
function remote_build_client:disconnect()
if not self:is_connected() then
print("%s: has been disconnected!", self)
return
end
-- update status
local status = self:status()
status.token = nil
status.connected = false
self:status_save()
cprint("${dim}%s: disconnected!", self)
end
-- sync server files
function remote_build_client:sync()
assert(self:is_connected(), "%s: has been not connected!", self)
local addr = self:addr()
local port = self:port()
local sock = assert(socket.connect(addr, port, {timeout = self:connect_timeout()}), "%s: server unreachable!", self)
local session_id = self:session_id()
local errors
local ok = false
local diff_files
local xmakesrc = option.get("xmakesrc")
cprint("${dim}%s: sync files in %s:%d ..", self, addr, port)
while sock do
-- diff files
local stream = socket_stream(sock, {send_timeout = self:send_timeout(), recv_timeout = self:recv_timeout()})
diff_files, errors = self:_diff_files(stream, {xmakesrc = xmakesrc})
if not diff_files then
break
end
if not diff_files.changed then
ok = true
break
end
-- do sync
cprint("Uploading files ..")
local send_ok = false
if stream:send_msg(message.new_sync(session_id, diff_files,
{token = self:token(), xmakesrc = xmakesrc and true or false}), {compress = true}) and stream:flush() then
if self:_send_diff_files(stream, diff_files, {rootdir = xmakesrc}) then
send_ok = true
end
end
if not send_ok then
errors = "send files failed"
break
end
-- sync ok
local msg = stream:recv_msg({timeout = -1})
if msg and msg:success() then
vprint(msg:body())
ok = true
elseif msg then
errors = msg:errors()
end
break
end
if ok then
cprint("${dim}%s: sync files ok!", self)
else
cprint("${dim}%s: sync files failed in %s:%d, %s", self, addr, port, errors or "unknown")
end
end
-- pull server files
function remote_build_client:pull(filepattern, outputdir)
assert(self:is_connected(), "%s: has been not connected!", self)
local addr = self:addr()
local port = self:port()
local sock = assert(socket.connect(addr, port, {timeout = self:connect_timeout()}), "%s: server unreachable!", self)
local session_id = self:session_id()
local errors
local ok = false
if not filepattern:find("*", 1, true) and os.isdir(filepattern) then
filepattern = path.join(filepattern, "**")
end
if not outputdir then
outputdir = os.curdir()
end
cprint("${dim}%s: pull %s in %s:%d ..", self, filepattern, addr, port)
local stream = socket_stream(sock, {send_timeout = self:send_timeout(), recv_timeout = self:recv_timeout()})
if stream:send_msg(message.new_pull(session_id, filepattern, {token = self:token()})) and stream:flush() then
local fileitems
local msg = stream:recv_msg({timeout = -1})
if msg then
dprint(msg:body())
if msg:success() then
fileitems = msg:body().fileitems
else
errors = msg:errors()
end
end
if fileitems then
for _, fileitem in ipairs(fileitems) do
print("recving %s ..", fileitem)
if not stream:recv_file(path.normalize(path.join(outputdir, fileitem))) then
errors = string.format("recv %s failed", fileitem)
break
end
end
msg = stream:recv_msg({timeout = -1})
if msg then
dprint(msg:body())
if msg:success() then
ok = true
else
errors = msg:errors()
end
end
end
end
if ok then
cprint("${dim}%s: pull files to %s!", self, outputdir)
else
cprint("${dim}%s: pull files failed in %s:%d, %s", self, addr, port, errors or "unknown")
end
end
-- clean server files
function remote_build_client:clean()
assert(self:is_connected(), "%s: has been not connected!", self)
local addr = self:addr()
local port = self:port()
local sock = assert(socket.connect(addr, port, {timeout = self:connect_timeout()}), "%s: server unreachable!", self)
local session_id = self:session_id()
local errors
local ok = false
cprint("${dim}%s: clean files in %s:%d ..", self, addr, port)
local stream = socket_stream(sock, {send_timeout = self:send_timeout(), recv_timeout = self:recv_timeout()})
if stream:send_msg(message.new_clean(session_id, {token = self:token(), all = option.get("all")})) and stream:flush() then
local msg = stream:recv_msg({timeout = -1})
if msg then
vprint(msg:body())
if msg:success() then
ok = true
else
errors = msg:errors()
end
end
end
if ok then
cprint("${dim}%s: clean files ok!", self)
else
cprint("${dim}%s: clean files failed in %s:%d, %s", self, addr, port, errors or "unknown")
end
end
-- run command
function remote_build_client:runcmd(program, argv)
assert(self:is_connected(), "%s: has been not connected!", self)
local addr = self:addr()
local port = self:port()
local sock = assert(socket.connect(addr, port, {timeout = self:connect_timeout()}), "%s: server unreachable!", self)
local session_id = self:session_id()
local errors
local ok = false
local buff = bytes(8192)
local command = os.args(table.join(program, argv))
local leftstr = ""
cprint("${dim}%s: run '%s' in %s:%d ..", self, command, addr, port)
local stream = socket_stream(sock, {send_timeout = self:send_timeout(), recv_timeout = self:recv_timeout()})
if stream:send_msg(message.new_runcmd(session_id, program, argv, {token = self:token()})) and stream:flush() then
local stdin_opt = {stop = false}
local group_name = "remote_build/runcmd"
scheduler.co_group_begin(group_name, function (co_group)
scheduler.co_start(self._read_stdin, self, stream, stdin_opt)
end)
while true do
local msg = stream:recv_msg({timeout = -1})
if msg then
if msg:is_data() then
local data = stream:recv(buff, msg:body().size)
if data then
leftstr = leftstr .. data:str()
local pos = leftstr:lastof("\n", true)
if pos then
cprint(leftstr:sub(1, pos - 1))
leftstr = leftstr:sub(pos + 1)
end
else
errors = string.format("recv output data(%d) failed!", msg:body().size)
break
end
elseif msg:is_end() then
ok = true
break
else
if msg:success() then
ok = true
else
errors = msg:errors()
end
break
end
else
break
end
end
stdin_opt.stop = true
scheduler.co_group_wait(group_name)
end
if #leftstr > 0 then
cprint(leftstr)
end
if ok then
cprint("${dim}%s: run command ok!", self)
else
cprint("${dim}%s: run command failed in %s:%d, %s", self, addr, port, errors or "unknown")
end
io.flush()
end
-- is connected?
function remote_build_client:is_connected()
return self:status().connected
end
-- get the status
function remote_build_client:status()
local status = self._STATUS
local statusfile = self:statusfile()
if not status then
if os.isfile(statusfile) then
status = io.load(statusfile)
end
status = status or {}
self._STATUS = status
end
return status
end
-- save status
function remote_build_client:status_save()
io.save(self:statusfile(), self:status())
end
-- get the status file
function remote_build_client:statusfile()
return path.join(self:workdir(), "status.txt")
end
-- get the project directory
function remote_build_client:projectdir()
return self._PROJECTDIR
end
-- get working directory
function remote_build_client:workdir()
return self._WORKDIR
end
-- get user token
function remote_build_client:token()
return self:status().token
end
-- get the session id, only for unique project
function remote_build_client:session_id()
return self:status().session_id or hash.uuid(option.get("session")):split("-", {plain = true})[1]:lower()
end
-- set the given client address
function remote_build_client:address_set(address)
local addr, port, user = self:address_parse(address)
self._ADDR = addr
self._PORT = port
self._USER = user
end
-- get user name
function remote_build_client:user()
return self._USER
end
-- get the ip address
function remote_build_client:addr()
return self._ADDR
end
-- get the address port
function remote_build_client:port()
return self._PORT
end
-- get filesync
function remote_build_client:_filesync()
return self._FILESYNC
end
-- diff server files
function remote_build_client:_diff_files(stream, opt)
opt = opt or {}
assert(self:is_connected(), "%s: has been not connected!", self)
print("Scanning files ..")
local filesync = self:_filesync()
if opt.xmakesrc then
assert(os.isdir(opt.xmakesrc), "%s: %s not found!", opt.xmakesrc)
filesync = new_filesync(opt.xmakesrc, path.join(self:workdir(), "xmakesrc_manifest.txt"))
filesync:ignorefiles_add(".git/**")
end
local manifest, filecount = filesync:snapshot()
local session_id = self:session_id()
local count = 0
local result, errors
cprint("Comparing ${bright}%d${clear} files ..", filecount)
if stream:send_msg(message.new_diff(session_id, manifest,
{token = self:token(), xmakesrc = opt.xmakesrc and true or false}),
{compress = true}) and stream:flush() then
local msg = stream:recv_msg({timeout = -1})
if msg and msg:success() then
result = msg:body().manifest
if result then
for _, fileitem in ipairs(result.inserted) do
if count < 8 then
cprint(" ${green}[+]: ${clear}%s", fileitem)
end
count = count + 1
end
for _, fileitem in ipairs(result.modified) do
if count < 8 then
cprint(" ${yellow}[*]: ${clear}%s", fileitem)
end
count = count + 1
end
for _, fileitem in ipairs(result.removed) do
if count < 8 then
cprint(" ${red}[-]: ${clear}%s", fileitem)
end
count = count + 1
end
if count >= 8 then
print(" ...")
end
end
elseif msg then
errors = msg:errors()
end
end
cprint("${bright}%d${clear} files has been changed!", count)
return result, errors
end
-- send diff files
function remote_build_client:_send_diff_files(stream, diff_files, opt)
opt = opt or {}
local count = 0
local totalsize = 0
local compressed_size = 0
local totalcount = #(diff_files.inserted or {}) + #(diff_files.modified or {})
local time = os.mclock()
local startime = time
for _, fileitem in ipairs(diff_files.inserted) do
local filepath = fileitem
if opt.rootdir and not path.is_absolute(fileitem) then
filepath = path.absolute(fileitem, opt.rootdir)
end
local filesize = os.filesize(filepath)
if os.mclock() - time > 1000 then
cprint("Uploading ${bright}%d%%${clear} ..", math.floor(count * 100 / totalcount))
time = os.mclock()
end
vprint("uploading %s, %d bytes ..", fileitem, filesize)
local sent, compressed_real = stream:send_file(filepath, {compress = filesize > 4096})
if not sent then
return false
end
count = count + 1
totalsize = totalsize + filesize
compressed_size = compressed_size + compressed_real
end
for _, fileitem in ipairs(diff_files.modified) do
local filepath = fileitem
if opt.rootdir and not path.is_absolute(fileitem) then
filepath = path.absolute(fileitem, opt.rootdir)
end
local filesize = os.filesize(filepath)
if os.mclock() - time > 1000 then
cprint("Uploading ${bright}%d%%${clear} ..", math.floor(count * 100 / totalcount))
time = os.mclock()
end
vprint("uploading %s, %d bytes ..", fileitem, filesize)
local sent, compressed_real = stream:send_file(filepath, {compress = filesize > 4096})
if not sent then
return false
end
count = count + 1
totalsize = totalsize + filesize
compressed_size = compressed_size + compressed_real
end
cprint("Uploading ${bright}%s%%${clear} ..", totalcount > 0 and math.floor(count * 100 / totalcount) or 0)
cprint("${bright}%s${clear} files, ${bright}%s (%s%%)${clear} bytes are uploaded, spent ${bright}%s${clear} ms.",
totalcount, compressed_size, totalsize > 0 and math.floor(compressed_size * 100 / totalsize) or 0, os.mclock() - startime)
return stream:flush()
end
-- read stdin data
function remote_build_client:_read_stdin(stream, opt)
local term = tty.term()
if term == "msys2" or term == "cygwin" then
wprint("we cannot capture stdin on %s, please pass `-y` option to xmake command or use cmd/powershell terminal!", term)
end
while not opt.stop do
-- FIXME, io.readable is invalid on msys2/cygwin, it always return false
-- @see https://github.com/xmake-io/xmake/issues/2504
if io.readable() then
local line = io.read("L") -- with crlf
if line and #line > 0 then
local ok = false
local data = bytes(line)
if stream:send_msg(message.new_data(0, data:size(), {token = self:token()})) then
if stream:send(data) and stream:flush() then
ok = true
end
end
if not ok then
break
end
else
-- we need to avoid always reading stdin
-- https://github.com/xmake-io/xmake/issues/3422
os.sleep(1)
end
else
os.sleep(500)
end
end
-- say bye
if stream:send_msg(message.new_end(self:session_id(), {token = self:token()})) then
stream:flush()
end
end
function remote_build_client:__tostring()
return "<remote_build_client>"
end
-- is connected? we cannot depend on client:init when run action
function is_connected()
-- the current process is in service? we cannot enable it
if os.getenv("XMAKE_IN_SERVICE") then
return false
end
local projectdir = os.projectdir()
local projectfile = os.projectfile()
if projectfile and os.isfile(projectfile) and projectdir then
local workdir = path.join(project_config.directory(), "service", "remote_build")
local statusfile = path.join(workdir, "status.txt")
if os.isfile(statusfile) then
local status = io.load(statusfile)
if status and status.connected then
return true
end
end
end
end
-- new a client instance
function new()
local instance = remote_build_client()
instance:init()
return instance
end
-- get the singleton
function singleton()
local instance = _g.singleton
if not instance then
config.load()
instance = new()
_g.singleton = instance
end
return instance
end
function main()
return new()
end
|
0 | repos/xmake/xmake/modules/private/service | repos/xmake/xmake/modules/private/service/remote_build/server_session.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 server_session.lua
--
-- imports
import("core.base.pipe")
import("core.base.bytes")
import("core.base.object")
import("core.base.global")
import("core.base.option")
import("core.base.hashset")
import("core.base.scheduler")
import("private.service.server_config", {alias = "config"})
import("private.service.message")
import("private.service.remote_build.filesync", {alias = "new_filesync"})
-- define module
local server_session = server_session or object()
-- init server session
function server_session:init(server, session_id)
self._ID = session_id
self._SERVER = server
local filesync = new_filesync(self:sourcedir(), path.join(self:workdir(), "manifest.txt"))
filesync:ignorefiles_add(".git/**")
filesync:ignorefiles_add(".xmake/**")
self._FILESYNC = filesync
end
-- get server session id
function server_session:id()
return self._ID
end
-- get server
function server_session:server()
return self._SERVER
end
-- open server session
function server_session:open()
if self:is_connected() then
return
end
-- ensure source directory
self:_ensure_sourcedir()
-- update status
local status = self:status()
status.connected = true
status.session_id = self:id()
self:status_save()
end
-- close server session
function server_session:close()
if not self:is_connected() then
return
end
-- update status
local status = self:status()
status.connected = false
status.session_id = self:id()
self:status_save()
end
-- set stream
function server_session:stream_set(stream)
self._STREAM = stream
end
-- get stream
function server_session:stream()
return self._STREAM
end
-- diff files
function server_session:diff(respmsg)
local body = respmsg:body()
-- ensure sourcedir
self:_ensure_sourcedir()
-- do snapshot
local filesync = body.xmakesrc and self:_xmake_filesync() or self:_filesync()
local manifest_server = assert(filesync:snapshot(), "server manifest not found!")
local manifest_client = assert(body.manifest, "client manifest not found!")
vprint("%s: diff files in %s ..", self, filesync:rootdir())
-- get all files
local fileitems = hashset.new()
for fileitem, _ in pairs(manifest_client) do
fileitems:insert(fileitem)
end
for fileitem, _ in pairs(manifest_server) do
fileitems:insert(fileitem)
end
-- do diff
local removed = {}
local modified = {}
local inserted = {}
local changed = false
for _, fileitem in fileitems:keys() do
local manifest_info_client = manifest_client[fileitem]
local manifest_info_server = manifest_server[fileitem]
if manifest_info_client and manifest_info_server
and manifest_info_client.sha256 ~= manifest_info_server.sha256 then
table.insert(modified, fileitem)
changed = true
vprint("[*]: %s", fileitem)
elseif not manifest_info_server and manifest_info_client then
table.insert(inserted, fileitem)
changed = true
vprint("[+]: %s", fileitem)
elseif manifest_info_server and not manifest_info_client then
table.insert(removed, fileitem)
changed = true
vprint("[-]: %s", fileitem)
end
end
body.manifest = {changed = changed, removed = removed, inserted = inserted, modified = modified}
vprint("%s: diff files ok", self)
end
-- sync files
function server_session:sync(respmsg)
local body = respmsg:body()
local stream = self:stream()
local manifest = assert(body.manifest, "manifest not found!")
local filesync = body.xmakesrc and self:_xmake_filesync() or self:_filesync()
local sourcedir = body.xmakesrc and self:xmake_sourcedir() or self:sourcedir()
local archivedir = os.tmpfile() .. ".dir"
vprint("%s: sync files in %s ..", self, sourcedir)
if self:_recv_syncfiles(manifest, archivedir) then
-- do sync
for _, fileitem in ipairs(manifest.inserted) do
vprint("[+]: %s", fileitem)
local filepath_server = path.join(sourcedir, fileitem)
local filepath_client = path.join(archivedir, fileitem)
os.cp(filepath_client, filepath_server)
filesync:update(fileitem, filepath_server)
end
for _, fileitem in ipairs(manifest.modified) do
vprint("[*]: %s", fileitem)
local filepath_server = path.join(sourcedir, fileitem)
local filepath_client = path.join(archivedir, fileitem)
os.cp(filepath_client, filepath_server)
filesync:update(fileitem, filepath_server)
end
for _, fileitem in ipairs(manifest.removed) do
vprint("[-]: %s", fileitem)
local filepath_server = path.join(sourcedir, fileitem)
os.rm(filepath_server)
filesync:remove(fileitem)
end
filesync:manifest_save()
else
raise("receive files failed!")
end
os.tryrm(archivedir)
vprint("%s: sync files ok", self)
end
-- pull file
function server_session:pull(respmsg)
local body = respmsg:body()
local stream = self:stream()
local filepattern = body.filename
vprint("pull %s ..", filepattern)
-- get files
local filepaths = os.files(path.join(self:sourcedir(), filepattern))
local fileitems = {}
for _, filepath in ipairs(filepaths) do
local fileitem = path.relative(filepath, self:sourcedir())
if is_host("windows") then
fileitem = fileitem:gsub("\\", "/")
end
if fileitem:startswith("./") then
fileitem = fileitem:sub(3)
end
table.insert(fileitems, fileitem)
end
vprint(fileitems)
-- send files
body.fileitems = fileitems
respmsg:status_set(true)
if stream:send_msg(respmsg) then
for _, fileitem in ipairs(fileitems) do
local filepath = path.join(self:sourcedir(), fileitem)
vprint("sending %s ..", filepath)
if not stream:send_file(filepath, {compress = os.filesize(filepath) > 4096}) then
raise("send %s failed!", filepath)
end
end
end
end
-- clean files
function server_session:clean(respmsg)
local body = respmsg:body()
vprint("%s: clean files in %s ..", self, self:workdir())
os.tryrm(self:sourcedir())
os.tryrm(path.join(self:workdir(), "manifest.txt"))
if body.all then
for _, sessiondir in ipairs(os.dirs(path.join(self:server():workdir(), "sessions", "*"))) do
os.tryrm(path.join(sessiondir, "source"))
os.tryrm(path.join(sessiondir, "manifest.txt"))
end
os.tryrm(self:xmake_sourcedir())
os.tryrm(path.join(self:server():workdir(), "xmakesrc_manifest.txt"))
end
vprint("%s: clean files ok", self)
end
-- run command
function server_session:runcmd(respmsg)
local body = respmsg:body()
local program = body.program
local argv = body.argv
vprint("%s: run command(%s) ..", self, os.args(table.join(program, argv)))
-- init pipes
local stdin_rpipe, stdin_wpipe = pipe.openpair("BA") -- rpipe (block)
local stdin_wpipeopt = {wpipe = stdin_wpipe, stop = false}
local stdout_rpipe, stdout_wpipe = pipe.openpair()
local stdout_rpipeopt = {rpipe = stdout_rpipe, stop = false}
-- read and write pipe
local group_name = "remote_build/runcmd"
scheduler.co_group_begin(group_name, function (co_group)
scheduler.co_start(self._write_pipe, self, stdin_wpipeopt)
scheduler.co_start(self._read_pipe, self, stdout_rpipeopt)
end)
-- run program
local xmakesrc
if os.isfile(path.join(self:xmake_sourcedir(), "core", "main.lua")) then
xmakesrc = self:xmake_sourcedir()
end
try { function ()
os.execv(program, argv, {curdir = self:sourcedir(),
stdout = stdout_wpipe, stderr = stdout_wpipe, stdin = stdin_rpipe,
envs = {XMAKE_IN_SERVICE = "true", XMAKE_PROGRAM_DIR = xmakesrc}})
end}
stdin_rpipe:close()
stdout_wpipe:close()
-- stop it
stdin_wpipeopt.stop = true
stdout_rpipeopt.stop = true
-- wait pipes exits
scheduler.co_group_wait(group_name)
vprint("%s: run command ok", self)
end
-- get work directory
function server_session:workdir()
return path.join(self:server():workdir(), "sessions", self:id())
end
-- is connected?
function server_session:is_connected()
return self:status().connected
end
-- get the status
function server_session:status()
local status = self._STATUS
local statusfile = self:statusfile()
if not status then
if os.isfile(statusfile) then
status = io.load(statusfile)
end
status = status or {}
self._STATUS = status
end
return status
end
-- save status
function server_session:status_save()
io.save(self:statusfile(), self:status())
end
-- get status file
function server_session:statusfile()
return path.join(self:workdir(), "status.txt")
end
-- get sourcedir directory
function server_session:sourcedir()
return path.join(self:workdir(), "source")
end
-- get xmake sourcedir directory
function server_session:xmake_sourcedir()
return self:server():xmake_sourcedir()
end
-- get filesync
function server_session:_filesync()
return self._FILESYNC
end
-- get xmake filesync
function server_session:_xmake_filesync()
return self:server():_xmake_filesync()
end
-- ensure source directory
function server_session:_ensure_sourcedir()
local sourcedir = self:sourcedir()
if not os.isdir(sourcedir) then
os.mkdir(sourcedir)
end
local xmake_sourcedir = self:xmake_sourcedir()
if not os.isdir(xmake_sourcedir) then
os.mkdir(xmake_sourcedir)
end
end
-- write data to pipe
function server_session:_write_pipe(opt)
local buff = bytes(256)
local wpipe = opt.wpipe
vprint("%s: %s: writing data ..", self, wpipe)
while not opt.stop do
local data = self:_recv_data(buff)
if data then
local real = wpipe:write(data, {block = true})
vprint("%s: %s: write bytes(%d)", self, wpipe, real)
if real < 0 then
break
end
else
break
end
end
wpipe:close()
vprint("%s: %s: write data end", self, wpipe)
end
-- read data from pipe
function server_session:_read_pipe(opt)
local buff = bytes(256)
local rpipe = opt.rpipe
local verbose = option.get("verbose")
vprint("%s: %s: reading data ..", self, rpipe)
local leftstr = ""
while not opt.stop do
local real, data = rpipe:read(buff)
if real > 0 then
if verbose then
leftstr = leftstr .. data:str()
local pos = leftstr:lastof("\n", true)
if pos then
cprint(leftstr:sub(1, pos - 1))
leftstr = leftstr:sub(pos + 1)
end
end
if not self:_send_data(data) then
break
end
elseif real == 0 then
if rpipe:wait(pipe.EV_READ, -1) < 0 then
break
end
else
break
end
end
rpipe:close()
if #leftstr > 0 then
cprint(leftstr)
end
-- say end to client
self:_send_end()
vprint("%s: %s: read data end", self, rpipe)
end
-- recv data from stream
function server_session:_recv_data(buff)
local stream = self:stream()
local msg = stream:recv_msg({timeout = -1})
if msg and msg:is_data() then
return stream:recv(buff, msg:body().size)
end
end
-- send data to stream
function server_session:_send_data(data)
local stream = self:stream()
if stream:send_msg(message.new_data(self:id(), data:size())) then
if stream:send(data) then
return stream:flush()
end
end
end
-- send end to stream
function server_session:_send_end()
local stream = self:stream()
if stream:send_msg(message.new_end(self:id())) then
return stream:flush()
end
end
-- recv syncfiles
function server_session:_recv_syncfiles(manifest, outputdir)
local stream = self:stream()
for _, fileitem in ipairs(manifest.inserted) do
local filepath = path.join(outputdir, fileitem)
if not stream:recv_file(filepath) then
dprint("%s: recv %s failed!", self, filepath)
return false
end
end
for _, fileitem in ipairs(manifest.modified) do
local filepath = path.join(outputdir, fileitem)
if not stream:recv_file(filepath) then
dprint("%s: recv %s failed!", self, filepath)
return false
end
end
return true
end
function server_session:__tostring()
return string.format("<session %s>", self:id())
end
function main(server, session_id)
local instance = server_session()
instance:init(server, session_id)
return instance
end
|
0 | repos/xmake/xmake/modules/private/service | repos/xmake/xmake/modules/private/service/remote_cache/server.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 server.lua
--
-- imports
import("core.base.global")
import("private.service.server_config", {alias = "config"})
import("private.service.message")
import("private.service.server")
import("private.service.remote_cache.server_session")
import("lib.detect.find_tool")
-- define module
local remote_cache_server = remote_cache_server or server()
local super = remote_cache_server:class()
-- init server
function remote_cache_server:init(daemon)
super.init(self, daemon)
-- init address
local address = assert(config.get("remote_cache.listen"), "config(remote_cache.listen): not found!")
super.address_set(self, address)
-- init handler
super.handler_set(self, self._on_handle)
-- init sessions
self._SESSIONS = {}
-- init timeout
self._SEND_TIMEOUT = config.get("remote_cache.send_timeout") or config.get("send_timeout") or -1
self._RECV_TIMEOUT = config.get("remote_cache.recv_timeout") or config.get("recv_timeout") or -1
end
-- get class
function remote_cache_server:class()
return remote_cache_server
end
-- get work directory
function remote_cache_server:workdir()
local workdir = config.get("remote_cache.workdir")
if not workdir then
workdir = path.join(global.directory(), "service", "server", "remote_cache")
end
return workdir
end
-- on handle message
function remote_cache_server:_on_handle(stream, msg)
local session_id = msg:session_id()
local session = self:_session(session_id)
vprint("%s: %s: <session %s>: on handle message(%d)", self, stream:sock(), session_id, msg:code())
vprint(msg:body())
session:stream_set(stream)
local respmsg = msg:clone()
local session_errs
local session_ok = try
{
function()
if self:need_verfiy() then
local ok, errors = self:verify_user(msg:token(), stream:sock():peeraddr())
if not ok then
session_errs = errors
return false
end
end
if msg:is_connect() then
session:open()
else
assert(session:is_connected(), "session has not been connected!")
if msg:is_push() then
session:push(respmsg)
elseif msg:is_pull() then
session:pull(respmsg)
elseif msg:is_fileinfo() then
session:fileinfo(respmsg)
elseif msg:is_existinfo() then
session:existinfo(respmsg)
elseif msg:is_clean() then
session:clean()
end
end
return true
end,
catch
{
function (errors)
if errors then
session_errs = tostring(errors)
vprint(session_errs)
end
end
}
}
respmsg:status_set(session_ok)
if not session_ok and session_errs then
respmsg:errors_set(session_errs)
end
local ok = stream:send_msg(respmsg) and stream:flush()
vprint("%s: %s: <session %s>: send %s", self, stream:sock(), session_id, ok and "ok" or "failed")
end
-- get session
function remote_cache_server:_session(session_id)
local session = self._SESSIONS[session_id]
if not session then
session = server_session(self, session_id)
self._SESSIONS[session_id] = session
end
return session
end
-- close session
function remote_cache_server:_session_close(session_id)
self._SESSIONS[session_id] = nil
end
function remote_cache_server:__tostring()
return "<remote_cache_server>"
end
function main(daemon)
local instance = remote_cache_server()
instance:init(daemon ~= nil)
return instance
end
|
0 | repos/xmake/xmake/modules/private/service | repos/xmake/xmake/modules/private/service/remote_cache/client.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 client.lua
--
-- imports
import("core.base.bytes")
import("core.base.base64")
import("core.base.socket")
import("core.base.option")
import("core.base.hashset")
import("core.base.scheduler")
import("core.base.bloom_filter")
import("core.project.config", {alias = "project_config"})
import("lib.detect.find_tool")
import("private.service.client_config", {alias = "config"})
import("private.service.message")
import("private.service.client")
import("private.service.stream", {alias = "socket_stream"})
-- define module
local remote_cache_client = remote_cache_client or client()
local super = remote_cache_client:class()
-- init client
function remote_cache_client:init()
super.init(self)
-- init address
local address = assert(config.get("remote_cache.connect"), "config(remote_cache.connect): not found!")
self:address_set(address)
-- get project directory
local projectdir = os.projectdir()
local projectfile = os.projectfile()
if projectfile and os.isfile(projectfile) and projectdir then
self._PROJECTDIR = projectdir
self._WORKDIR = path.join(project_config.directory(), "service", "remote_cache")
else
raise("we need to enter a project directory with xmake.lua first!")
end
-- init sockets
self._FREESOCKS = {}
self._OPENSOCKS = hashset.new()
-- init timeout
self._SEND_TIMEOUT = config.get("remote_cache.send_timeout") or config.get("send_timeout") or -1
self._RECV_TIMEOUT = config.get("remote_cache.recv_timeout") or config.get("recv_timeout") or -1
self._CONNECT_TIMEOUT = config.get("remote_cache.connect_timeout") or config.get("connect_timeout") or 10000
end
-- get class
function remote_cache_client:class()
return remote_cache_client
end
-- connect to the remote server
function remote_cache_client:connect()
if self:is_connected() then
print("%s: has been connected!", self)
return
end
-- Do we need user authorization?
local token = config.get("remote_cache.token")
if not token and self:user() then
-- get user password
cprint("Please input user ${bright}%s${clear} password to connect <%s:%d>:", self:user(), self:addr(), self:port())
io.flush()
local pass = (io.read() or ""):trim()
assert(pass ~= "", "password is empty!")
-- compute user authorization
token = base64.encode(self:user() .. ":" .. pass)
token = hash.md5(bytes(token))
end
-- do connect
local addr = self:addr()
local port = self:port()
local sock = assert(socket.connect(addr, port, {timeout = self:connect_timeout()}), "%s: server unreachable!", self)
local session_id = self:session_id()
local ok = false
local errors
print("%s: connect %s:%d ..", self, addr, port)
if sock then
local stream = socket_stream(sock, {send_timeout = self:send_timeout(), recv_timeout = self:recv_timeout()})
if stream:send_msg(message.new_connect(session_id, {token = token})) and stream:flush() then
local msg = stream:recv_msg()
if msg then
vprint(msg:body())
if msg:success() then
ok = true
else
errors = msg:errors()
end
end
end
end
if ok then
print("%s: connected!", self)
else
print("%s: connect %s:%d failed, %s", self, addr, port, errors or "unknown")
end
-- update status
local status = self:status()
status.addr = addr
status.port = port
status.token = token
status.connected = ok
status.session_id = session_id
self:status_save()
end
-- disconnect server
function remote_cache_client:disconnect()
if not self:is_connected() then
print("%s: has been disconnected!", self)
return
end
-- update status
local status = self:status()
status.token = nil
status.connected = false
self:status_save()
print("%s: disconnected!", self)
end
-- pull cache file
function remote_cache_client:pull(cachekey, cachefile)
assert(self:is_connected(), "%s: has been not connected!", self)
local addr = self:addr()
local port = self:port()
local sock = assert(self:_sock_open(), "open socket failed!")
local session_id = self:session_id()
local errors
local ok = false
local exists = false
local extrainfo
dprint("%s: pull cache(%s) in %s:%d ..", self, cachekey, addr, port)
local stream = socket_stream(sock, {send_timeout = self:send_timeout(), recv_timeout = self:recv_timeout()})
if stream:send_msg(message.new_pull(session_id, cachekey, {token = self:token()})) and stream:flush() then
if stream:recv_file(cachefile) then
local msg = stream:recv_msg()
if msg then
dprint(msg:body())
if msg:success() then
ok = true
exists = msg:body().exists
extrainfo = msg:body().extrainfo
else
errors = msg:errors()
end
end
else
errors = "recv cache file failed"
end
end
self:_sock_close(sock)
if ok then
dprint("%s: pull cache(%s) ok!", self, cachekey)
else
dprint("%s: pull cache(%s) failed in %s:%d, %s", self, cachekey, addr, port, errors or "unknown")
end
return exists, extrainfo
end
-- push cache file
function remote_cache_client:push(cachekey, cachefile, extrainfo)
assert(self:is_connected(), "%s: has been not connected!", self)
local addr = self:addr()
local port = self:port()
local sock = assert(self:_sock_open(), "open socket failed!")
local session_id = self:session_id()
local errors
local ok = false
dprint("%s: push cache(%s) in %s:%d ..", self, cachekey, addr, port)
local stream = socket_stream(sock, {send_timeout = self:send_timeout(), recv_timeout = self:recv_timeout()})
if stream:send_msg(message.new_push(session_id, cachekey, {token = self:token(), extrainfo = extrainfo})) and stream:flush() then
if stream:send_file(cachefile, {compress = os.filesize(cachefile) > 4096}) then
local msg = stream:recv_msg()
if msg then
dprint(msg:body())
if msg:success() then
ok = true
else
errors = msg:errors()
end
end
else
errors = "send cache file failed"
end
end
self:_sock_close(sock)
if ok then
dprint("%s: push cache(%s) ok!", self, cachekey)
else
dprint("%s: push cache(%s) failed in %s:%d, %s", self, cachekey, addr, port, errors or "unknown")
end
end
-- get cache file info
function remote_cache_client:cacheinfo(cachekey)
assert(self:is_connected(), "%s: has been not connected!", self)
local addr = self:addr()
local port = self:port()
local sock = assert(self:_sock_open(), "open socket failed!")
local session_id = self:session_id()
local errors
local ok = false
local cacheinfo
dprint("%s: get cacheinfo(%s) in %s:%d ..", self, cachekey, addr, port)
local stream = socket_stream(sock, {send_timeout = self:send_timeout(), recv_timeout = self:recv_timeout()})
if stream:send_msg(message.new_fileinfo(session_id, cachekey, {token = self:token()})) and stream:flush() then
local msg = stream:recv_msg()
if msg then
dprint(msg:body())
if msg:success() then
cacheinfo = msg:body().fileinfo
ok = true
else
errors = msg:errors()
end
end
end
self:_sock_close(sock)
if ok then
dprint("%s: get cacheinfo(%s) ok!", self, cachekey)
else
dprint("%s: get cacheinfo(%s) failed in %s:%d, %s", self, cachekey, addr, port, errors or "unknown")
end
return cacheinfo
end
-- get the exist info of cache in server
function remote_cache_client:existinfo()
assert(self:is_connected(), "%s: has been not connected!", self)
local addr = self:addr()
local port = self:port()
local sock = assert(self:_sock_open(), "open socket failed!")
local session_id = self:session_id()
local errors
local existinfo
dprint("%s: get exist info in %s:%d ..", self, addr, port)
local stream = socket_stream(sock, {send_timeout = self:send_timeout(), recv_timeout = self:recv_timeout()})
if stream:send_msg(message.new_existinfo(session_id, "objectfiles", {token = self:token()})) and stream:flush() then
local data = stream:recv_data()
if data then
local msg = stream:recv_msg()
if msg then
dprint(msg:body())
if msg:success() then
local count = msg:body().count
if count and count > 0 then
local filter = bloom_filter.new()
filter:data_set(data)
existinfo = filter
end
else
errors = msg:errors()
end
end
else
errors = "recv exist info failed"
end
end
self:_sock_close(sock)
if existinfo then
dprint("%s: get exist info ok!", self)
else
dprint("%s: get exist info failed in %s:%d, %s", self, addr, port, errors or "unknown")
end
return existinfo
end
-- clean server files
function remote_cache_client:clean()
assert(self:is_connected(), "%s: has been not connected!", self)
local addr = self:addr()
local port = self:port()
local sock = assert(self:_sock_open(), "open socket failed!")
local session_id = self:session_id()
local errors
local ok = false
print("%s: clean files in %s:%d ..", self, addr, port)
local stream = socket_stream(sock, {send_timeout = self:send_timeout(), recv_timeout = self:recv_timeout()})
if stream:send_msg(message.new_clean(session_id, {token = self:token()})) and stream:flush() then
local msg = stream:recv_msg()
if msg then
vprint(msg:body())
if msg:success() then
ok = true
else
errors = msg:errors()
end
end
end
self:_sock_close(sock)
if ok then
print("%s: clean files ok!", self)
else
print("%s: clean files failed in %s:%d, %s", self, addr, port, errors or "unknown")
end
end
-- is connected?
function remote_cache_client:is_connected()
return self:status().connected
end
-- get the status
function remote_cache_client:status()
local status = self._STATUS
local statusfile = self:statusfile()
if not status then
if os.isfile(statusfile) then
status = io.load(statusfile)
end
status = status or {}
self._STATUS = status
end
return status
end
-- save status
function remote_cache_client:status_save()
io.save(self:statusfile(), self:status())
end
-- get the status file
function remote_cache_client:statusfile()
return path.join(self:workdir(), "status.txt")
end
-- get the project directory
function remote_cache_client:projectdir()
return self._PROJECTDIR
end
-- get working directory
function remote_cache_client:workdir()
return self._WORKDIR
end
-- get user token
function remote_cache_client:token()
return self:status().token
end
-- get the session id, only for unique project
function remote_cache_client:session_id()
return self:status().session_id or hash.uuid(option.get("session")):split("-", {plain = true})[1]:lower()
end
-- set the given client address
function remote_cache_client:address_set(address)
local addr, port, user = self:address_parse(address)
self._ADDR = addr
self._PORT = port
self._USER = user
end
-- get user name
function remote_cache_client:user()
return self._USER
end
-- get the ip address
function remote_cache_client:addr()
return self._ADDR
end
-- get the address port
function remote_cache_client:port()
return self._PORT
end
-- is server unreachable?
function remote_cache_client:unreachable()
return self._UNREACHABLE
end
-- open a free socket
function remote_cache_client:_sock_open()
local freesocks = self._FREESOCKS
local opensocks = self._OPENSOCKS
if #freesocks > 0 then
local sock = freesocks[#freesocks]
table.remove(freesocks)
opensocks:insert(sock)
return sock
end
local addr = self:addr()
local port = self:port()
local sock = socket.connect(addr, port, {timeout = self:connect_timeout()})
if not sock then
self._UNREACHABLE = true
raise("%s: server unreachable!", self)
end
opensocks:insert(sock)
return sock
end
-- close a socket
function remote_cache_client:_sock_close(sock)
local freesocks = self._FREESOCKS
local opensocks = self._OPENSOCKS
table.insert(freesocks, sock)
opensocks:remove(sock)
end
function remote_cache_client:__gc()
local freesocks = self._FREESOCKS
local opensocks = self._OPENSOCKS
for _, sock in ipairs(freesocks) do
sock:close()
end
for _, sock in ipairs(opensocks:keys()) do
sock:close()
end
self._FREESOCKS = {}
self._OPENSOCKS = {}
end
function remote_cache_client:__tostring()
return "<remote_cache_client>"
end
-- is connected? we cannot depend on client:init when run action
function is_connected()
local connected = _g.connected
if connected == nil then
-- the current process is in service? we cannot enable it
if os.getenv("XMAKE_IN_SERVICE") then
connected = false
end
if connected == nil then
local projectdir = os.projectdir()
local projectfile = os.projectfile()
if projectfile and os.isfile(projectfile) and projectdir then
local workdir = path.join(project_config.directory(), "service", "remote_cache")
local statusfile = path.join(workdir, "status.txt")
if os.isfile(statusfile) then
local status = io.load(statusfile)
if status and status.connected then
connected = true
end
end
end
end
connected = connected or false
_g.connected = connected
end
return connected
end
-- new a client instance
function new()
local instance = remote_cache_client()
instance:init()
return instance
end
-- get the singleton
function singleton()
local instance = _g.singleton
if not instance then
config.load()
instance = new()
_g.singleton = instance
end
return instance
end
function main()
return new()
end
|
0 | repos/xmake/xmake/modules/private/service | repos/xmake/xmake/modules/private/service/remote_cache/server_session.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 server_session.lua
--
-- imports
import("core.base.pipe")
import("core.base.bytes")
import("core.base.object")
import("core.base.global")
import("core.base.option")
import("core.base.hashset")
import("core.base.scheduler")
import("core.base.bloom_filter")
import("private.service.server_config", {alias = "config"})
import("private.service.message")
-- define module
local server_session = server_session or object()
-- init server session
function server_session:init(server, session_id)
self._ID = session_id
self._SERVER = server
end
-- get server session id
function server_session:id()
return self._ID
end
-- get server
function server_session:server()
return self._SERVER
end
-- open server session
function server_session:open()
if self:is_connected() then
return
end
-- update status
local status = self:status()
status.connected = true
status.session_id = self:id()
self:status_save()
end
-- close server session
function server_session:close()
if not self:is_connected() then
return
end
-- update status
local status = self:status()
status.connected = false
status.session_id = self:id()
self:status_save()
end
-- pull file
function server_session:pull(respmsg)
local body = respmsg:body()
local stream = self:stream()
local cachekey = body.filename
local cachefile = path.join(self:cachedir(), cachekey:sub(1, 2), cachekey)
local cacheinfofile = cachefile .. ".txt"
vprint("pull cachefile(%s) ..", cachekey)
-- send cache file
if os.isfile(cachefile) then
body.exists = true
if os.isfile(cacheinfofile) then
body.extrainfo = io.load(cacheinfofile)
end
if not stream:send_file(cachefile, {compress = os.filesize(cachefile) > 4096}) then
raise("send %s failed!", cachefile)
end
else
body.exists = false
if not stream:send_emptydata() then
raise("send empty data failed!")
end
end
end
-- push file
function server_session:push(respmsg)
local body = respmsg:body()
local stream = self:stream()
local cachekey = body.filename
local cachefile = path.join(self:cachedir(), cachekey:sub(1, 2), cachekey)
local cacheinfofile = cachefile .. ".txt"
vprint("push cachefile(%s) ..", cachekey)
if not stream:recv_file(cachefile) then
raise("recv %s failed!", cachefile)
end
if body.extrainfo then
io.save(cacheinfofile, body.extrainfo)
end
end
-- get file info
function server_session:fileinfo(respmsg)
local body = respmsg:body()
local stream = self:stream()
local cachekey = body.filename
local cachefile = path.join(self:cachedir(), cachekey:sub(1, 2), cachekey)
body.fileinfo = {filesize = os.filesize(cachefile), exists = os.isfile(cachefile)}
vprint("get cacheinfo(%s)", cachekey)
end
-- get exist info
function server_session:existinfo(respmsg)
local body = respmsg:body()
local stream = self:stream()
local cachedir = self:cachedir()
local filter = bloom_filter.new()
local count = 0
vprint("get existinfo(%s) ..", body.name)
for _, objectfile in ipairs(os.files(path.join(cachedir, "*", "*"))) do
local cachekey = path.basename(objectfile)
if cachekey then
filter:set(cachekey)
count = count + 1
end
end
if count > 0 then
if not stream:send_data(filter:data(), {compress = true}) then
raise("send data failed!")
end
else
if not stream:send_emptydata() then
raise("send empty data failed!")
end
end
body.count = count
vprint("get existinfo(%s): %d ok", body.name, count)
end
-- clean files
function server_session:clean()
vprint("%s: clean files in %s ..", self, self:cachedir())
os.tryrm(self:cachedir())
vprint("%s: clean files ok", self)
end
-- set stream
function server_session:stream_set(stream)
self._STREAM = stream
end
-- get stream
function server_session:stream()
return self._STREAM
end
-- get work directory
function server_session:workdir()
return path.join(self:server():workdir(), "sessions", self:id())
end
-- is connected?
function server_session:is_connected()
return self:status().connected
end
-- get the status
function server_session:status()
local status = self._STATUS
local statusfile = self:statusfile()
if not status then
if os.isfile(statusfile) then
status = io.load(statusfile)
end
status = status or {}
self._STATUS = status
end
return status
end
-- save status
function server_session:status_save()
io.save(self:statusfile(), self:status())
end
-- get status file
function server_session:statusfile()
return path.join(self:workdir(), "status.txt")
end
-- get cache directory
function server_session:cachedir()
return path.join(self:workdir(), "cache")
end
function server_session:__tostring()
return string.format("<session %s>", self:id())
end
function main(server, session_id)
local instance = server_session()
instance:init(server, session_id)
return instance
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/require/export.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 export.lua
--
-- imports
import("core.base.task")
import("core.base.option")
import("private.action.require.impl.repository")
import("private.action.require.impl.environment")
import("private.action.require.impl.export_packages")
import("private.action.require.impl.utils.get_requires")
-- export the given packages
function main(requires_raw)
-- enter environment
environment.enter()
-- pull all repositories first if not exists
if not repository.pulled() then
task.run("repo", {update = true})
end
-- 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
-- export packages
local packagedir = option.get("packagedir")
local nodeps = option.get("shallow") and true or false
local packages = export_packages(requires, {requires_extra = requires_extra, packagedir = packagedir, nodeps = nodeps})
if not packages or #packages == 0 then
if requires_raw then
cprint("${bright}packages(%s) not found, maybe they don’t exactly match the configuration ", table.concat(requires_raw, ", "))
if os.getenv("XREPO_WORKING") then
print("please attempt to export them with `-f/--configs=` option, e.g.")
print(" - xrepo export -f \"name=value, ...\" package")
print(" - xrepo export -m debug -k shared -f \"name=value, ...\" package")
else
print("please attempt to export them with `--extra=` option, e.g.")
print(" - xmake require --export --extra=\"{configs={...}}\" package")
print(" - xmake require --export --extra=\"{debug=true,configs={shared=true}}\" package")
end
end
end
-- leave environment
environment.leave()
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/require/search.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.lua
--
-- imports
import("core.base.task")
import("private.action.require.impl.utils.filter")
import("private.action.require.impl.repository")
import("private.action.require.impl.environment")
import("private.action.require.impl.search_packages")
-- search the given packages
function main(names)
-- no names?
if not names then
return
end
-- enter environment
environment.enter()
-- pull all repositories first if not exists
if not repository.pulled() then
task.run("repo", {update = true})
end
-- show title
print("The package names:")
-- search packages
for name, packages in pairs(search_packages(names)) do
if #packages > 0 then
-- show name
print(" %s: ", name)
-- show packages
for _, result in ipairs(packages) do
local name = result.name
local version = result.version
local reponame = result.reponame
local description = result.description
cprint(" -> ${color.dump.string}%s%s${clear}: %s %s", name,
version and ("-" .. version) or "",
description or "",
reponame and ("(in " .. reponame .. ")") or "")
end
end
end
-- leave environment
environment.leave()
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/require/uninstall.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 uninstall.lua
--
-- imports
import("core.base.task")
import("core.base.option")
import("private.action.require.impl.repository")
import("private.action.require.impl.environment")
import("private.action.require.impl.uninstall_packages")
import("private.action.require.impl.utils.get_requires")
-- uninstall the given packages
function main(requires_raw)
-- enter environment
environment.enter()
-- pull all repositories first if not exists
if not repository.pulled() then
task.run("repo", {update = true})
end
-- 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
-- uninstall packages
local packages = uninstall_packages(requires, {requires_extra = requires_extra})
for _, instance in ipairs(packages) do
print("uninstall: %s%s ok!", instance:name(), instance:version_str() and ("-" .. instance:version_str()) or "")
end
if not packages or #packages == 0 then
cprint("${bright}packages(%s) not found, maybe they don’t exactly match the configuration"
, requires_raw and table.concat(requires_raw, ", ") or "")
if os.getenv("XREPO_WORKING") then
print("please attempt to remove them with `-f/--configs=` option, e.g.")
print(" - xrepo remove -f \"name=value, ...\" package")
print(" - xrepo remove -m debug -k shared -f \"name=value, ...\" package")
else
print("please attempt to uninstall them with `--extra=` option, e.g.")
print(" - xmake require --uninstall --extra=\"{configs={...}}\" package")
print(" - xmake require --uninstall --extra=\"{debug=true,configs={shared=true}}\" package")
end
end
-- leave environment
environment.leave()
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/require/fetch.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 fetch.lua
--
-- imports
import("core.base.option")
import("core.base.hashset")
import("core.base.json")
import("core.project.project")
import("core.package.package", {alias = "core_package"})
import("core.tool.linker")
import("core.tool.compiler")
import("private.action.require.impl.package")
import("private.action.require.impl.repository")
import("private.action.require.impl.utils.get_requires")
-- fetch the given package info
function main(requires_raw)
-- 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 the fetching modes
local fetchmodes = option.get("fetch_modes")
if fetchmodes then
fetchmodes = hashset.from(fetchmodes:split(',', {plain = true}))
end
-- fetch all packages
local fetchinfos = {}
local nodeps = not (fetchmodes and fetchmodes:has("deps"))
for _, instance in irpairs(package.load_packages(requires, {requires_extra = requires_extra, nodeps = nodeps})) do
local fetchinfo = instance:fetch({external = (fetchmodes and fetchmodes:has("external") or false)})
if fetchinfo then
table.insert(fetchinfos, fetchinfo)
end
end
-- show results
if #fetchinfos > 0 then
local flags = {}
if fetchmodes and fetchmodes:has("cflags") then
for _, fetchinfo in ipairs(fetchinfos) do
table.join2(flags, compiler.map_flags("cxx", "define", fetchinfo.defines))
table.join2(flags, compiler.map_flags("cxx", "includedir", fetchinfo.includedirs))
table.join2(flags, compiler.map_flags("cxx", "sysincludedir", fetchinfo.sysincludedirs))
for _, cflag in ipairs(fetchinfo.cflags) do
table.insert(flags, cflag)
end
for _, cxflag in ipairs(fetchinfo.cxflags) do
table.insert(flags, cxflag)
end
for _, cxxflag in ipairs(fetchinfo.cxxflags) do
table.insert(flags, cxxflag)
end
end
end
if fetchmodes and fetchmodes:has("ldflags") then
for _, fetchinfo in ipairs(fetchinfos) do
table.join2(flags, linker.map_flags("binary", {"cxx"}, "linkdir", fetchinfo.linkdirs))
table.join2(flags, linker.map_flags("binary", {"cxx"}, "link", fetchinfo.links))
table.join2(flags, linker.map_flags("binary", {"cxx"}, "syslink", fetchinfo.syslinks))
for _, ldflag in ipairs(fetchinfo.ldflags) do
table.insert(flags, ldflags)
end
end
end
if #flags > 0 then
print(os.args(flags))
elseif fetchmodes and fetchmodes:has("json") then
print(json.encode(fetchinfos))
else
print(fetchinfos)
end
end
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/require/info.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 info.lua
--
-- imports
import("core.base.task")
import("core.base.option")
import("core.base.hashset")
import("core.project.project")
import("core.package.package", {alias = "core_package"})
import("devel.git")
import("utils.archive")
import("private.action.require.impl.utils.filter")
import("private.action.require.impl.utils.url_filename")
import("private.action.require.impl.package")
import("private.action.require.impl.repository")
import("private.action.require.impl.environment")
import("private.action.require.impl.utils.get_requires")
-- from xmake/system/remote?
function _from(instance)
local fetchinfo = instance:fetch()
if fetchinfo then
if instance:is_thirdparty() then
return ", ${green}3rd${clear}"
elseif instance:is_system() then
return ", ${green}system${clear}"
else
return ""
end
elseif #instance:urls() > 0 then
local repo = instance:repo()
local reponame = repo and repo:name() or "unknown"
return instance:is_supported() and format(", ${yellow}remote${clear}(in %s)", reponame) or format(", ${yellow}remote${clear}(${red}unsupported${clear} in %s)", reponame)
elseif instance:is_system() then
return ", ${red}missing${clear}"
else
return ""
end
end
-- get package info
function _info(instance)
local info = instance:version_str() and instance:version_str() or "no version"
info = info .. _from(instance)
info = info .. (instance:is_optional() and ", ${yellow}optional${clear}" or "")
return info
end
-- show the given package info
function main(requires_raw)
-- 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
-- enter environment
environment.enter()
-- pull all repositories first if not exists
if not repository.pulled() then
task.run("repo", {update = true})
end
-- show title
print("The package info of project:")
-- list all packages
for _, instance in ipairs(package.load_packages(requires, {requires_extra = requires_extra})) do
-- show package name
local requireinfo = instance:requireinfo() or {}
cprint(" ${color.dump.string_quote}require${clear}(%s): ", requireinfo.originstr)
-- show description
local description = instance:get("description")
if description then
cprint(" -> ${color.dump.string_quote}description${clear}: %s", description)
end
-- show version
local version = instance:version_str()
if version then
cprint(" -> ${color.dump.string_quote}version${clear}: %s", version)
end
-- show license
local license = instance:get("license")
if license then
cprint(" -> ${color.dump.string_quote}license${clear}: %s", license)
end
-- show urls
local urls = instance:urls()
if instance:is_precompiled() then
instance:fallback_build()
local urls_raw = instance:urls()
if urls_raw then
urls = table.join(urls, urls_raw)
end
end
if urls and #urls > 0 then
cprint(" -> ${color.dump.string_quote}urls${clear}:")
for _, url in ipairs(urls) do
print(" -> %s", filter.handle(url, instance))
if git.asgiturl(url) then
local url_alias = instance:url_alias(url)
cprint(" -> ${yellow}%s", instance:revision(url_alias) or instance:tag() or instance:version_str())
else
local sourcehash = instance:sourcehash(instance:url_alias(url))
if sourcehash then
cprint(" -> ${yellow}%s", sourcehash)
end
end
end
end
-- show repository
local repo = instance:repo()
if repo then
cprint(" -> ${color.dump.string_quote}repo${clear}: %s %s %s", repo:name(), repo:url(), repo:branch() or "")
end
-- show deps
local deps = instance:orderdeps()
if deps and #deps > 0 then
cprint(" -> ${color.dump.string_quote}deps${clear}:")
for _, dep in ipairs(deps) do
requireinfo = dep:requireinfo() or {}
cprint(" -> %s", requireinfo.originstr)
end
end
-- show cache directory
cprint(" -> ${color.dump.string_quote}cachedir${clear}: %s", instance:cachedir())
-- show install directory
cprint(" -> ${color.dump.string_quote}installdir${clear}: %s", instance:installdir())
-- show search directories and search names
cprint(" -> ${color.dump.string_quote}searchdirs${clear}: %s", table.concat(table.wrap(core_package.searchdirs()), path.envsep()))
local searchnames = hashset.new()
for _, url in ipairs(urls) do
url = filter.handle(url, instance)
if git.checkurl(url) then
searchnames:insert(instance:name() .. archive.extension(url) .. " ${dim}(git)${clear}")
searchnames:insert(path.basename(url_filename(url)) .. " ${dim}(git)${clear}")
else
local extension = archive.extension(url)
if extension then
searchnames:insert(instance:name() .. "-" .. instance:version_str() .. extension)
end
searchnames:insert(url_filename(url))
-- match github name mangling https://github.com/xmake-io/xmake/issues/1343
local github_name = url_filename.github_filename(url)
if github_name then
searchnames:insert(github_name)
end
end
end
cprint(" -> ${color.dump.string_quote}searchnames${clear}:")
for _, searchname in searchnames:keys() do
cprint(" -> %s", searchname)
end
-- show fetch info
cprint(" -> ${color.dump.string_quote}fetchinfo${clear}: %s", _info(instance))
local fetchinfo = instance:fetch()
if fetchinfo then
for name, info in pairs(fetchinfo) do
if type(info) ~= "table" then
info = tostring(info)
end
cprint(" -> ${color.dump.string_quote}%s${clear}: %s", name, table.concat(table.wrap(info), " "))
end
end
-- show supported platforms
local platforms = {}
local on_install = instance:get("install")
if type(on_install) == "table" then
for plat, _ in pairs(on_install) do
table.insert(platforms, plat)
end
else
table.insert(platforms, "all")
end
cprint(" -> ${color.dump.string_quote}platforms${clear}: %s", table.concat(platforms, ", "))
-- show requires
cprint(" -> ${color.dump.string_quote}requires${clear}:")
cprint(" -> ${cyan}plat${clear}: %s", instance:plat())
cprint(" -> ${cyan}arch${clear}: %s", instance:arch())
local configs_required = instance:configs()
if configs_required then
cprint(" -> ${cyan}configs${clear}:")
for name, value in pairs(configs_required) do
cprint(" -> %s: %s", name, value)
end
end
-- show user configs
local configs_defined = instance:get("configs")
if configs_defined then
cprint(" -> ${color.dump.string_quote}configs${clear}:")
for _, conf in ipairs(configs_defined) do
local configs_extra = instance:extraconf("configs", conf)
if configs_extra and not configs_extra.builtin then
cprintf(" -> ${cyan}%s${clear}: ", conf)
if configs_extra.description then
printf(configs_extra.description)
end
if configs_extra.default ~= nil then
printf(" (default: %s)", configs_extra.default)
elseif configs_extra.type ~= nil and configs_extra.type ~= "string" then
printf(" (type: %s)", configs_extra.type)
end
if configs_extra.readonly then
printf(" (readonly)")
end
print("")
if configs_extra.values then
cprint(" -> values: %s", string.serialize(configs_extra.values, true))
end
end
end
end
-- show builtin configs
local configs_defined = instance:get("configs")
if configs_defined then
cprint(" -> ${color.dump.string_quote}configs (builtin)${clear}:")
for _, conf in ipairs(configs_defined) do
local configs_extra = instance:extraconf("configs", conf)
if configs_extra and configs_extra.builtin then
cprintf(" -> ${cyan}%s${clear}: ", conf)
if configs_extra.description then
printf(configs_extra.description)
end
if configs_extra.default ~= nil then
printf(" (default: %s)", configs_extra.default)
elseif configs_extra.type ~= nil and configs_extra.type ~= "string" then
printf(" (type: %s)", configs_extra.type)
end
print("")
if configs_extra.values then
cprint(" -> values: %s", string.serialize(configs_extra.values, true))
end
end
end
end
-- show components
local components = instance:get("components")
if components then
cprint(" -> ${color.dump.string_quote}components${clear}: ")
for _, comp in ipairs(components) do
cprintf(" -> ${cyan}%s${clear}: ", comp)
local plaindeps = instance:extraconf("components", comp, "deps")
if plaindeps then
print("%s", table.concat(table.wrap(plaindeps), ", "))
else
print("")
end
end
end
-- show references
local references = instance:references()
if references then
cprint(" -> ${color.dump.string_quote}references${clear}:")
for projectdir, refdate in pairs(references) do
cprint(" -> %s: %s%s", refdate, projectdir, os.isdir(projectdir) and "" or " ${red}(not found)${clear}")
end
end
-- end
print("")
end
-- leave environment
environment.leave()
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/require/import.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 import.lua
--
-- imports
import("core.base.task")
import("core.base.option")
import("private.action.require.impl.repository")
import("private.action.require.impl.environment")
import("private.action.require.impl.import_packages")
import("private.action.require.impl.utils.get_requires")
-- import the given packages
function main(requires_raw)
-- enter environment
environment.enter()
-- pull all repositories first if not exists
if not repository.pulled() then
task.run("repo", {update = true})
end
-- 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
-- import packages
local packagedir = option.get("packagedir")
local packages = import_packages(requires, {requires_extra = requires_extra, packagedir = packagedir})
if not packages or #packages == 0 then
if requires_raw then
cprint("${bright}packages(%s) cannot be imported, maybe they don’t exactly match the configuration.", table.concat(requires_raw, ", "))
if os.getenv("XREPO_WORKING") then
print("please attempt to import them with `-f/--configs=` option, e.g.")
print(" - xrepo import -f \"name=value, ...\" package")
print(" - xrepo import -m debug -k shared -f \"name=value, ...\" package")
else
print("please attempt to import them with `--extra=` option, e.g.")
print(" - xmake require --import --extra=\"{configs={...}}\" package")
print(" - xmake require --import --extra=\"{debug=true,configs={shared=true}}\" package")
end
end
end
-- leave environment
environment.leave()
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/require/list.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 list.lua
--
-- imports
import("core.project.project")
import("core.base.task")
import("private.action.require.impl.package")
import("private.action.require.impl.repository")
import("private.action.require.impl.environment")
-- from xmake/system/remote?
function _from(instance)
local fetchinfo = instance:fetch()
if fetchinfo then
if instance:is_thirdparty() then
return ", ${green}3rd${clear}"
elseif instance:is_system() then
return ", ${green}system${clear}"
else
return ""
end
elseif #instance:urls() > 0 then
return instance:is_supported() and format(", ${yellow}remote${clear}(in %s)", instance:repo():name()) or format(", ${yellow}remote${clear}(${red}unsupported${clear} in %s)", instance:repo():name())
elseif instance:is_system() then
return ", ${red}missing${clear}"
else
return ""
end
end
-- get package info
function _info(instance)
local info = instance:version_str() and instance:version_str() or "no version"
info = info .. _from(instance)
info = info .. (instance:is_optional() and ", ${yellow}optional${clear}" or "")
return info
end
-- list packages
function main()
-- list all requires
print("The package dependencies of project:")
-- get requires
local requires, requires_extra = project.requires_str()
if not requires or #requires == 0 then
return
end
-- enter environment
environment.enter()
-- pull all repositories first if not exists
if not repository.pulled() then
task.run("repo", {update = true})
end
-- list all required packages
for _, instance in ipairs(package.load_packages(requires, {requires_extra = requires_extra})) do
cprint(" ${color.dump.string_quote}require${clear}(%s): %s", instance:requireinfo().originstr, _info(instance))
for _, dep in ipairs(instance:orderdeps()) do
cprint(" -> ${color.dump.string_quote}dep${clear}(%s): %s", dep:requireinfo().originstr, _info(dep))
end
local fetchinfo = instance:fetch()
if fetchinfo then
for name, info in pairs(fetchinfo) do
if type(info) == "table" then
cprint(" -> ${color.dump.string_quote}%s${clear}: %s", name, table.concat(info, " "))
else
cprint(" -> ${color.dump.string_quote}%s${clear}: %s", name, tostring(info))
end
end
end
end
-- leave environment
environment.leave()
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/require/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("core.base.option")
import("core.base.task")
import("lib.detect.find_tool")
import("private.action.require.impl.package")
import("private.action.require.impl.repository")
import("private.action.require.impl.environment")
import("private.action.require.impl.install_packages")
import("private.action.require.impl.utils.get_requires")
-- check missing packages
function _check_missing_packages(packages)
-- get all missing packages
local packages_missing = {}
local optional_missing = {}
for _, instance in ipairs(packages) do
if package.should_install(instance, {install_finished = true}) or (instance:is_fetchonly() and not instance:exists()) then
if instance:is_optional() then
optional_missing[instance:name()] = instance
else
table.insert(packages_missing, instance:name())
end
end
end
-- raise tips
if #packages_missing > 0 then
local cmd = "xmake repo -u"
if os.getenv("XREPO_WORKING") then
cmd = "xrepo update-repo"
end
raise("The packages(%s) not found, please run `%s` first!", table.concat(packages_missing, ", "), cmd)
end
-- save the optional missing packages
_g.optional_missing = optional_missing
end
-- install packages
function main(requires_raw)
-- 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
-- find git
environment.enter()
local git = find_tool("git")
environment.leave()
-- pull all repositories first if not exists
--
-- attempt to install git from the builtin-packages first if git not found
--
if git and (not repository.pulled() or option.get("upgrade")) then
task.run("repo", {update = true})
end
-- install packages
environment.enter()
local packages = install_packages(requires, {requires_extra = requires_extra})
if packages then
_check_missing_packages(packages)
end
environment.leave()
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/require/register.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 register.lua
--
-- imports
import("core.base.option")
import("core.base.task")
import("lib.detect.find_tool")
import("async.runjobs")
import("private.action.require.impl.package")
import("private.action.require.impl.repository")
import("private.action.require.impl.environment")
import("private.action.require.impl.register_packages")
import("private.action.require.impl.utils.get_requires")
-- register packages
function main(requires_raw)
-- 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
-- find git
environment.enter()
local git = find_tool("git")
environment.leave()
-- pull all repositories first if not exists
--
-- attempt to install git from the builtin-packages first if git not found
--
if git and (not repository.pulled() or option.get("upgrade")) then
task.run("repo", {update = true})
end
-- register packages
local packages = package.load_packages(requires, {requires_extra = requires_extra})
if packages then
-- fetch and register packages (with system) from local first
runjobs("fetch_packages", function (index)
local instance = packages[index]
if instance and (not option.get("force") or (option.get("shallow") and not instance:is_toplevel())) then
local oldenvs = os.getenvs()
instance:envs_enter()
instance:fetch()
os.setenvs(oldenvs)
end
end, {total = #packages, isolate = true})
-- register all required root packages to local cache
register_packages(packages)
end
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/require/scan.lua | --!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional scanrmation
-- regarding copyright ownership. The ASF licenses this file
-- to you 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 scan.lua
--
-- imports
import("core.base.option")
import("core.package.package")
-- scan local package
function _scan_package(packagedir)
-- show packages
local package_name = path.filename(packagedir)
for _, versiondir in ipairs(os.dirs(path.join(packagedir, "*"))) do
local version = path.filename(versiondir)
cprint("${color.dump.string}%s-%s${clear}:", package_name, version)
-- show package hash
for _, hashdir in ipairs(os.dirs(path.join(versiondir, "*"))) do
local hash = path.filename(hashdir)
local references_file = path.join(hashdir, "references.txt")
local referenced = false
local references = os.isfile(references_file) and io.load(references_file) or nil
if references then
for projectdir, refdate in pairs(references) do
if os.isdir(projectdir) then
referenced = true
break
end
end
end
local manifest_file = path.join(hashdir, "manifest.txt")
local manifest = os.isfile(manifest_file) and io.load(manifest_file) or nil
cprintf(" -> ${yellow}%s${clear}: ${green}%s, %s", hash, manifest and manifest.plat or "", manifest and manifest.arch or "")
if os.emptydir(hashdir) then
cprintf(", ${red}empty")
elseif not referenced then
cprintf(", ${red}unused")
elseif not manifest then
cprintf(", ${red}invalid")
end
print("")
if manifest and manifest.configs then
print(" -> %s", string.serialize(manifest.configs, {orderkeys = true, indent = false, strip = true}))
end
end
end
end
-- scan local packages
function main(package_names)
-- trace
print("scanning packages ..")
-- scan packages
local installdir = package.installdir()
if package_names then
for _, package_name in ipairs(package_names) do
for _, packagedir in ipairs(os.dirs(path.join(installdir, package_name:sub(1, 1), package_name))) do
_scan_package(packagedir)
end
end
else
for _, packagedir in ipairs(os.dirs(path.join(installdir, "*", "*"))) do
_scan_package(packagedir)
end
end
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/require/check.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.lua
--
-- imports
import("core.base.option")
import("core.base.hashset")
import("core.base.json")
import("core.project.project")
import("core.package.package", {alias = "core_package"})
import("private.action.require.impl.package")
import("private.action.require.impl.repository")
import("private.action.require.impl.utils.get_requires")
import("private.action.require.impl.actions.check", {alias = "action_check"})
-- check the given package info
function main(requires_raw)
-- 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
-- check the given packages
for _, instance in irpairs(package.load_packages(requires, {requires_extra = requires_extra, nodeps = true})) do
action_check(instance)
end
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/require/clean.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 clean.lua
--
-- imports
import("core.base.option")
import("core.base.hashset")
import("core.package.package")
import("core.cache.localcache")
import("private.action.require.impl.remove_packages")
-- clean the given or all package caches
function main(package_names)
local clean_modes = option.get("clean_modes")
if clean_modes then
clean_modes = hashset.from(clean_modes:split(","))
else
clean_modes = hashset.of("cache", "package")
end
-- clear cache directory
if clean_modes:has("cache") then
print("clearing caches ..")
os.rm(package.cachedir())
-- clear require cache
local require_cache = localcache.cache("package")
require_cache:clear()
require_cache:save()
end
-- clear all unused packages
if clean_modes:has("package") then
print("clearing packages ..")
remove_packages(package_names, {clean = true})
end
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/require/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("core.base.task")
import("lib.detect.find_tool")
import("private.action.require.impl.package")
import("private.action.require.impl.repository")
import("private.action.require.impl.environment")
import("private.action.require.impl.download_packages")
import("private.action.require.impl.utils.get_requires")
-- download packages
function main(requires_raw)
-- 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
-- find git
environment.enter()
local git = find_tool("git")
environment.leave()
-- pull all repositories first if not exists
--
-- attempt to download git from the builtin-packages first if git not found
--
if git and (not repository.pulled() or option.get("upgrade")) then
task.run("repo", {update = true})
end
-- download packages
environment.enter()
download_packages(requires, {requires_extra = requires_extra, nodeps = true})
environment.leave()
end
|
0 | repos/xmake/xmake/modules/private/action/require | repos/xmake/xmake/modules/private/action/require/impl/install_packages.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_packages.lua
--
-- imports
import("core.base.option")
import("core.base.hashset")
import("core.base.scheduler")
import("core.project.project")
import("core.base.tty")
import("async.runjobs")
import("utils.progress")
import("net.fasturl")
import("private.action.require.impl.package")
import("private.action.require.impl.lock_packages")
import("private.action.require.impl.register_packages")
import("private.action.require.impl.actions.check", {alias = "action_check"})
import("private.action.require.impl.actions.install", {alias = "action_install"})
import("private.action.require.impl.actions.download", {alias = "action_download"})
-- sort packages urls
function _sort_packages_urls(packages)
-- add all urls to fasturl and prepare to sort them together
for _, instance in pairs(packages) do
fasturl.add(instance:urls())
end
-- sort and update urls
for _, instance in pairs(packages) do
instance:urls_set(fasturl.sort(instance:urls()))
end
end
-- replace modified package
function _replace_package(packages, instance, extinstance)
for idx, rawinstance in ipairs(packages) do
if rawinstance == instance then
packages[idx] = extinstance
end
local deps = rawinstance._DEPS
for name, dep in pairs(deps) do
if dep == instance then
deps[name] = nil
deps[extinstance:name()] = extinstance
break
end
end
local parents = rawinstance._PARENTS
for name, parent in pairs(parents) do
if parent == instance then
parents[name] = nil
parents[extinstance:name()] = extinstance
break
end
end
local orderdeps = rawinstance._ORDERDEPS
for depidx, dep in ipairs(orderdeps) do
if dep == instance then
orderdeps[depidx] = extinstance
break
end
end
local librarydeps = rawinstance._LIBRARYDEPS
for depidx, dep in ipairs(librarydeps) do
if dep == instance then
librarydeps[depidx] = extinstance
break
end
end
local plaindeps = rawinstance._PLAINDEPS
for depidx, dep in ipairs(rawinstance._PLAINDEPS) do
if dep == instance then
plaindeps[depidx] = extinstance
break
end
end
end
end
-- replace modified packages
function _replace_packages(packages, packages_modified)
for _, package_modified in ipairs(packages_modified) do
local instance = package_modified.instance
local extinstance = package_modified.extinstance
_replace_package(packages, instance, extinstance)
end
end
-- get user confirm from 3rd package sources
-- @see https://github.com/xmake-io/xmake/issues/1140
function _get_confirm_from_3rd(packages)
-- get extpackages list
local extpackages_list = _g.extpackages_list
if not extpackages_list then
extpackages_list = {}
for _, instance in ipairs(packages) do
local extsources = instance:get("extsources")
local extsources_extra = instance:extraconf("extsources")
if extsources then
local extpackages = package.load_packages(extsources, extsources_extra)
for _, extinstance in ipairs(extpackages) do
table.insert(extpackages_list, {instance = instance, extinstance = extinstance})
end
end
end
_g.extpackages_list = extpackages_list
end
-- no extpackages?
if #extpackages_list == 0 then
print("no more packages!")
return
end
-- get confirm result
local result = utils.confirm({description = function ()
cprint("${bright color.warning}note: ${clear}select the following 3rd packages")
for idx, extinstance in ipairs(extpackages_list) do
local instance = extinstance.instance
local extinstance = extinstance.extinstance
cprint(" ${yellow}%d.${clear} %s ${yellow}->${clear} %s %s ${dim}%s",
idx, extinstance:name(),
instance:displayname(),
instance:version_str() or "",
package.get_configs_str(instance))
end
end, answer = function ()
cprint("please input number list: ${bright}n${clear} (1,2,..)")
io.flush()
return (io.read() or "n"):trim()
end})
-- get confirmed extpackages
local confirmed_extpackages = {}
if result and result ~= "n" then
for _, idx in ipairs(result:split(',')) do
idx = tonumber(idx)
if extpackages_list[idx] then
table.insert(confirmed_extpackages, extpackages_list[idx])
end
end
end
-- modify packages
if #confirmed_extpackages > 0 then
_replace_packages(packages, confirmed_extpackages)
return confirmed_extpackages
end
end
-- get user confirm
function _get_confirm(packages, opt)
opt = opt or {}
-- no confirmed packages?
if #packages == 0 then
return true
end
local result
local packages_modified
while result == nil do
-- get confirm result
result = utils.confirm({default = true, description = function ()
-- get packages for each repositories
local packages_repo = {}
local packages_group = {}
for _, instance in ipairs(packages) do
-- achive packages by repository
local reponame = instance:repo() and instance:repo():name() or (instance:is_system() and "system" or "")
if instance:is_thirdparty() then
reponame = instance:name():lower():split("::")[1]
end
packages_repo[reponame] = packages_repo[reponame] or {}
table.insert(packages_repo[reponame], instance)
-- achive packages by group
local group = instance:group()
if group then
packages_group[group] = packages_group[group] or {}
table.insert(packages_group[group], instance)
end
end
-- show tips
if opt.toolchain then
cprint("${bright color.warning}note: ${clear}install or modify (m) these ${bright}toolchain${clear} packages first (pass -y to skip confirm)?")
else
cprint("${bright color.warning}note: ${clear}install or modify (m) these packages (pass -y to skip confirm)?")
end
for reponame, packages in pairs(packages_repo) do
if reponame ~= "" then
print("in %s:", reponame)
end
local packages_showed = {}
for _, instance in ipairs(packages) do
if not packages_showed[tostring(instance)] then
local group = instance:group()
if group and packages_group[group] and #packages_group[group] > 1 then
for idx, package_in_group in ipairs(packages_group[group]) do
cprint(" ${yellow}%s${clear} %s %s ${dim}%s", idx == 1 and "->" or " or", package_in_group:displayname(), package_in_group:version_str() or "", package.get_configs_str(package_in_group))
packages_showed[tostring(package_in_group)] = true
end
packages_group[group] = nil
else
cprint(" ${yellow}->${clear} %s %s ${dim}%s", instance:displayname(), instance:version_str() or "", package.get_configs_str(instance))
packages_showed[tostring(instance)] = true
end
end
end
end
end, answer = function ()
cprint("please input: ${bright}y${clear} (y/n/m)")
io.flush()
return (io.read() or "false"):trim()
end})
-- modify to select 3rd packages?
if result == "m" then
packages_modified = _get_confirm_from_3rd(packages)
result = nil
else
-- get confirm result
result = option.boolean(result)
if type(result) ~= "boolean" then
result = true
end
end
end
return result, packages_modified
end
-- show upgraded packages
function _show_upgraded_packages(packages)
local upgraded_count = 0
for _, instance in ipairs(packages) do
local locked_requireinfo = package.get_locked_requireinfo(instance:requireinfo(), {force = true})
if locked_requireinfo and locked_requireinfo.version and instance:version() and instance:version():gt(locked_requireinfo.version) then
cprint(" ${color.dump.string}%s${clear}: %s -> ${color.success}%s", instance:displayname(), locked_requireinfo.version, instance:version_str())
upgraded_count = upgraded_count + 1
end
end
cprint("${bright}%d packages are upgraded!", upgraded_count)
end
-- fetch packages
function _fetch_packages(packages_fetch, installdeps)
-- init installed packages
local packages_fetched = {}
for _, instance in ipairs(packages_fetch) do
packages_fetched[tostring(instance)] = false
end
-- save terminal mode for stdout, @see https://github.com/xmake-io/xmake/issues/1924
local term_mode_stdout = tty.term_mode("stdout")
-- do fetch
local packages_fetching = {}
local packages_pending = table.copy(packages_fetch)
local working_count = 0
local fetching_count = 0
local parallelize = true
runjobs("fetch_packages", function (index)
-- fetch a new package
local instance = nil
while instance == nil and #packages_pending > 0 do
for idx, pkg in ipairs(packages_pending) do
-- all dependencies has been fetched? we fetch it now
local ready = true
local dep_not_ready = nil
for _, dep in pairs(installdeps[tostring(pkg)]) do
local fetched = packages_fetched[tostring(dep)]
if fetched == false then
ready = false
dep_not_ready = dep
break
end
end
-- get a package with the ready status
if ready then
instance = pkg
table.remove(packages_pending, idx)
break
elseif working_count == 0 then
if #packages_pending == 1 and dep_not_ready then
raise("package(%s): cannot be fetched, there are dependencies(%s) that cannot be fetched!", pkg:displayname(), dep_not_ready:displayname())
elseif #packages_pending == 1 then
raise("package(%s): cannot be fetched!", pkg:displayname())
end
end
end
if instance == nil and #packages_pending > 0 then
os.sleep(100)
end
end
if instance then
-- update working count
working_count = working_count + 1
-- disable parallelize?
if not instance:is_parallelize() then
parallelize = false
end
if not parallelize then
while fetching_count > 0 do
os.sleep(100)
end
end
fetching_count = fetching_count + 1
-- fetch this package
packages_fetching[index] = instance
local oldenvs = os.getenvs()
instance:envs_enter()
instance:lock()
instance:fetch()
instance:unlock()
os.setenvs(oldenvs)
-- fix terminal mode to avoid some subprocess to change it
--
-- @see https://github.com/xmake-io/xmake/issues/1924
-- https://github.com/xmake-io/xmake/issues/2329
if term_mode_stdout ~= tty.term_mode("stdout") then
tty.term_mode("stdout", term_mode_stdout)
end
-- next
parallelize = true
fetching_count = fetching_count - 1
packages_fetching[index] = nil
packages_fetched[tostring(instance)] = true
-- update working count
working_count = working_count - 1
end
packages_fetching[index] = nil
end, {total = #packages_fetch,
comax = (option.get("verbose") or option.get("diagnosis")) and 1 or 4,
isolate = true})
end
-- should fetch package?
function _should_fetch_package(instance)
if instance:is_fetchonly() or not option.get("force") or
(option.get("shallow") and not instance:is_toplevel()) then
return true
end
end
-- should install package?
function _should_install_package(instance)
_g.package_status_cache = _g.package_status_cache or {}
local result = _g.package_status_cache[tostring(instance)]
if result == nil then
result = package.should_install(instance) or false
_g.package_status_cache[tostring(instance)] = result
end
return result
end
-- do install packages
function _do_install_packages(packages_install, packages_download, installdeps)
-- we need to hide wait characters if is not a tty
local show_wait = io.isatty()
-- init installed packages
local packages_installed = {}
for _, instance in ipairs(packages_install) do
packages_installed[tostring(instance)] = false
end
-- save terminal mode for stdout, @see https://github.com/xmake-io/xmake/issues/1924
local term_mode_stdout = tty.term_mode("stdout")
-- do install
local progress_helper = show_wait and progress.new() or nil
local packages_installing = {}
local packages_downloading = {}
local packages_pending = table.copy(packages_install)
local packages_in_group = {}
local working_count = 0
local installing_count = 0
local parallelize = true
runjobs("install_packages", function (index)
-- fetch a new package
local instance = nil
while instance == nil and #packages_pending > 0 do
for idx, pkg in ipairs(packages_pending) do
-- all dependencies has been installed? we install it now
local ready = true
local dep_not_found = nil
for _, dep in pairs(installdeps[tostring(pkg)]) do
local installed = packages_installed[tostring(dep)]
if installed == false or (installed == nil and _should_install_package(dep) and not dep:is_optional()) then
ready = false
dep_not_found = dep
break
end
end
local group = pkg:group()
if ready and group then
-- this group has been installed? skip it
local group_status = packages_in_group[group]
if group_status == 1 then
table.remove(packages_pending, idx)
break
-- this group is installing? wait it
elseif group_status == 0 then
ready = false
end
end
-- get a package with the ready status
if ready then
instance = pkg
table.remove(packages_pending, idx)
break
elseif working_count == 0 then
if #packages_pending == 1 and dep_not_found then
raise("package(%s): cannot be installed, there are dependencies(%s) that cannot be installed!", pkg:displayname(), dep_not_found:displayname())
elseif #packages_pending == 1 then
raise("package(%s): cannot be installed!", pkg:displayname())
end
end
end
if instance == nil and #packages_pending > 0 then
os.sleep(100)
end
end
if instance then
-- update working count
working_count = working_count + 1
-- only install the first package in same group
local group = instance:group()
if not group or not packages_in_group[group] then
-- disable parallelize?
if not instance:is_parallelize() then
parallelize = false
end
if not parallelize then
while installing_count > 0 do
os.sleep(100)
end
end
installing_count = installing_count + 1
-- mark this group as 'installing'
if group then
packages_in_group[group] = 0
end
-- download this package first
local downloaded = true
if packages_download[tostring(instance)] then
packages_downloading[index] = instance
action_check(instance)
downloaded = action_download(instance)
packages_downloading[index] = nil
end
-- install this package
packages_installing[index] = instance
if downloaded then
if not action_install(instance) then
assert(instance:is_precompiled(), "package(%s) should be precompiled", instance:name())
-- we need to disable built and re-download and re-install it
instance:fallback_build()
action_check(instance)
action_download(instance)
action_install(instance)
end
end
-- reset package status cache
_g.package_status_cache = nil
-- register it to local cache if it is root required package
--
-- @note we need to register the package in time,
-- because other packages may be used, e.g. toolchain/packages
if instance:is_toplevel() then
register_packages({instance})
end
-- mark this group as 'installed' or 'failed'
if group then
packages_in_group[group] = instance:exists() and 1 or -1
end
-- next
parallelize = true
installing_count = installing_count - 1
packages_installing[index] = nil
packages_installed[tostring(instance)] = true
end
-- update working count
working_count = working_count - 1
end
packages_installing[index] = nil
packages_downloading[index] = nil
end, {total = #packages_install,
comax = (option.get("verbose") or option.get("diagnosis")) and 1 or 4,
isolate = true,
on_timer = function (running_jobs_indices)
-- do not print progress info if be verbose
if option.get("verbose") or not show_wait then
return
end
-- make installing and downloading packages list
local installing = {}
local downloading = {}
for _, index in ipairs(running_jobs_indices) do
local instance = packages_installing[index]
if instance then
table.insert(installing, instance:displayname())
end
local instance = packages_downloading[index]
if instance then
table.insert(downloading, instance:displayname())
end
end
-- we just return it directly if no thing is waited
-- @see https://github.com/xmake-io/xmake/issues/3535
if #installing == 0 and #downloading == 0 then
return
end
-- get waitobjs tips
local tips = nil
local waitobjs = scheduler.co_group_waitobjs("install_packages")
if waitobjs:size() > 0 then
local names = {}
for _, obj in waitobjs:keys() do
if obj:otype() == scheduler.OT_PROC then
table.insert(names, obj:name())
elseif obj:otype() == scheduler.OT_SOCK then
table.insert(names, "sock")
elseif obj:otype() == scheduler.OT_PIPE then
table.insert(names, "pipe")
end
end
names = table.unique(names)
if #names > 0 then
names = table.concat(names, ",")
if #names > 16 then
names = names:sub(1, 16) .. ".."
end
tips = string.format("(%d/%s)", waitobjs:size(), names)
end
end
-- fix terminal mode to avoid some subprocess to change it
-- @see https://github.com/xmake-io/xmake/issues/1924
if term_mode_stdout ~= tty.term_mode("stdout") then
tty.term_mode("stdout", term_mode_stdout)
end
-- trace
progress_helper:clear()
tty.erase_line_to_start().cr()
cprintf("${yellow} => ")
if #downloading > 0 then
cprintf("downloading ${color.dump.string}%s", table.concat(downloading, ", "))
end
if #installing > 0 then
cprintf("%sinstalling ${color.dump.string}%s", #downloading > 0 and ", " or "", table.concat(installing, ", "))
end
cprintf(" .. %s", tips and ("${dim}" .. tips .. "${clear} ") or "")
progress_helper:write()
end, exit = function(errors)
if errors then
tty.erase_line_to_start().cr()
io.flush()
end
end})
end
-- only enable the first package in same group and root packages
function _disable_other_packages_in_group(packages)
local registered_in_group = {}
for _, instance in ipairs(packages) do
local group = instance:group()
if instance:is_toplevel() and group then
local required_package = project.required_package(instance:alias() or instance:name())
if required_package then
if not registered_in_group[group] and required_package:enabled() then
registered_in_group[group] = true
elseif required_package:enabled() then
required_package:enable(false)
required_package:save()
end
end
end
end
end
-- sort packages for installation dependencies
function _sort_packages_for_installdeps(packages, installdeps, order_packages)
for _, instance in ipairs(packages) do
local deps = installdeps[tostring(instance)]
if deps then
_sort_packages_for_installdeps(deps, installdeps, order_packages)
end
table.insert(order_packages, instance)
end
end
-- get package installation dependencies
function _get_package_installdeps(packages)
local installdeps = {}
local packagesmap = {}
for _, instance in ipairs(packages) do
-- we need to use alias name first for toolchain/packages
packagesmap[instance:alias() or instance:name()] = instance
end
for _, instance in ipairs(packages) do
local deps = {}
if instance:orderdeps() then
deps = table.copy(instance:orderdeps())
end
-- patch toolchain/packages to installdeps, because we need to install toolchain package first
for _, toolchain in ipairs(instance:toolchains()) do
for _, packagename in ipairs(toolchain:config("packages")) do
if packagesmap[packagename] ~= instance then -- avoid loop recursion
table.insert(deps, packagesmap[packagename])
end
end
end
installdeps[tostring(instance)] = deps
end
return installdeps
end
-- install packages
function _install_packages(requires, opt)
opt = opt or {}
-- load packages
local packages = package.load_packages(requires, opt)
-- get package installation dependencies
local installdeps = _get_package_installdeps(packages)
-- sort packages for installdeps
local order_packages = {}
_sort_packages_for_installdeps(packages, installdeps, order_packages)
packages = table.unique(order_packages)
-- save terminal mode for stdout
local term_mode_stdout = tty.term_mode("stdout")
-- fetch and register packages (with system) from local first
local packages_fetch = {}
for _, instance in ipairs(packages) do
if _should_fetch_package(instance) then
table.insert(packages_fetch, instance)
end
end
_fetch_packages(packages_fetch, installdeps)
-- register all installed root packages to local cache
register_packages(packages)
-- filter packages
local packages_install = {}
local packages_download = {}
local packages_unsupported = {}
local packages_not_found = {}
local packages_unknown = {}
for _, instance in ipairs(packages) do
if _should_install_package(instance) then
if instance:is_supported() then
if #instance:urls() > 0 then
packages_download[tostring(instance)] = instance
end
table.insert(packages_install, instance)
elseif not instance:is_optional() then
if not instance:exists() and instance:is_system() then
table.insert(packages_unknown, instance)
else
table.insert(packages_unsupported, instance)
end
end
-- @see https://github.com/xmake-io/xmake/issues/2050
elseif not instance:exists() and not instance:is_optional() then
local requireinfo = instance:requireinfo()
if requireinfo and requireinfo.system then
table.insert(packages_not_found, instance)
end
end
end
-- exists unknown packages?
local has_errors = false
if #packages_unknown > 0 then
cprint("${bright color.warning}note: ${clear}the following packages were not found in any repository (check if they are spelled correctly):")
for _, instance in ipairs(packages_unknown) do
print(" -> %s", instance:displayname())
end
has_errors = true
end
-- exists unsupported packages?
if #packages_unsupported > 0 then
cprint("${bright color.warning}note: ${clear}the following packages are unsupported on $(plat)/$(arch):")
for _, instance in ipairs(packages_unsupported) do
print(" -> %s %s", instance:displayname(), instance:version_str() or "")
end
has_errors = true
end
-- exists not found packages?
if #packages_not_found > 0 then
if packages_not_found[1]:is_cross() then
cprint("${bright color.warning}note: ${clear}system package is not supported for cross-compilation currently, the following system packages cannot be found:")
else
cprint("${bright color.warning}note: ${clear}the following packages were not found on your system, try again after installing them:")
end
for _, instance in ipairs(packages_not_found) do
print(" -> %s %s", instance:displayname(), instance:version_str() or "")
end
has_errors = true
end
if has_errors then
raise()
end
-- get user confirm
local confirm, packages_modified = _get_confirm(packages_install, opt)
if not confirm then
local packages_must = {}
for _, instance in ipairs(packages_install) do
if not instance:is_optional() then
table.insert(packages_must, instance:displayname())
end
end
if #packages_must > 0 then
raise("packages(%s): must be installed!", table.concat(packages_must, ", "))
else
-- continue other actions
return
end
end
-- show upgraded information
if option.get("upgrade") then
print("upgrading packages ..")
end
-- some packages are modified? we need to fix packages list and all deps
if packages_modified then
order_packages = {}
_replace_packages(packages, packages_modified)
installdeps = _get_package_installdeps(packages)
_sort_packages_for_installdeps(packages, installdeps, order_packages)
packages = table.unique(order_packages)
end
-- sort package urls
_sort_packages_urls(packages_download)
-- install all required packages from repositories
_do_install_packages(packages_install, packages_download, installdeps)
-- disable other packages in same group
_disable_other_packages_in_group(packages)
-- re-register and refresh all root packages to local cache,
-- because there may be some missing optional dependencies reinstalled
register_packages(packages)
-- show upgraded packages
if option.get("upgrade") then
_show_upgraded_packages(packages)
end
return packages
end
function main(requires, opt)
-- we need to install toolchain packages first,
-- because we will call compiler-specific api in package.on_load,
-- and we will check package toolchains before calling package.on_load
--
-- @see https://github.com/xmake-io/xmake/pull/5466
local packages = {}
table.join2(packages, _install_packages(requires, table.join(opt or {}, {toolchain = true})))
table.join2(packages, _install_packages(requires, opt))
-- lock packages
lock_packages(packages)
return packages
end
|
0 | repos/xmake/xmake/modules/private/action/require | repos/xmake/xmake/modules/private/action/require/impl/import_packages.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 import_packages.lua
--
-- imports
import("core.package.package", {alias = "core_package"})
import("private.action.require.impl.package")
-- import packages
function main(requires, opt)
opt = opt or {}
local packages = {}
local packagedir = assert(opt.packagedir)
for _, instance in ipairs(package.load_packages(requires, opt)) do
-- get import path
local installdir = instance:installdir()
local rootdir = core_package.installdir()
local importpath, count = installdir:replace(rootdir, packagedir, {plain = true})
-- import this package
if importpath and count == 1 then
print("importing %s-%s %s", instance:displayname(), instance:version_str(), package.get_configs_str(instance))
cprint(" ${yellow}<-${clear} %s", importpath)
os.tryrm(installdir)
os.cp(importpath, installdir, {symlink = true})
table.insert(packages, instance)
end
end
return packages
end
|
0 | repos/xmake/xmake/modules/private/action/require | repos/xmake/xmake/modules/private/action/require/impl/environment.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 environment.lua
--
-- imports
import("core.project.config")
import("lib.detect.find_tool")
import("private.action.require.impl.packagenv")
import("private.action.require.impl.install_packages")
-- enter environment
--
-- ensure that we can find some basic tools: git, unzip, ...
--
-- If these tools not exist, we will install it first.
--
function enter()
-- unzip or 7zip is necessary
if not find_tool("unzip") and not find_tool("7z") then
raise("failed to find unzip or 7zip! please install one of them first")
end
-- enter the environments of git
_g._OLDENVS = packagenv.enter("git")
-- git not found? install it first
local packages = {}
local git = find_tool("git")
if not git then
table.join2(packages, install_packages("git"))
end
-- missing the necessary unarchivers for *.gz, *.7z? install them first, e.g. gzip, 7z, tar ..
local zip = (find_tool("gzip") and find_tool("tar")) or find_tool("7z")
if not zip then
table.join2(packages, install_packages("7z"))
end
-- enter the environments of installed packages
for _, instance in ipairs(packages) do
instance:envs_enter()
end
-- we need to force to detect and flush detect cache after loading all environments
if not git then
find_tool("git", {force = true})
end
if not zip then
find_tool("7z", {force = true})
end
end
-- leave environment
function leave()
local oldenvs = _g._OLDENVS
if oldenvs then
os.setenvs(oldenvs)
end
end
|
0 | repos/xmake/xmake/modules/private/action/require | repos/xmake/xmake/modules/private/action/require/impl/lock_packages.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 lock_packages.lua
--
-- imports
import("core.project.project")
import("core.project.config")
import("devel.git")
import("private.action.require.impl.utils.filter")
import("private.action.require.impl.utils.requirekey")
-- get locked package key
function _get_packagelock_key(instance)
local requireinfo = instance:requireinfo()
return requireinfo and requireinfo.requirekey
end
-- lock package
function _lock_package(instance)
local result = {}
local repo = instance:repo()
result.version = instance:version_str()
result.branch = instance:branch()
result.tag = instance:tag()
if repo then
local lastcommit
local manifest = instance:manifest_load()
if manifest and manifest.repo then
lastcommit = manifest.repo.commit
end
if not lastcommit then
lastcommit = repo:commit()
end
result.repo = {url = repo:url(), commit = lastcommit, branch = repo:branch()}
end
return result
end
-- lock all required packages
function main(packages)
if project.policy("package.requires_lock") then
local plat = config.plat() or os.subhost()
local arch = config.arch() or so.subarch()
local key = plat .. "|" .. arch
local results = os.isfile(project.requireslock()) and io.load(project.requireslock()) or {}
results.__meta__ = results.__meta__ or {}
results.__meta__.version = project.requireslock_version()
results[key] = {}
for _, instance in ipairs(packages) do
local packagelock_key = _get_packagelock_key(instance)
results[key][packagelock_key] = _lock_package(instance)
end
io.writefile(project.requireslock(), string.serialize(results, {orderkeys = true}), {encoding = "binary"})
end
end
|
0 | repos/xmake/xmake/modules/private/action/require | repos/xmake/xmake/modules/private/action/require/impl/repository.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 repository.lua
--
-- imports
import("core.base.option")
import("core.base.global")
import("core.project.config")
import("core.project.project")
import("core.package.repository")
import("devel.git")
import("net.proxy")
-- get package directory from the locked repository
function _get_packagedir_from_locked_repo(packagename, locked_repo)
-- find global repository directory
local repo_global
for _, repo in ipairs(repositories()) do
if locked_repo.url == repo:url() and locked_repo.branch == repo:branch() then
repo_global = repo
break
end
end
local reponame = hash.uuid(locked_repo.url .. (locked_repo.commit or "")):gsub("%-", ""):lower() .. ".lock"
-- get local repodir
local repodir_local
if os.isdir(locked_repo.url) then
repodir_local = locked_repo.url
elseif not locked_repo.commit and repo_global then
repodir_local = repo_global:directory()
else
repodir_local = path.join(config.directory(), "repositories", reponame)
end
-- get the network mode?
local network = project.policy("network.mode")
if network == nil then
network = global.get("network")
end
-- clone repository to local
local lastcommit
if not os.isdir(repodir_local) then
if repo_global then
git.clone(repo_global:directory(), {treeless = true, checkout = false, verbose = option.get("verbose"), outputdir = repodir_local, autocrlf = false})
lastcommit = repo_global:commit()
elseif network ~= "private" then
local remoteurl = proxy.mirror(locked_repo.url) or locked_repo.url
git.clone(remoteurl, {verbose = option.get("verbose"), branch = locked_repo.branch, outputdir = repodir_local, autocrlf = false})
else
wprint("we cannot lock repository(%s) in private network mode!", locked_repo.url)
return
end
end
-- lock commit
local ok
if locked_repo.commit and os.isdir(path.join(repodir_local, ".git")) then
lastcommit = lastcommit or try {function()
return git.lastcommit({repodir = repodir_local})
end}
if locked_repo.commit ~= lastcommit then
-- try checkout to the given commit
ok = try {function () git.checkout(locked_repo.commit, {verbose = option.get("verbose"), repodir = repodir_local}); return true end}
if not ok then
if network ~= "private" then
-- pull the latest commit
local remoteurl = proxy.mirror(locked_repo.url) or locked_repo.url
git.pull({verbose = option.get("verbose"), remote = remoteurl, branch = locked_repo.branch, repodir = repodir_local, force = true})
-- re-checkout to the given commit
ok = try {function () git.checkout(locked_repo.commit, {verbose = option.get("verbose"), repodir = repodir_local}); return true end}
else
wprint("we cannot lock repository(%s) in private network mode!", locked_repo.url)
return
end
end
else
ok = true
end
end
-- find package directory
local foundir
if ok then
local dir = path.join(repodir_local, "packages", packagename:sub(1, 1), packagename)
if os.isdir(dir) and os.isfile(path.join(dir, "xmake.lua")) then
local repo = repository.load(reponame, locked_repo.url, locked_repo.branch, false)
foundir = {dir, repo}
vprint("lock package(%s) in %s from repository(%s)/%s", packagename, dir, locked_repo.url, locked_repo.commit)
end
end
return foundir
end
-- get all repositories
function repositories()
if _g._REPOSITORIES then
return _g._REPOSITORIES
end
-- get all repositories (local first)
local repos = table.join(repository.repositories(false), repository.repositories(true))
_g._REPOSITORIES = repos
return repos
end
-- the remote repositories have been pulled?
function pulled()
local network = project.policy("network.mode")
if network == nil then
network = global.get("network")
end
if network ~= "private" then
for _, repo in ipairs(repositories()) do
if not os.isdir(repo:url()) then
-- repository not found? or xmake has been re-installed
local repodir = repo:directory()
local updatefile = path.join(repodir, "updated")
if not os.isfile(updatefile) or (os.isfile(updatefile) and os.mtime(os.programfile()) > os.mtime(updatefile)) then
-- fix broken empty directory
-- @see https://github.com/xmake-io/xmake/issues/2159
if os.isdir(repodir) and os.emptydir(repodir) then
os.tryrm(repodir)
end
return false
end
end
end
end
return true
end
-- get package directory from repositories
function packagedir(packagename, opt)
-- strip trailng ~tag, e.g. zlib~debug
opt = opt or {}
packagename = packagename:lower()
if packagename:find('~', 1, true) then
packagename = packagename:gsub("~.+$", "")
end
-- get cache key
local reponame = opt.name
local cachekey = packagename
local locked_repo = opt.locked_repo
if locked_repo then
cachekey = cachekey .. locked_repo.url .. (locked_repo.commit or "") .. (locked_repo.branch or "")
end
local packagedirs = _g._PACKAGEDIRS
if not packagedirs then
packagedirs = {}
_g._PACKAGEDIRS = packagedirs
end
-- get the package directory
local foundir = packagedirs[cachekey]
if not foundir then
-- find the package directory from the locked repository
if locked_repo then
foundir = _get_packagedir_from_locked_repo(packagename, locked_repo)
end
-- find the package directory from repositories
if not foundir then
for _, repo in ipairs(repositories()) do
local dir = path.join(repo:directory(), "packages", packagename:sub(1, 1), packagename)
if os.isdir(dir) and os.isfile(path.join(dir, "xmake.lua")) and (not reponame or reponame == repo:name()) then
foundir = {dir, repo}
break
end
end
end
foundir = foundir or {}
packagedirs[cachekey] = foundir
end
-- save the current commit
local dir = foundir[1]
local repo = foundir[2]
if repo and not repo:commit() then
local lastcommit = try {function()
if os.isdir(path.join(repo:directory(), ".git")) then
return git.lastcommit({repodir = repo:directory()})
end
end}
repo:commit_set(lastcommit)
end
return dir, repo
end
-- get artifacts manifest from repositories
function artifacts_manifest(packagename, version)
packagename = packagename:lower()
for _, repo in ipairs(repositories()) do
local manifestfile = path.join(repo:directory(), "packages", packagename:sub(1, 1), packagename, version, "manifest.txt")
if os.isfile(manifestfile) then
return io.load(manifestfile)
end
end
end
-- search package directories from repositories
function searchdirs(name)
-- find the package directories from all repositories
local unique = {}
local packageinfos = {}
for _, repo in ipairs(repositories()) do
for _, file in ipairs(os.files(path.join(repo:directory(), "packages", "*", string.ipattern("*" .. name .. "*"), "xmake.lua"))) do
local dir = path.directory(file)
local subdirname = path.basename(path.directory(dir))
if #subdirname == 1 then -- ignore l/luajit/port/xmake.lua
local packagename = path.filename(dir)
if not unique[packagename] then
table.insert(packageinfos, {name = packagename, repo = repo, packagedir = path.directory(file)})
unique[packagename] = true
end
end
end
end
return packageinfos
end
|
0 | repos/xmake/xmake/modules/private/action/require | repos/xmake/xmake/modules/private/action/require/impl/download_packages.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_packages.lua
--
-- imports
import("core.base.option")
import("core.base.hashset")
import("core.base.scheduler")
import("core.project.project")
import("core.base.tty")
import("async.runjobs")
import("utils.progress")
import("net.fasturl")
import("private.action.require.impl.package")
import("private.action.require.impl.lock_packages")
import("private.action.require.impl.register_packages")
import("private.action.require.impl.actions.download", {alias = "action_download"})
-- sort packages urls
function _sort_packages_urls(packages)
-- add all urls to fasturl and prepare to sort them together
for _, instance in pairs(packages) do
fasturl.add(instance:urls())
end
-- sort and update urls
for _, instance in pairs(packages) do
instance:urls_set(fasturl.sort(instance:urls()))
end
end
-- get user confirm
function _get_confirm(packages)
-- no confirmed packages?
if #packages == 0 then
return true
end
local result
local packages_modified
while result == nil do
-- get confirm result
result = utils.confirm({default = true, description = function ()
-- get packages for each repositories
local packages_repo = {}
for _, instance in ipairs(packages) do
-- achive packages by repository
local reponame = instance:repo() and instance:repo():name() or (instance:is_system() and "system" or "")
if instance:is_thirdparty() then
reponame = instance:name():lower():split("::")[1]
end
packages_repo[reponame] = packages_repo[reponame] or {}
table.insert(packages_repo[reponame], instance)
end
-- show tips
cprint("${bright color.warning}note: ${clear}download these packages (pass -y to skip confirm)?")
for reponame, packages in pairs(packages_repo) do
if reponame ~= "" then
print("in %s:", reponame)
end
local packages_showed = {}
for _, instance in ipairs(packages) do
if not packages_showed[tostring(instance)] then
cprint(" ${yellow}->${clear} %s %s ${dim}%s", instance:displayname(), instance:version_str() or "", package.get_configs_str(instance))
packages_showed[tostring(instance)] = true
end
end
end
end, answer = function ()
cprint("please input: ${bright}y${clear} (y/n)")
io.flush()
return (io.read() or "false"):trim()
end})
-- get confirm result
result = option.boolean(result)
if type(result) ~= "boolean" then
result = true
end
end
return result, packages_modified
end
-- should download package?
function _should_download_package(instance)
_g.package_status_cache = _g.package_status_cache or {}
local result = _g.package_status_cache[tostring(instance)]
if result == nil then
result = package.should_install(instance) or false
_g.package_status_cache[tostring(instance)] = result
end
return result
end
-- download packages
function _download_packages(packages_download)
-- we need to hide wait characters if is not a tty
local show_wait = io.isatty()
-- init downloaded packages
local packages_downloaded = {}
for _, instance in ipairs(packages_download) do
packages_downloaded[tostring(instance)] = false
end
-- save terminal mode for stdout, @see https://github.com/xmake-io/xmake/issues/1924
local term_mode_stdout = tty.term_mode("stdout")
-- do download
local progress_helper = show_wait and progress.new() or nil
local packages_downloading = {}
local packages_pending = table.copy(packages_download)
local working_count = 0
local downloading_count = 0
runjobs("download_packages", function (index)
-- fetch a new package
local instance = nil
while instance == nil and #packages_pending > 0 do
instance = packages_pending[1]
table.remove(packages_pending, 1)
end
if instance then
working_count = working_count + 1
downloading_count = downloading_count + 1
packages_downloading[index] = instance
-- download this package
action_download(instance, {outputdir = option.get("packagedir"), download_only = true})
-- reset package status cache
_g.package_status_cache = nil
-- next
downloading_count = downloading_count - 1
packages_downloading[index] = nil
packages_downloaded[tostring(instance)] = true
-- update working count
working_count = working_count - 1
end
end, {total = #packages_download,
comax = (option.get("verbose") or option.get("diagnosis")) and 1 or 4,
isolate = true,
on_timer = function (running_jobs_indices)
-- do not print progress info if be verbose
if option.get("verbose") or not show_wait then
return
end
-- make downloading packages list
local downloading = {}
for _, index in ipairs(running_jobs_indices) do
local instance = packages_downloading[index]
if instance then
table.insert(downloading, instance:displayname())
end
end
-- we just return it directly if no thing is waited
-- @see https://github.com/xmake-io/xmake/issues/3535
if #downloading == 0 and #downloading == 0 then
return
end
-- get waitobjs tips
local tips = nil
local waitobjs = scheduler.co_group_waitobjs("download_packages")
if waitobjs:size() > 0 then
local names = {}
for _, obj in waitobjs:keys() do
if obj:otype() == scheduler.OT_PROC then
table.insert(names, obj:name())
elseif obj:otype() == scheduler.OT_SOCK then
table.insert(names, "sock")
elseif obj:otype() == scheduler.OT_PIPE then
table.insert(names, "pipe")
end
end
names = table.unique(names)
if #names > 0 then
names = table.concat(names, ",")
if #names > 16 then
names = names:sub(1, 16) .. ".."
end
tips = string.format("(%d/%s)", waitobjs:size(), names)
end
end
-- fix terminal mode to avoid some subprocess to change it
-- @see https://github.com/xmake-io/xmake/issues/1924
if term_mode_stdout ~= tty.term_mode("stdout") then
tty.term_mode("stdout", term_mode_stdout)
end
-- trace
progress_helper:clear()
tty.erase_line_to_start().cr()
cprintf("${yellow} => ")
if #downloading > 0 then
cprintf("downloading ${color.dump.string}%s", table.concat(downloading, ", "))
end
cprintf(" .. %s", tips and ("${dim}" .. tips .. "${clear} ") or "")
progress_helper:write()
end, exit = function(errors)
if errors then
tty.erase_line_to_start().cr()
io.flush()
end
end})
end
-- download packages
function main(requires, opt)
opt = opt or {}
-- load packages
local packages = package.load_packages(requires, opt)
-- save terminal mode for stdout
local term_mode_stdout = tty.term_mode("stdout")
-- filter packages
local packages_download = {}
local packages_unsupported = {}
local packages_unknown = {}
for _, instance in ipairs(packages) do
if _should_download_package(instance) then
if instance:is_supported() then
if #instance:urls() > 0 then
packages_download[tostring(instance)] = instance
end
table.insert(packages_download, instance)
elseif not instance:is_optional() then
if not instance:exists() and instance:is_system() then
table.insert(packages_unknown, instance)
else
table.insert(packages_unsupported, instance)
end
end
end
end
-- exists unknown packages?
local has_errors = false
if #packages_unknown > 0 then
cprint("${bright color.warning}note: ${clear}the following packages were not found in any repository (check if they are spelled correctly):")
for _, instance in ipairs(packages_unknown) do
print(" -> %s", instance:displayname())
end
has_errors = true
end
-- exists unsupported packages?
if #packages_unsupported > 0 then
cprint("${bright color.warning}note: ${clear}the following packages are unsupported on $(plat)/$(arch):")
for _, instance in ipairs(packages_unsupported) do
print(" -> %s %s", instance:displayname(), instance:version_str() or "")
end
has_errors = true
end
if has_errors then
raise()
end
-- get user confirm
local confirm = _get_confirm(packages_download)
if not confirm then
return
end
-- sort package urls
_sort_packages_urls(packages_download)
-- download all required packages from repositories
_download_packages(packages_download)
cprint("outputdir: ${bright}%s", option.get("packagedir"))
cprint("${color.success}install packages ok")
return packages
end
|
0 | repos/xmake/xmake/modules/private/action/require | repos/xmake/xmake/modules/private/action/require/impl/register_packages.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 register_packages.lua
--
-- imports
import("core.project.project")
import("core.cache.localcache")
-- register required package environments
-- envs: bin path for *.dll, program ..
function _register_required_package_envs(instance, envs)
for name, values in table.orderpairs(instance:envs()) do
envs[name] = envs[name] or {}
table.join2(envs[name], values)
end
end
-- register required package libraries
-- libs: includedirs, links, linkdirs ...
function _register_required_package_libs(instance, required_package, is_deps)
if instance:is_library() then
local fetchinfo = table.clone(instance:fetch())
if fetchinfo then
fetchinfo.name = nil
if is_deps then
-- we only need reserve license for root package
--
-- @note the license compatibility between the root package and
-- its dependent packages is guaranteed by the root package itself
--
fetchinfo.license = nil
-- we only need some infos for root package
fetchinfo.version = nil
fetchinfo.static = nil
fetchinfo.shared = nil
fetchinfo.installdir = nil
fetchinfo.extras = nil
fetchinfo.components = nil
end
-- merge into the root values
local components = fetchinfo.components
fetchinfo.components = nil
required_package:add(fetchinfo)
-- save components list and dependencies
if components then
required_package:set("__components_deps", instance:components_deps())
required_package:set("__components_default", instance:components_default())
required_package:set("__components_orderlist", instance:components_orderlist())
end
-- merge into the components values
local required_components = required_package:get("components")
if required_components then
fetchinfo.libfiles = nil
local components_base = required_components.__base or {}
for k, v in table.orderpairs(fetchinfo) do
local values = table.wrap(components_base[k])
components_base[k] = table.unwrap(table.unique(table.join(values, v)))
end
required_components.__base = components_base
else
required_package:set("components", components)
end
end
end
end
-- register the base info of required package
function _register_required_package_base(instance, required_package)
if not instance:is_system() and not instance:is_thirdparty() then
required_package:set("installdir", instance:installdir())
end
end
-- register the required local package
function _register_required_package(instance, required_package)
-- disable it if this package is missing
if not instance:exists() then
required_package:enable(false)
else
-- clear require info first
required_package:clear()
-- add packages info with all dependencies
local envs = {}
_register_required_package_base(instance, required_package)
_register_required_package_libs(instance, required_package)
_register_required_package_envs(instance, envs)
for _, dep in ipairs(instance:librarydeps()) do
if instance:is_library() then
_register_required_package_libs(dep, required_package, true)
end
end
for _, dep in ipairs(instance:orderdeps()) do
if not dep:is_private() then
_register_required_package_envs(dep, envs)
end
end
if #table.keys(envs) > 0 then
required_package:add({envs = envs})
end
-- enable this require info
required_package:enable(true)
end
-- save this require info and flush the whole cache file
required_package:save()
end
-- register all required root packages to local cache
function main(packages)
-- register to package cache for add_packages()
for _, instance in ipairs(packages) do
if instance:is_toplevel() then
local required_packagename = instance:alias() or instance:name()
local required_package = project.required_package(required_packagename)
if required_package then
_register_required_package(instance, required_package)
end
end
end
-- register references for `xrepo clean`
-- and we use glocal memory cache to save all packages from multiple arch/mode, e.g. `xmake project -m "debug,release" -k vsxmake`
-- @see https://github.com/xmake-io/xmake/issues/3679
local references = _g.references or {}
_g.references = references
for _, instance in ipairs(packages) do
if not instance:is_system() and not instance:is_thirdparty() then
local installdir = instance:installdir({readonly = true})
if os.isdir(installdir) then
table.insert(references, installdir)
end
end
end
localcache.set("references", "packages", table.unique(references))
localcache.save("references")
end
|
0 | repos/xmake/xmake/modules/private/action/require | repos/xmake/xmake/modules/private/action/require/impl/packagenv.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 packagenv.lua
--
-- imports
import("core.base.hashset")
import("core.package.package", {alias = "core_package"})
-- enter the package environments
function _enter_package(package_name, envs, pathenvs, installdir)
if pathenvs then
pathenvs = hashset.from(pathenvs)
end
for name, values in pairs(envs) do
if pathenvs and pathenvs:has(name) then
for _, value in ipairs(values) do
if path.is_absolute(value) then
os.addenv(name, value)
else
os.addenv(name, path.normalize(path.join(installdir, value)))
end
end
else
os.addenv(name, table.unpack(table.wrap(values)))
end
end
end
-- enter environment of the given binary packages, git, 7z, ..
function enter(...)
local oldenvs = os.getenvs()
for _, name in ipairs({...}) do
for _, manifest_file in ipairs(os.files(path.join(core_package.installdir(), name:sub(1, 1), name, "*", "*", "manifest.txt"))) do
local manifest = io.load(manifest_file)
if manifest and manifest.plat == os.host() and manifest.arch == os.arch() then
_enter_package(name, manifest.envs, manifest.pathenvs, path.directory(manifest_file))
end
end
end
return oldenvs
end
|
0 | repos/xmake/xmake/modules/private/action/require | repos/xmake/xmake/modules/private/action/require/impl/search_packages.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_packages.lua
--
-- search packages from repositories
function _search_packages(name, opt)
-- 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 = "xmake"
else
manager_name = manager_name:lower():trim()
end
-- search packages
local packages = {}
local result = import("package.manager." .. manager_name .. ".search_package", {anonymous = true})(package_name, opt)
if result then
table.join2(packages, result)
end
return packages
end
-- search packages
function main(names, opt)
local results = {}
for _, name in ipairs(names) do
local packages = _search_packages(name, opt)
if packages then
table.sort(packages, function (a, b)
return name:levenshtein(a.name) < name:levenshtein(b.name)
end)
results[name] = packages
end
end
return results
end
|
0 | repos/xmake/xmake/modules/private/action/require | repos/xmake/xmake/modules/private/action/require/impl/uninstall_packages.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 uninstall_packages.lua
--
-- imports
import("core.cache.localcache")
import("private.action.require.impl.package")
-- uninstall packages
function main(requires, opt)
-- init options
opt = opt or {}
-- do not remove dependent packages
opt.nodeps = true
-- clear the local cache
localcache.clear()
-- remove all packages
local packages = {}
for _, instance in ipairs(package.load_packages(requires, opt)) do
if os.isfile(instance:manifest_file()) then
table.insert(packages, instance)
end
os.tryrm(instance:installdir())
end
return packages
end
|
0 | repos/xmake/xmake/modules/private/action/require | repos/xmake/xmake/modules/private/action/require/impl/remove_packages.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 remove_packages.lua
--
-- imports
import("core.base.option")
import("core.base.hashset")
import("core.package.package")
import("core.cache.localcache")
-- get package configs string
function _get_package_configs_str(manifest_file)
local manifest = os.isfile(manifest_file) and io.load(manifest_file)
if manifest then
local configs = {}
for k, v in pairs(manifest.configs) do
if type(v) == "boolean" then
table.insert(configs, k .. ":" .. (v and "y" or "n"))
else
table.insert(configs, k .. ":" .. string.serialize(v, {strip = true, indent = false}))
end
end
local configs_str = #configs > 0 and "[" .. table.concat(configs, ", ") .. "]" or ""
local limitwidth = math.floor(os.getwinsize().width * 2 / 3)
if #configs_str > limitwidth then
configs_str = configs_str:sub(1, limitwidth) .. " ..)"
end
return configs_str
end
end
-- has reference from project?
-- @see https://github.com/xmake-io/xmake/issues/3679
function _has_reference_from_project(projectdir, packagedir)
local project_references_file = path.join(projectdir, ".xmake", os.host(), os.arch(), "cache", "references")
if os.isfile(project_references_file) then
local references = io.load(project_references_file)
if references and references.packages then
local packages = hashset.from(references.packages)
if packages:has(packagedir) then
return true
end
end
end
end
-- remove package directories
function _remove_packagedirs(packagedir, opt)
-- clear them
local package_name = path.filename(packagedir)
for _, versiondir in ipairs(os.dirs(path.join(packagedir, "*"))) do
local version = path.filename(versiondir)
for _, hashdir in ipairs(os.dirs(path.join(versiondir, "*"))) do
local hash = path.filename(hashdir)
local references_file = path.join(hashdir, "references.txt")
local referenced = false
local references = os.isfile(references_file) and io.load(references_file) or nil
if references then
for projectdir, refdate in pairs(references) do
if os.isdir(projectdir) and _has_reference_from_project(projectdir, hashdir) then
referenced = true
break
end
end
end
local manifest_file = path.join(hashdir, "manifest.txt")
local status = nil
if os.emptydir(hashdir) then
status = "empty"
elseif not referenced then
status = "unused"
elseif not os.isfile(manifest_file) then
status = "invalid"
end
if not opt.clean or status then
local configs_str = _get_package_configs_str(manifest_file) or "[]"
local description = string.format("remove ${color.dump.string}%s-%s${clear}/${yellow}%s${clear}\n -> ${dim}%s${clear} (${red}%s${clear})", package_name, version, hash, configs_str, status and status or "used")
local confirm = utils.confirm({default = true, description = description})
if confirm then
os.rm(hashdir)
end
end
end
if os.emptydir(versiondir) then
os.rm(versiondir)
end
end
if os.emptydir(packagedir) then
os.rm(packagedir)
end
end
-- remove the given or all packages
--
-- @param package_names the package names list, support lua pattern
-- @param opt the options, only clean unused packages if pass `{clean = true}`
--
function main(package_names, opt)
opt = opt or {}
local installdir = package.installdir()
if package_names then
for _, package_name in ipairs(package_names) do
for _, packagedir in ipairs(os.dirs(path.join(installdir, package_name:sub(1, 1), package_name))) do
_remove_packagedirs(packagedir, opt)
end
end
else
for _, packagedir in ipairs(os.dirs(path.join(installdir, "*", "*"))) do
_remove_packagedirs(packagedir, opt)
end
end
end
|
0 | repos/xmake/xmake/modules/private/action/require | repos/xmake/xmake/modules/private/action/require/impl/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.semver")
import("core.base.option")
import("core.base.global")
import("core.base.hashset")
import("utils.progress")
import("core.cache.memcache")
import("core.project.project")
import("core.project.config")
import("core.tool.toolchain")
import("core.platform.platform")
import("core.package.package", {alias = "core_package"})
import("devel.git")
import("private.action.require.impl.repository")
import("private.action.require.impl.utils.requirekey", {alias = "_get_requirekey"})
-- get memcache
function _memcache()
return memcache.cache("require.impl.package")
end
--
-- parse require string
--
-- basic
-- - add_requires("zlib")
--
-- semver
-- - add_requires("tbox >=1.5.1", "zlib >=1.2.11")
-- - add_requires("tbox", {version = ">=1.5.1"})
--
-- git branch/tag
-- - add_requires("zlib master")
--
-- with the given repository
-- - add_requires("xmake-repo@tbox >=1.5.1")
--
-- with the given configs
-- - add_requires("aaa_bbb_ccc >=1.5.1 <1.6.0", {optional = true, alias = "mypkg", debug = true})
-- - add_requires("tbox", {config = {coroutine = true, abc = "xxx"}})
--
-- with namespace and the 3rd package manager
-- - add_requires("xmake::xmake-repo@tbox >=1.5.1")
-- - add_requires("vcpkg::ffmpeg")
-- - add_requires("conan::OpenSSL/1.0.2n@conan/stable")
-- - add_requires("conan::openssl/1.1.1g") -- new
-- - add_requires("brew::pcre2/libpcre2-8 10.x", {alias = "pcre2"})
--
-- clone as a standalone package with the different configs
-- we can install and use these three packages at the same time.
-- - add_requires("zlib")
-- - add_requires("zlib~debug", {debug = true})
-- - add_requires("zlib~shared", {configs = {shared = true}, alias = "zlib_shared"})
--
-- - add_requires("zlib~label1")
-- - add_requires("zlib", {label = "label2"})
--
-- private package, only for installation, do not export any links/includes and environments to target
-- - add_requires("zlib", {private = true})
--
-- {system = nil/true/false}:
-- nil: get remote or system packages
-- true: only get system package
-- false: only get remote packages
--
-- {build = true}: always build packages, we do not use the precompiled artifacts
--
function _parse_require(require_str)
-- split package and version info
local splitinfo = require_str:split('%s+')
assert(splitinfo and #splitinfo > 0, "require(\"%s\"): invalid!", require_str)
-- get package info
local packageinfo = splitinfo[1]
-- get version
--
-- e.g.
--
-- latest
-- >=1.5.1 <1.6.0
-- master || >1.4
-- ~1.2.3
-- ^1.1
--
local version = "latest"
if #splitinfo > 1 then
version = table.concat(table.slice(splitinfo, 2), " ")
end
assert(version, "require(\"%s\"): unknown version!", require_str)
-- require third-party packages? e.g. brew::pcre2/libpcre2-8
local reponame = nil
local packagename = nil
if require_str:find("::", 1, true) then
packagename = packageinfo
else
-- get repository name, package name and package url
local pos = packageinfo:lastof('@', true)
if pos then
packagename = packageinfo:sub(pos + 1)
reponame = packageinfo:sub(1, pos - 1)
else
packagename = packageinfo
end
end
-- check package name
assert(packagename, "require(\"%s\"): the package name not found!", require_str)
return packagename, version, reponame
end
-- load require info
function _load_require(require_str, requires_extra, parentinfo)
-- parse require
local packagename, version, reponame = _parse_require(require_str)
-- get require extra
local require_extra = {}
if requires_extra then
require_extra = requires_extra[require_str] or {}
end
-- get required building configurations
-- we need to clone a new configs object, because the whole requireinfo will be modified later.
-- @see https://github.com/xmake-io/xmake-repo/pull/2067
local require_build_configs = table.clone(require_extra.configs or require_extra.config)
if require_extra.debug then
require_build_configs = require_build_configs or {}
require_build_configs.debug = true
end
-- vs_runtime is deprecated, we should use runtimes
if require_build_configs and require_build_configs.vs_runtime then
require_build_configs.runtimes = require_build_configs.vs_runtime
require_build_configs.vs_runtime = nil
wprint("add_requires(%s): vs_runtime is deprecated, please use runtimes!", require_str)
end
-- require packge in the current host platform
if require_extra.host then
if is_subhost(core_package.targetplat()) and os.subarch() == core_package.targetarch() then
-- we need to pass plat/arch to avoid repeat installation
-- @see https://github.com/xmake-io/xmake/issues/1579
else
require_extra.plat = os.subhost()
require_extra.arch = os.subarch()
end
end
-- check require options
local extra_options = hashset.of("plat", "arch", "kind", "host", "targetos",
"alias", "group", "system", "option", "default", "optional", "debug",
"verify", "external", "private", "build", "configs", "version")
for name, value in pairs(require_extra) do
if not extra_options:has(name) then
wprint("add_requires(\"%s\") has unknown option: {%s=%s}!", require_str, name, tostring(value))
end
end
-- we always use xmake package, `add_requires("xmake::zlib")`,
-- it is equivalent to `add_requires("zlib", {system = false})`
if packagename:startswith("xmake::") then
packagename = packagename:sub(8)
require_extra.system = false
end
-- init required item
local required = {}
parentinfo = parentinfo or {}
required.packagename = packagename
required.requireinfo =
{
originstr = require_str,
reponame = reponame,
version = require_extra.version or version,
plat = require_extra.plat, -- require package in the given platform
arch = require_extra.arch, -- require package in the given architecture
targetos = require_extra.targetos, -- require package in the given target os
kind = require_extra.kind, -- default: library, set package kind, e.g. binary, library, we can set `kind = "binary"` to only detect binary program and ignore library.
alias = require_extra.alias, -- set package alias name
group = require_extra.group, -- only uses the first package in same group
system = require_extra.system, -- default: true, we can set it to disable system package manually
option = require_extra.option, -- set and attach option
configs = require_build_configs, -- the required building configurations
default = require_extra.default, -- default: true, we can set it to disable package manually
optional = parentinfo.optional or require_extra.optional, -- default: false, inherit parentinfo.optional
verify = require_extra.verify, -- default: true, we can set false to ignore sha256sum and select any version
external = require_extra.external, -- default: true, we use sysincludedirs/-isystem instead of -I/xxx
private = require_extra.private, -- default: false, private package, only for installation, do not export any links/includes and environments
build = require_extra.build -- default: false, always build packages, we do not use the precompiled artifacts
}
return required.packagename, required.requireinfo
end
-- load package package from system
function _load_package_from_system(packagename)
return core_package.load_from_system(packagename)
end
-- load package package from project
function _load_package_from_project(packagename)
return core_package.load_from_project(packagename)
end
-- load package package from repositories
function _load_package_from_repository(packagename, opt)
opt = opt or {}
local packagedir, repo = repository.packagedir(packagename, opt)
if packagedir then
return core_package.load_from_repository(packagename, packagedir, {plat = opt.plat, arch = opt.arch, repo = repo})
end
end
-- load package package from base
function _load_package_from_base(package, basename, opt)
local package_base = _load_package_from_project(basename)
if not package_base then
package_base = _load_package_from_repository(basename, opt)
end
if package_base then
package._BASE = package_base
end
end
-- has locked requires?
function _has_locked_requires(opt)
opt = opt or {}
if not option.get("upgrade") or opt.force then
return project.policy("package.requires_lock") and os.isfile(project.requireslock())
end
end
-- get locked requires
function _get_locked_requires(requirekey, opt)
opt = opt or {}
local requireslock = _memcache():get("requireslock")
if requireslock == nil or opt.force then
if _has_locked_requires(opt) then
requireslock = io.load(project.requireslock())
end
_memcache():set("requireslock", requireslock or false)
end
if requireslock then
local plat = config.plat() or os.subhost()
local arch = config.arch() or os.subarch()
local key = plat .. "|" .. arch
if requireslock[key] then
return requireslock[key][requirekey], requireslock.__meta__.version
end
end
end
-- sort package deps
--
-- e.g.
--
-- a.deps = b
-- b.deps = c
--
-- orderdeps: c -> b -> a
--
function _sort_packagedeps(package)
-- we must use native deps list instead of package:deps() to generate correct librarydeps
local orderdeps = {}
for _, dep in ipairs(package:plaindeps()) do
if dep then
table.join2(orderdeps, _sort_packagedeps(dep))
table.insert(orderdeps, dep)
end
end
return orderdeps
end
-- sort library deps and generate correct link order
--
-- e.g.
--
-- a.deps = b
-- b.deps = c
--
-- orderdeps: a -> b -> c
--
function _sort_librarydeps(package, opt)
-- we must use native deps list instead of package:deps() to generate correct link order
local orderdeps = {}
for _, dep in ipairs(package:plaindeps()) do
if dep and dep:is_library() and (opt and opt.private or not dep:is_private()) then
table.insert(orderdeps, dep)
table.join2(orderdeps, _sort_librarydeps(dep, opt))
end
end
return orderdeps
end
-- get builtin configuration default values
function _get_default_config_value_of(name)
local defaults = {
debug = false,
shared = false,
pic = true,
lto = false,
asan = false
}
return defaults[name]
end
-- add some builtin configurations to package
function _add_package_configurations(package)
-- we can define configs to override it and it's default value in package()
if package:extraconf("configs", "debug", "default") == nil then
local default = _get_default_config_value_of("debug")
package:add("configs", "debug", {builtin = true, description = "Enable debug symbols.", default = default, type = "boolean"})
end
if package:extraconf("configs", "shared", "default") == nil then
-- we always use static library if it's for wasm platform
local readonly
if package:is_plat("wasm") then
readonly = true
end
local default = _get_default_config_value_of("shared")
package:add("configs", "shared", {builtin = true, description = "Build shared library.", default = default, readonly = readonly, type = "boolean"})
end
if package:extraconf("configs", "pic", "default") == nil then
local default = _get_default_config_value_of("pic")
package:add("configs", "pic", {builtin = true, description = "Enable the position independent code.", default = default, type = "boolean"})
end
if package:extraconf("configs", "lto", "default") == nil then
package:add("configs", "lto", {builtin = true, description = "Enable the link-time build optimization.", type = "boolean"})
end
if package:extraconf("configs", "asan", "default") == nil then
package:add("configs", "asan", {builtin = true, description = "Enable the address sanitizer.", type = "boolean"})
end
if package:extraconf("configs", "runtimes", "default") == nil then
local values = {"MT", "MTd", "MD", "MDd",
"c++_static", "c++_shared", "stdc++_static", "stdc++_shared"}
package:add("configs", "runtimes", {builtin = true, description = "Set the compiler runtimes.", type = "string", values = values, restrict = function (value)
local values_set = hashset.from(values)
if type(value) ~= "string" then
return false
end
if value then
for _, item in ipairs(value:split(",", {plain = true})) do
if not values_set:has(item) then
return false
end
end
end
return true
end})
end
-- deprecated, please use runtimes
if package:extraconf("configs", "vs_runtime", "default") == nil then
package:add("configs", "vs_runtime", {builtin = true, description = "Set vs compiler runtime.", values = {"MT", "MTd", "MD", "MDd"}})
end
if package:extraconf("configs", "toolchains", "default") == nil then
package:add("configs", "toolchains", {builtin = true, description = "Set package toolchains only for cross-compilation."})
end
package:add("configs", "cflags", {builtin = true, description = "Set the C compiler flags."})
package:add("configs", "cxflags", {builtin = true, description = "Set the C/C++ compiler flags."})
package:add("configs", "cxxflags", {builtin = true, description = "Set the C++ compiler flags."})
package:add("configs", "asflags", {builtin = true, description = "Set the assembler flags."})
package:add("configs", "ldflags", {builtin = true, description = "Set the binary linker flags."})
package:add("configs", "shflags", {builtin = true, description = "Set the shared library linker flags."})
end
-- select package version
function _select_package_version(package, requireinfo, locked_requireinfo)
-- get it from the locked requireinfo
if locked_requireinfo then
local version = locked_requireinfo.version
local source = "version"
if locked_requireinfo.branch then
source = "branch"
elseif locked_requireinfo.tag then
source = "tag"
end
return version, source
end
-- has git url?
local has_giturl = false
for _, url in ipairs(package:urls()) do
if git.checkurl(url) then
has_giturl = true
break
end
end
-- select package version
local source = nil
local version = nil
local require_version = requireinfo.version
local require_verify = requireinfo.verify
if (not package:get("versions") or require_verify == false)
and (semver.is_valid(require_version) or semver.is_valid_range(require_version)) then
-- no version list in package() or need not verify sha256sum? try selecting this version directly
-- @see
-- https://github.com/xmake-io/xmake/issues/930
-- https://github.com/xmake-io/xmake/issues/1009
-- https://github.com/xmake-io/xmake/issues/3551
version = require_version
source = "version"
elseif #package:versions() > 0 then -- select version?
version, source = try { function () return semver.select(require_version, package:versions()) end }
end
if not version and has_giturl then -- select branch?
if require_version and #require_version == 40 and require_version:match("%w+") then
version, source = require_version, "commit"
else
version, source = require_version ~= "latest" and require_version or "@default", "branch"
end
end
-- local source package? we use a phony version
if not version and require_version == "latest" and #package:urls() == 0 then
version = "latest"
source = "version"
end
if not version and not package:is_thirdparty() then
raise("package(%s): version(%s) not found!", package:name(), require_version)
end
return version, source
end
-- check the configurations of packages
--
-- package("pcre2")
-- add_configs("bitwidth", {description = "Set the code unit width.", default = "8", values = {"8", "16", "32"}})
-- add_configs("bitwidth", {type = "number", values = {8, 16, 32}})
-- add_configs("bitwidth", {restrict = function(value) if tonumber(value) < 100 then return true end})
--
function _check_package_configurations(package)
local configs_defined = {}
for _, name in ipairs(package:get("configs")) do
configs_defined[name] = package:extraconf("configs", name) or {}
end
for name, value in pairs(package:configs()) do
local conf = configs_defined[name]
if conf then
local config_type = conf.type
if config_type ~= nil and type(value) ~= config_type then
raise("package(%s %s): invalid type(%s) for config(%s), need type(%s)!", package:displayname(), package:version_str(), type(value), name, config_type)
end
if conf.restrict then
if not conf.restrict(value) then
raise("package(%s %s): invalid value(%s) for config(%s)!", package:displayname(), package:version_str(), string.serialize(value, {indent = false}), name)
end
elseif conf.values then
local found = false
for _, config_value in ipairs(conf.values) do
if tostring(value) == tostring(config_value) then
found = true
break
end
end
if not found then
raise("package(%s %s): invalid value(%s) for config(%s), please run `xmake require --info %s` to get all valid values!", package:displayname(), package:version_str(), value, name, package:name())
end
end
else
raise("package(%s %s): invalid config(%s), please run `xmake require --info %s` to get all configurations!", package:displayname(), package:version_str(), name, package:name())
end
end
end
-- check package toolchains
function _check_package_toolchains(package)
if package:toolchains() then
for _, toolchain_inst in pairs(package:toolchains()) do
if not toolchain_inst:check() then
raise("toolchain(\"%s\"): not found!", toolchain_inst:name())
end
end
else
-- maybe this package is host package, it's platform and toolchain has been not checked yet.
local platform_inst = platform.load(package:plat(), package:arch())
if not platform_inst:check() then
raise("no any matched platform for this package(%s)!", package:name())
end
end
end
-- match require path
function _match_requirepath(requirepath, requireconf)
-- get pattern
local function _get_pattern(pattern)
pattern = pattern:gsub("([%+%.%-%^%$%(%)%%])", "%%%1")
pattern = pattern:gsub("%*%*", "\001")
pattern = pattern:gsub("%*", "\002")
pattern = pattern:gsub("\001", ".*")
pattern = pattern:gsub("\002", "[^.]*")
pattern = string.ipattern(pattern, true)
return pattern
end
-- get the excludes
local excludes = requireconf:match("|.*$")
if excludes then excludes = excludes:split("|", {plain = true}) end
-- do match
local pattern = requireconf:gsub("|.*$", "")
pattern = _get_pattern(pattern)
if (requirepath:match('^' .. pattern .. '$')) then
-- exclude sub-deps, e.g. "libwebp.**|cmake|autoconf"
local splitinfo = requirepath:split(".", {plain = true})
if #splitinfo > 0 then
local name = splitinfo[#splitinfo]
for _, exclude in ipairs(excludes) do
pattern = _get_pattern(exclude)
if (name:match('^' .. pattern .. '$')) then
return false
end
end
end
return true
end
end
-- init requireinfo
function _init_requireinfo(requireinfo, package, opt)
-- pass root configs to top library package
requireinfo.configs = requireinfo.configs or {}
if opt.is_toplevel then
requireinfo.is_toplevel = true
-- we always pass some configurations from toplevel even it's headeronly, because it's library deps need inherit them
-- @see https://github.com/xmake-io/xmake/issues/2688
if package:is_library() then
requireinfo.configs.toolchains = requireinfo.configs.toolchains or project.get("target.toolchains")
if project.policy("package.inherit_external_configs") then
requireinfo.configs.toolchains = requireinfo.configs.toolchains or get_config("toolchain")
end
end
requireinfo.configs.runtimes = requireinfo.configs.runtimes or project.get("target.runtimes")
if project.policy("package.inherit_external_configs") then
requireinfo.configs.runtimes = requireinfo.configs.runtimes or get_config("runtimes") or get_config("vs_runtime")
end
if type(requireinfo.configs.runtimes) == "table" then
requireinfo.configs.runtimes = table.concat(requireinfo.configs.runtimes, ",")
end
if requireinfo.configs.lto == nil then
requireinfo.configs.lto = project.policy("build.optimization.lto")
end
if requireinfo.configs.asan == nil then
requireinfo.configs.asan = project.policy("build.sanitizer.address")
end
end
-- but we will ignore some configs for buildhash in the headeronly, moduleonly and host/binary package
-- @note on_test still need these configs, @see https://github.com/xmake-io/xmake/issues/4124
if package:is_headeronly() or package:is_moduleonly() or (package:is_binary() and not package:is_cross()) then
requireinfo.ignored_configs_for_buildhash = {"runtimes", "toolchains", "lto", "asan", "pic"}
end
end
-- finish requireinfo
function _finish_requireinfo(requireinfo, package)
-- we need to synchronise the plat/arch inherited from the parent package as early as possible
if requireinfo.plat then
package:plat_set(requireinfo.plat)
end
if requireinfo.arch then
package:arch_set(requireinfo.arch)
end
requireinfo.configs = requireinfo.configs or {}
if package:is_plat("windows") then
-- @see https://github.com/xmake-io/xmake/issues/4477#issuecomment-1913249489
-- @note its buildhash will be ignored for headeronly
local runtimes = requireinfo.configs.runtimes
if runtimes then
runtimes = runtimes:split(",")
else
runtimes = {}
end
if not table.contains(runtimes, "MT", "MD", "MTd", "MDd") then
table.insert(runtimes, "MT")
end
requireinfo.configs.runtimes = table.concat(runtimes, ",")
end
-- we need to ensure readonly configs
for _, name in ipairs(table.keys(requireinfo.configs)) do
local current = requireinfo.configs[name]
local default = package:extraconf("configs", name, "default")
local readonly = package:extraconf("configs", name, "readonly")
if name == "runtimes" then
-- vs_runtime is deprecated, but we need also support it now.
if default == nil then
default = package:extraconf("configs", "vs_runtime", "default")
end
if readonly == nil then
readonly = package:extraconf("configs", "vs_runtime", "readonly")
end
if default ~= nil or readonly ~= nil then
wprint("please use add_configs(\"runtimes\") instead of add_configs(\"vs_runtime\").")
end
end
if readonly and current ~= default then
wprint("configs.%s is readonly in package(%s), it's always %s", name, package:name(), default)
-- package:config() will use default value after loading package
requireinfo.configs[name] = nil
end
end
-- sync default value to prevent cache mismatch (buildhash)
-- @see https://github.com/xmake-io/xmake/pull/4324
for k, v in pairs(requireinfo.configs) do
local default = _get_default_config_value_of(k)
if v == default then
requireinfo.configs[k] = nil
end
end
end
-- merge requireinfo from `add_requireconfs()`
--
-- add_requireconfs("*", {system = false, configs = {runtimes = "MD"}})
-- add_requireconfs("lib*", {system = false, configs = {runtimes = "MD"}})
-- add_requireconfs("libwebp", {system = false, configs = {runtimes = "MD"}})
-- add_requireconfs("libpng.zlib", {system = false, override = true, configs = {cxflags = "-DTEST1"}, version = "1.2.10"})
-- add_requireconfs("libtiff.*", {system = false, configs = {cxflags = "-DTEST2"}})
-- add_requireconfs("libwebp.**|cmake|autoconf", {system = false, configs = {cxflags = "-DTEST3"}}) -- recursive deps
--
function _merge_requireinfo(requireinfo, requirepath)
-- only for project
if not os.isfile(os.projectfile()) then
return
end
-- find requireconf from the given requirepath
local requireconf_result = {}
local requireconfs, requireconfs_extra = project.requireconfs_str()
if requireconfs then
for _, requireconf in ipairs(requireconfs) do
if _match_requirepath(requirepath, requireconf) then
local requireconf_extra = requireconfs_extra[requireconf]
table.insert(requireconf_result, {requireconf = requireconf, requireconf_extra = requireconf_extra})
end
end
end
-- Append requireconf_extra into requireinfo
-- and the configs of add_requires have a higher priority than add_requireconfs.
--
-- e.g.
-- add_requireconfs("*", {configs = {debug = false}})
-- add_requires("foo", "bar", {configs = {debug = true}})
--
-- foo and bar will be debug mode
--
-- We can also override the configs of add_requires
--
-- e.g.
-- add_requires("zlib 1.2.11")
-- add_requireconfs("zlib", {override = true, version = "1.2.10"})
--
-- We override the version of zlib to 1.2.10
--
-- If the same dependency is matched to multiple configurations,
-- the configurations are merged by default,
-- and if override is set, then it rewrites the previous configurations.
--
for _, item in ipairs(requireconf_result) do
local requireconf_extra = item.requireconf_extra
if requireconf_extra then
-- preprocess requireconf_extra, (debug, override ..)
local override = requireconf_extra.override
if requireconf_extra.debug then
requireconf_extra.configs = requireconf_extra.configs or {}
requireconf_extra.configs.debug = true
requireconf_extra.debug = nil
end
-- append or override configs and extra options
for k, v in pairs(requireconf_extra.configs) do
requireinfo.configs = requireinfo.configs or {}
if override or requireinfo.configs[k] == nil then
requireinfo.configs[k] = v
end
end
for k, v in pairs(requireconf_extra) do
if k ~= "configs" then
if override or requireinfo[k] == nil then
requireinfo[k] = v
end
end
end
end
end
end
-- get package key
function _get_packagekey(packagename, requireinfo, version)
return _get_requirekey(requireinfo, {name = packagename,
plat = requireinfo.plat,
arch = requireinfo.arch,
kind = requireinfo.kind,
version = version or requireinfo.version})
end
-- get locked package key
function _get_packagelock_key(requireinfo)
local requirestr = requireinfo.originstr
local key = _get_requirekey(requireinfo, {hash = true})
return string.format("%s#%s", requirestr, key)
end
-- inherit some builtin configs of parent package if these config values are not default value
-- e.g. add_requires("libpng", {configs = {runtimes = "MD", pic = false}})
--
function _inherit_parent_configs(requireinfo, package, parentinfo)
if package:is_library() then
local requireinfo_configs = requireinfo.configs or {}
local parentinfo_configs = parentinfo.configs or {}
if not requireinfo_configs.shared then
if requireinfo_configs.runtimes == nil then
requireinfo_configs.runtimes = parentinfo_configs.runtimes
end
if requireinfo_configs.pic == nil then
requireinfo_configs.pic = parentinfo_configs.pic
end
end
if parentinfo.plat then
requireinfo.plat = parentinfo.plat
end
if parentinfo.arch then
requireinfo.arch = parentinfo.arch
end
requireinfo_configs.toolchains = requireinfo_configs.toolchains or parentinfo_configs.toolchains
requireinfo_configs.runtimes = requireinfo_configs.runtimes or parentinfo_configs.runtimes
requireinfo_configs.lto = requireinfo_configs.lto or parentinfo_configs.lto
requireinfo_configs.asan = requireinfo_configs.asan or parentinfo_configs.asan
requireinfo.configs = requireinfo_configs
end
end
-- select artifacts for msvc
function _select_artifacts_for_msvc(package, artifacts_manifest)
local msvc
for _, instance in ipairs(package:toolchains()) do
if instance:name() == "msvc" then
msvc = instance
break
end
end
if not msvc then
msvc = toolchain.load("msvc", {plat = package:plat(), arch = package:arch()})
end
local vcvars = msvc:config("vcvars")
if vcvars then
local vs_toolset = vcvars.VCToolsVersion
if vs_toolset and semver.is_valid(vs_toolset) then
local artifacts_infos = {}
for key, artifacts_info in pairs(artifacts_manifest) do
if key:startswith(package:plat() .. "-" .. package:arch() .. "-vc") and key:endswith("-" .. package:buildhash()) then
table.insert(artifacts_infos, artifacts_info)
end
end
-- we sort them to select a newest toolset to get better optimzed performance
table.sort(artifacts_infos, function (a, b)
if a.toolset and b.toolset then
return semver.compare(a.toolset, b.toolset) > 0
else
return false
end
end)
if package:config("shared") or package:is_binary() then
-- executable programs and dynamic libraries only need to select the latest toolset
return artifacts_infos[1]
else
-- static libraries need to consider toolset compatibility
for _, artifacts_info in ipairs(artifacts_infos) do
-- toolset is backwards compatible
--
-- @see https://github.com/xmake-io/xmake/issues/1513
-- https://docs.microsoft.com/en-us/cpp/porting/binary-compat-2015-2017?view=msvc-160
if artifacts_info.toolset and semver.compare(vs_toolset, artifacts_info.toolset) >= 0 then
return artifacts_info
end
end
end
end
end
end
-- select artifacts for generic
function _select_artifacts_for_generic(package, artifacts_manifest)
local buildid = package:plat() .. "-" .. package:arch() .. "-" .. package:buildhash()
return artifacts_manifest[buildid]
end
-- select to use precompiled artifacts?
function _select_artifacts(package, artifacts_manifest)
-- the precompile policy is disabled in package?
if package:policy("package.precompiled") == false then
return
end
-- the precompile policy is disabled in project?
if os.isfile(os.projectfile()) and project.policy("package.precompiled") == false then
return
end
local artifacts_info
if package:is_plat("windows") then -- for msvc
artifacts_info = _select_artifacts_for_msvc(package, artifacts_manifest)
else
artifacts_info = _select_artifacts_for_generic(package, artifacts_manifest)
end
if artifacts_info then
package:artifacts_set(artifacts_info)
end
end
-- select package runtimes
function _select_package_runtimes(package)
local runtimes = package:config("runtimes")
if runtimes then
local runtimes_supported = hashset.new()
local toolchains = package:toolchains() or platform.load(package:plat(), package:arch()):toolchains()
if toolchains then
for _, toolchain_inst in ipairs(toolchains) do
if toolchain_inst:is_standalone() and toolchain_inst:get("runtimes") then
for _, runtime in ipairs(table.wrap(toolchain_inst:get("runtimes"))) do
runtimes_supported:insert(runtime)
end
end
end
end
local runtimes_current = {}
for _, runtime in ipairs(table.wrap(runtimes:split(",", {plain = true}))) do
if runtimes_supported:has(runtime) then
table.insert(runtimes_current, runtime)
end
end
-- we need update runtimes for buildhash, configs ...
--
-- we use configs_overrided to override configs in configs and buildhash,
-- but we shouldn't modify requireinfo.configs directly as it affects the package cache key
--
-- @see https://github.com/xmake-io/xmake/issues/4477#issuecomment-1913185727
local requireinfo = package:requireinfo()
if requireinfo then
requireinfo.configs_overrided = requireinfo.configs_overrided or {}
requireinfo.configs_overrided.runtimes = #runtimes_current > 0 and table.concat(runtimes_current, ",") or nil
package:_invalidate_configs()
end
end
end
-- load required packages
function _load_package(packagename, requireinfo, opt)
-- check circular dependency
opt = opt or {}
if opt.requirepath then
local splitinfo = opt.requirepath:split(".", {plain = true})
if #splitinfo > 3 and
splitinfo[1] == splitinfo[#splitinfo - 1] and
splitinfo[2] == splitinfo[#splitinfo] then
raise("circular dependency(%s) detected in package(%s)!", opt.requirepath, splitinfo[1])
end
end
-- strip trailng ~tag, e.g. zlib~debug
local displayname
if packagename:find('~', 1, true) then
displayname = packagename
local splitinfo = packagename:split('~', {plain = true, limit = 2})
packagename = splitinfo[1]
requireinfo.alias = requireinfo.alias or displayname
requireinfo.label = splitinfo[2]
end
-- save requirekey
local requirekey = _get_packagelock_key(requireinfo)
requireinfo.requirekey = requirekey
-- get locked requireinfo
local locked_requireinfo = get_locked_requireinfo(requireinfo)
-- load package from project first
local package
if os.isfile(os.projectfile()) then
package = _load_package_from_project(packagename)
end
-- load package from repositories
local from_repo = false
if not package then
package = _load_package_from_repository(packagename, {
plat = requireinfo.plat,
arch = requireinfo.arch,
name = requireinfo.reponame,
locked_repo = locked_requireinfo and locked_requireinfo.repo})
if package then
from_repo = true
end
end
-- load base package
if package and package:get("base") then
_load_package_from_base(package, package:get("base", {
name = requireinfo.reponame, locked_repo = locked_requireinfo and locked_requireinfo.repo}))
end
-- load package from system
local system = requireinfo.system
if system == nil then
system = opt.system
end
if not package and (system ~= false or packagename:find("::", 1, true)) then
package = _load_package_from_system(packagename)
end
-- check
assert(package, "package(%s) not found!", packagename)
-- init requireinfo
_init_requireinfo(requireinfo, package, {is_toplevel = not opt.parentinfo})
-- merge requireinfo from `add_requireconfs()`
_merge_requireinfo(requireinfo, opt.requirepath)
-- inherit some builtin configs of parent package, e.g. runtimes, pic
if opt.parentinfo then
_inherit_parent_configs(requireinfo, package, opt.parentinfo)
end
-- finish requireinfo
_finish_requireinfo(requireinfo, package)
-- save require info
package:requireinfo_set(requireinfo)
-- only load toolchain package and its deps
if opt.toolchain then
if package:is_toplevel() and not package:is_toolchain()then
return
end
end
-- init urls source
package:_init_source()
-- select package version
local version, source = _select_package_version(package, requireinfo, locked_requireinfo)
if version then
package:version_set(version, source)
end
-- get package key
local packagekey = _get_packagekey(packagename, requireinfo, version)
-- get package from cache first
local package_cached = _memcache():get2("packages", packagekey)
if package_cached then
-- since toplevel is not part of packagekey, we need to ensure it's part of the cached package table too
if requireinfo.is_toplevel and not package_cached:is_toplevel() then
package_cached:requireinfo().is_toplevel = true
end
-- mark this cached package.requireinfo as override
-- @see https://github.com/xmake-io/xmake/issues/4078
if requireinfo.override then
package_cached:requireinfo().override = true
end
return package_cached
end
-- save display name
if not displayname then
local packageid = _memcache():get2("packageids", packagename)
displayname = packagename
if packageid then
displayname = displayname .. "#" .. tostring(packageid)
end
_memcache():set2("packageids", packagename, (packageid or 0) + 1)
end
package:displayname_set(displayname)
-- disable parallelize if the package cache directory conflicts
local cachedirs = _memcache():get2("cachedirs", package:cachedir())
if cachedirs then
package:set("parallelize", false)
end
_memcache():set2("cachedirs", package:cachedir(), true)
-- add some builtin configurations to package
_add_package_configurations(package)
-- check package configurations
_check_package_configurations(package)
-- we need to check package toolchains before on_load and select runtimes,
-- because we will call compiler-specific apis in on_load/on_fetch/find_package ..
--
-- @see https://github.com/xmake-io/xmake/pull/5466
-- https://github.com/xmake-io/xmake/issues/4596#issuecomment-2014528801
_check_package_toolchains(package)
-- we need to select package runtimes before computing buildhash
-- @see https://github.com/xmake-io/xmake/pull/4630#issuecomment-1910216561
_select_package_runtimes(package)
-- pre-compute the package buildhash
package:_compute_buildhash()
-- save artifacts info, we need to add it at last before buildhash need depend on package configurations
-- it will switch to install precompiled binary package from xmake-mirror/build-artifacts
if from_repo and not option.get("build") and not requireinfo.build then
local artifacts_manifest = repository.artifacts_manifest(packagename, version)
if artifacts_manifest then
_select_artifacts(package, artifacts_manifest)
end
end
-- we need to check package toolchains before on_load,
-- because we will call compiler-specific apis in on_load/on_fetch/find_package ..
--
-- @see https://github.com/xmake-io/xmake/pull/5466
-- https://github.com/xmake-io/xmake/issues/4596#issuecomment-2014528801
_check_package_toolchains(package)
-- do load
package:_load()
-- load all components
for _, component in pairs(package:components()) do
component:_load()
end
-- load environments from the manifest to enable the environments of on_install()
package:envs_load()
-- save this package package to cache
_memcache():set2("packages", packagekey, package)
-- load ok
package:_mark_as_loaded()
return package
end
-- load all required packages
function _load_packages(requires, opt)
-- no requires?
if not requires or #requires == 0 then
return {}
end
-- load packages
local packages = {}
local packages_nodeps = {}
for _, requireitem in ipairs(load_requires(requires, opt.requires_extra, opt)) do
-- load package
local requireinfo = requireitem.info
local requirepath = opt.requirepath and (opt.requirepath .. "." .. requireitem.name) or requireitem.name
local package = _load_package(requireitem.name, requireinfo, table.join(opt, {requirepath = requirepath}))
-- maybe package not found and optional
if package then
-- load dependent packages and save them first of this package
if not package._DEPS then
if package:get("deps") and opt.nodeps ~= true then
-- load dependent packages and do not load system/3rd packages for package/deps()
local _, plaindeps = _load_packages(package:get("deps"), {requirepath = requirepath,
requires_extra = package:extraconf("deps") or {},
parentinfo = requireinfo,
nodeps = opt.nodeps,
system = false})
for _, dep in ipairs(plaindeps) do
dep:parents_add(package)
end
package._PLAINDEPS = plaindeps
package._ORDERDEPS = table.unique(_sort_packagedeps(package))
package._LIBRARYDEPS = table.reverse_unique(_sort_librarydeps(package))
package._LIBRARYDEPS_WITH_PRIVATE = table.reverse_unique(_sort_librarydeps(package, {private = true}))
-- we always need load dependencies everytime
-- @see https://github.com/xmake-io/xmake/issues/4522
local packagedeps = {}
for _, dep in ipairs(package._ORDERDEPS) do
table.insert(packages, dep)
packagedeps[dep:name()] = dep
end
package._DEPS = packagedeps
end
end
-- save this package
table.insert(packages, package)
table.insert(packages_nodeps, package)
end
end
return packages, packages_nodeps
end
-- get package parents string
function _get_parents_str(package)
local parents = package:parents()
if parents then
local parentnames = {}
for _, parent in ipairs(parents) do
table.insert(parentnames, parent:displayname())
end
if #parentnames == 0 then
return
end
return table.concat(parentnames, ",")
end
end
-- check dependencies conflicts
--
-- It exists conflict for dependent packages for each root packages? resolve it first
-- e.g.
-- add_requires("foo") -> bar -> zlib 1.2.10
-- -> xyz -> zlib 1.2.11 or other configs
--
-- add_requires("ddd") -> zlib
--
-- We assume that there is no conflict between `foo` and `ddd`.
--
-- Of course, conflicts caused by `add_packages("foo", "ddd")`
-- cannot be detected at present and can only be resolved by the user
--
function _check_package_depconflicts(package)
local packagekeys = {}
for _, dep in ipairs(package:librarydeps()) do
local key = _get_packagekey(dep:name(), dep:requireinfo())
local prevkey = packagekeys[dep:name()]
if prevkey then
assert(key == prevkey, "package(%s): conflict dependencies with package(%s) in %s!", key, prevkey, package:name())
else
packagekeys[dep:name()] = key
end
end
end
-- must depend on the given package?
function _must_depend_on(package, dep)
local manifest = package:manifest_load()
if manifest and manifest.librarydeps then
local librarydeps = hashset.from(manifest.librarydeps)
return librarydeps:has(dep:name())
end
end
-- compatible with all previous link dependencies?
-- @see https://github.com/xmake-io/xmake/issues/2719
function _compatible_with_previous_librarydeps(package, opt)
-- skip to check compatibility if installation has been finished
opt = opt or {}
if opt.install_finished then
return true
end
-- check strict compatibility for librarydeps?
local strict_compatibility = project.policy("package.librarydeps.strict_compatibility")
if strict_compatibility == nil then
strict_compatibility = package:policy("package.librarydeps.strict_compatibility")
end
-- and we can disable it manually, @see https://github.com/xmake-io/xmake/pull/3738
if strict_compatibility == false then
return true
end
-- compute the buildhash for current librarydeps
local depnames = hashset.new()
local depinfos_curr = {}
for _, dep in ipairs(package:librarydeps()) do
if strict_compatibility or dep:policy("package.strict_compatibility") then
depinfos_curr[dep:name()] = {
version = dep:version_str(),
buildhash = dep:buildhash()
}
depnames:insert(dep:name())
end
end
-- compute the buildhash for previous librarydeps
local depinfos_prev = {}
local manifest = package:manifest_load()
if manifest and manifest.librarydeps then
local deps = manifest.deps or {}
for _, depname in ipairs(manifest.librarydeps) do
if strict_compatibility or (package:dep(depname) and package:dep(depname):policy("package.strict_compatibility")) or depinfos_curr[depname] then
local depinfo = deps[depname]
if depinfo and depinfo.buildhash then
depinfos_prev[depname] = depinfo
depnames:insert(depname)
end
end
end
end
-- no any dependencies
if depnames:empty() then
return true
end
-- is compatible?
local is_compatible = true
local compatible_tips = {}
for _, depname in depnames:keys() do
local depinfo_prev = depinfos_prev[depname]
local depinfo_curr = depinfos_curr[depname]
if depinfo_prev and depinfo_curr then
if depinfo_prev.buildhash ~= depinfo_curr.buildhash then
is_compatible = false
table.insert(compatible_tips, ("*%s"):format(depname))
end
elseif depinfo_prev then
is_compatible = false
table.insert(compatible_tips, ("-%s"):format(depname))
elseif depinfo_curr then
is_compatible = false
table.insert(compatible_tips, ("+%s"):format(depname))
end
end
if not is_compatible and #compatible_tips > 0 then
package:data_set("librarydeps.compatible_tips", compatible_tips)
end
if not is_compatible then
package:data_set("force_reinstall", true)
end
return is_compatible
end
-- the cache directory
function cachedir()
return path.join(global.directory(), "cache", "packages")
end
-- this package should be install?
function should_install(package, opt)
opt = opt or {}
if package:is_template() then
return false
end
if not opt.install_finished and package:policy("package.install_always") then
return true
end
if package:exists() and _compatible_with_previous_librarydeps(package, opt) then
return false
end
-- we don't need to install it if this package only need to be fetched
if package:is_fetchonly() then
return false
end
-- only get system package? e.g. add_requires("xxx", {system = true})
local requireinfo = package:requireinfo()
if requireinfo and requireinfo.system then
return false
end
if package:parents() then
-- if all the packages that depend on it already exist, then there is no need to install it
for _, parent in ipairs(package:parents()) do
if should_install(parent, opt) and not parent:exists() then
return true
end
-- if the existing parent package is already using it,
-- then even if it is an optional package, you must make sure to install it
--
-- @see https://github.com/xmake-io/xmake/issues/1460
--
if parent:exists() and not option.get("force") and _must_depend_on(parent, package) then
-- mark this package as non-optional because parent package need it
local requireinfo = package:requireinfo()
if requireinfo.optional then
requireinfo.optional = nil
end
return true
end
end
else
return true
end
end
-- get package configs string
function get_configs_str(package)
local configs = {}
if package:is_optional() then
table.insert(configs, "optional")
end
if package:is_private() then
table.insert(configs, "private")
end
local requireinfo = package:requireinfo()
if requireinfo then
if requireinfo.plat then
table.insert(configs, requireinfo.plat)
end
if requireinfo.arch then
table.insert(configs, requireinfo.arch)
end
if requireinfo.kind then
table.insert(configs, requireinfo.kind)
end
local ignored_configs_for_buildhash = hashset.from(requireinfo.ignored_configs_for_buildhash or {})
local configs_overrided = requireinfo.configs_overrided or {}
for k, v in pairs(requireinfo.configs) do
if not ignored_configs_for_buildhash:has(k) then
v = configs_overrided[k] or v
if type(v) == "boolean" then
table.insert(configs, k .. ":" .. (v and "y" or "n"))
else
table.insert(configs, k .. ":" .. string.serialize(v, {strip = true, indent = false}))
end
end
end
end
local compatible_tips = package:data("librarydeps.compatible_tips")
if compatible_tips then
table.insert(configs, "deps:" .. table.concat(compatible_tips, ","))
end
local parents_str = _get_parents_str(package)
if parents_str then
table.insert(configs, "from:" .. parents_str)
end
local configs_str = #configs > 0 and "[" .. table.concat(configs, ", ") .. "]" or ""
local limitwidth = math.floor(os.getwinsize().width * 2 / 3)
if #configs_str > limitwidth then
configs_str = configs_str:sub(1, limitwidth) .. " ..)"
end
return configs_str
end
-- get locked requireinfo
function get_locked_requireinfo(requireinfo, opt)
local requirekey = requireinfo.requirekey
local locked_requireinfo, requireslock_version
if _has_locked_requires(opt) and requirekey then
locked_requireinfo, requireslock_version = _get_locked_requires(requirekey, opt)
if requireslock_version and semver.compare(project.requireslock_version(), requireslock_version) < 0 then
locked_requireinfo = nil
end
end
return locked_requireinfo, requireslock_version
end
-- load requires
function load_requires(requires, requires_extra, opt)
opt = opt or {}
local requireitems = {}
for _, require_str in ipairs(requires) do
local packagename, requireinfo = _load_require(require_str, requires_extra, opt.parentinfo)
table.insert(requireitems, {name = packagename, info = requireinfo})
end
return requireitems
end
-- load all required packages
function load_packages(requires, opt)
opt = opt or {}
local unique = {}
local packages = {}
for _, package in ipairs((_load_packages(requires, opt))) do
if package:is_toplevel() then
_check_package_depconflicts(package)
end
local key = _get_packagekey(package:name(), package:requireinfo())
if not unique[key] then
table.insert(packages, package)
unique[key] = true
end
end
return packages
end
|
0 | repos/xmake/xmake/modules/private/action/require | repos/xmake/xmake/modules/private/action/require/impl/export_packages.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 export_packages.lua
--
-- imports
import("core.package.package", {alias = "core_package"})
import("private.action.require.impl.package")
-- export packages
function main(requires, opt)
opt = opt or {}
local packages = {}
local packagedir = assert(opt.packagedir)
for _, instance in ipairs(package.load_packages(requires, opt)) do
-- get export path
local installdir = instance:installdir()
local rootdir = core_package.installdir()
local exportpath, count = installdir:replace(rootdir, packagedir, {plain = true})
if count == 0 and instance:is_binary_embed() then
-- maybe local binary embed package
-- @see https://github.com/xmake-io/xmake/issues/3470
local name = instance:name()
installdir = instance:scriptdir()
if installdir:endswith(path.join(name:sub(1, 1), name)) then
rootdir = path.directory(path.directory(installdir))
exportpath, count = installdir:replace(rootdir, packagedir, {plain = true})
end
end
-- export this package
if exportpath and count == 1 and instance:fetch({force = true}) then
print("exporting %s-%s %s", instance:displayname(), instance:version_str(), package.get_configs_str(instance))
cprint(" ${yellow}->${clear} %s", exportpath)
os.cp(installdir, exportpath, {symlink = true})
os.tryrm(path.join(exportpath, "references.txt"))
table.insert(packages, instance)
end
end
return packages
end
|
0 | repos/xmake/xmake/modules/private/action/require/impl | repos/xmake/xmake/modules/private/action/require/impl/actions/patch_sources.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 patch_sources.lua
--
-- imports
import("core.base.option")
import("core.base.global")
import("net.http")
import("net.proxy")
import("devel.git")
import("utils.archive")
-- check sha256
function _check_sha256(patch_hash, patch_file)
local ok = (patch_hash == hash.sha256(patch_file))
if not ok then
-- `git pull` maybe will replace lf to crlf in the patch text automatically on windows.
-- so we need to attempt to fix this sha256
--
-- @see
-- https://github.com/xmake-io/xmake-repo/pull/67
-- https://stackoverflow.com/questions/1967370/git-replacing-lf-with-crlf
--
local tmpfile = os.tmpfile(patch_file)
os.cp(patch_file, tmpfile)
local content = io.readfile(tmpfile, {encoding = "binary"})
content = content:gsub('\r\n', '\n')
io.writefile(tmpfile, content, {encoding = "binary"})
ok = (patch_hash == hash.sha256(tmpfile))
os.rm(tmpfile)
end
return ok
end
-- do patch
function _patch(package, patchinfo)
local patch_url = patchinfo.url
local patch_hash = patchinfo.sha256
local patch_extra = patchinfo.extra or {}
-- trace
patch_url = proxy.mirror(patch_url) or patch_url
vprint("patching %s to %s-%s ..", patch_url, package:name(), package:version_str())
-- get the patch file
local patch_file = path.join(os.tmpdir(), "patches", package:name(), package:version_str(), (path.filename(patch_url):gsub("%?.+$", "")))
-- ensure lower hash
if patch_hash then
patch_hash = patch_hash:lower()
end
-- the package file have been downloaded?
local cached = true
if not os.isfile(patch_file) or not _check_sha256(patch_hash, patch_file) then
-- no cached
cached = false
-- attempt to remove the previous file first
os.tryrm(patch_file)
-- download the patch file
if patch_url:find(string.ipattern("https-://")) or patch_url:find(string.ipattern("ftps-://")) then
http.download(patch_url, patch_file, {
insecure = global.get("insecure-ssl"),
headers = package:policy("package.download.http_headers")})
else
-- copy the patch file
if os.isfile(patch_url) then
os.cp(patch_url, patch_file)
else
local scriptdir = package:scriptdir()
if scriptdir and os.isfile(path.join(scriptdir, patch_url)) then
os.cp(path.join(scriptdir, patch_url), patch_file)
else
raise("patch(%s): not found!", patch_url)
end
end
end
-- check hash
if patch_hash and not _check_sha256(patch_hash, patch_file) then
raise("patch(%s): unmatched checksum!", patch_url)
end
end
-- is archive file? we need extract it first
local extension = archive.extension(patch_file)
if extension and #extension > 0 then
local patchdir = patch_file .. ".dir"
local patchdir_tmp = patchdir .. ".tmp"
os.tryrm(patchdir_tmp)
local ok = try {function() archive.extract(patch_file, patchdir_tmp); return true end}
if ok then
os.tryrm(patchdir)
os.mv(patchdir_tmp, patchdir)
else
os.tryrm(patchdir_tmp)
os.tryrm(patchdir)
raise("cannot extract %s", patch_file)
end
-- apply patch files
for _, file in ipairs(os.files(path.join(patchdir, "**"))) do
vprint("applying patch %s", file)
git.apply(file, {reverse = patch_extra.reverse})
end
else
-- apply single plain patch file
vprint("applying patch %s", patch_file)
git.apply(patch_file, {reverse = patch_extra.reverse})
end
end
-- patch the given package
function main(package)
-- we don't need to patch it if we use the precompiled artifacts to install package
if package:is_precompiled() then
return
end
-- no patches?
local patches = package:patches()
if not patches then
return
end
-- do all patches
for _, patchinfo in ipairs(patches) do
_patch(package, patchinfo)
end
end
|
0 | repos/xmake/xmake/modules/private/action/require/impl | repos/xmake/xmake/modules/private/action/require/impl/actions/download_resources.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_resources.lua
--
-- imports
import("core.base.option")
import("core.base.global")
import("core.package.package", {alias = "core_package"})
import("lib.detect.find_file")
import("lib.detect.find_directory")
import("net.http")
import("net.proxy")
import("devel.git")
import("utils.archive")
-- checkout resources
function _checkout(package, resource_name, resource_url, resource_revision)
-- trace
resource_url = proxy.mirror(resource_url) or resource_url
vprint("cloning resource(%s: %s) to %s-%s ..", resource_name, resource_revision, package:name(), package:version_str())
-- get the resource directory
local resourcedir = assert(package:resourcefile(resource_name), "invalid resource directory!")
-- use previous resource directory if exists
if os.isdir(resourcedir) and not option.get("force") then
-- clean the previous build files
git.clean({repodir = resourcedir, force = true, all = true})
-- reset the previous modified files
git.reset({repodir = resourcedir, hard = true})
if os.isfile(path.join(resourcedir, ".gitmodules")) then
git.submodule.clean({repodir = resourcedir, force = true, all = true})
git.submodule.reset({repodir = resourcedir, hard = true})
end
return
end
-- we can use local package from the search directories directly if network is too slow
local localdir = find_directory(path.filename(resourcedir), core_package.searchdirs())
if localdir and os.isdir(localdir) then
git.clean({repodir = localdir, force = true, all = true})
git.reset({repodir = localdir, hard = true})
if os.isfile(path.join(localdir, ".gitmodules")) then
git.submodule.clean({repodir = localdir, force = true, all = true})
git.submodule.reset({repodir = localdir, hard = true})
end
os.cp(localdir, resourcedir)
return
end
-- remove temporary directory
os.rm(resourcedir)
-- we need to enable longpaths on windows
local longpaths = package:policy("platform.longpaths")
-- clone whole history and tags
git.clone(resource_url, {treeless = true, checkout = false, longpaths = longpaths, outputdir = resourcedir})
-- attempt to checkout the given version
git.checkout(resource_revision, {repodir = resourcedir})
-- update all submodules
if os.isfile(path.join(resourcedir, ".gitmodules")) then
git.submodule.update({init = true, recursive = true, longpaths = longpaths, repodir = resourcedir})
end
end
-- download resources
function _download(package, resource_name, resource_url, resource_hash)
-- trace
resource_url = proxy.mirror(resource_url) or resource_url
vprint("downloading resource(%s: %s) to %s-%s ..", resource_name, resource_url, package:name(), package:version_str())
-- get the resource file
local resource_file = assert(package:resourcefile(resource_name), "invalid resource file!")
-- ensure lower hash
if resource_hash then
resource_hash = resource_hash:lower()
end
-- the package file have been downloaded?
local cached = true
if not os.isfile(resource_file) or resource_hash ~= hash.sha256(resource_file) then
-- no cached
cached = false
-- attempt to remove the previous file first
os.tryrm(resource_file)
-- download or copy the resource file
local localfile = find_file(path.filename(resource_file), core_package.searchdirs())
if localfile and os.isfile(localfile) then
-- we can use local resource from the search directories directly if network is too slow
os.cp(localfile, resource_file)
elseif os.isfile(resource_url) then
os.cp(resource_url, resource_file)
elseif resource_url:find(string.ipattern("https-://")) or resource_url:find(string.ipattern("ftps-://")) then
http.download(resource_url, resource_file, {
insecure = global.get("insecure-ssl"),
headers = package:policy("package.download.http_headers")})
else
raise("invalid resource url(%s)", resource_url)
end
-- check hash
if resource_hash and resource_hash ~= hash.sha256(resource_file) then
raise("resource(%s): unmatched checksum, current hash(%s) != original hash(%s)", resource_url,
hash.sha256(resource_file):sub(1, 8), resource_hash:sub(1, 8))
end
end
-- extract the resource file
local resourcedir = package:resourcedir(resource_name)
local resourcedir_tmp = resourcedir .. ".tmp"
os.tryrm(resourcedir_tmp)
local extension = archive.extension(resource_file)
local ok = try {function() archive.extract(resource_file, resourcedir_tmp); return true end}
if ok then
os.tryrm(resourcedir)
os.mv(resourcedir_tmp, resourcedir)
elseif extension and extension ~= "" then
os.tryrm(resourcedir_tmp)
os.tryrm(resourcedir)
raise("cannot extract %s", resource_file)
else
-- if it is not archive file, we only need to create empty resource directory and use package:resourcefile(resource_name)
os.tryrm(resourcedir)
os.mkdir(resourcedir)
end
end
-- download all resources of the given package
function main(package)
-- we don't need to download it if we use the precompiled artifacts to install package
if package:is_precompiled() then
return
end
-- no resources?
local resources = package:resources()
if not resources then
return
end
-- download all resources
for name, resourceinfo in pairs(resources) do
if git.checkurl(resourceinfo.url) then
_checkout(package, name, resourceinfo.url, resourceinfo.sha256)
else
_download(package, name, resourceinfo.url, resourceinfo.sha256)
end
end
end
|
0 | repos/xmake/xmake/modules/private/action/require/impl | repos/xmake/xmake/modules/private/action/require/impl/actions/test.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 test.lua
--
-- imports
import("core.base.option")
import("private.action.require.impl.utils.filter")
-- test the given package
function main(package)
-- enter the test directory
local testdir = path.join(os.tmpdir(), "pkgtest", package:name(), package:version_str() or "latest")
if os.isdir(testdir) then
os.tryrm(testdir)
end
if not os.isdir(testdir) then
os.mkdir(testdir)
end
local oldir = os.cd(testdir)
-- test it
local script = package:script("test")
if script ~= nil then
filter.call(script, package)
end
-- restore the current directory
os.cd(oldir)
-- remove the test directory
os.tryrm(testdir)
end
|
0 | repos/xmake/xmake/modules/private/action/require/impl | repos/xmake/xmake/modules/private/action/require/impl/actions/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("core.base.option")
import("core.base.tty")
import("core.package.package", {alias = "core_package"})
import("core.project.target")
import("core.platform.platform")
import("lib.detect.find_file")
import("private.action.require.impl.actions.test")
import("private.action.require.impl.actions.patch_sources")
import("private.action.require.impl.actions.download_resources")
import("private.action.require.impl.utils.filter")
-- patch pkgconfig if not exists
function _patch_pkgconfig(package)
-- only binary? need not pkgconfig
if not package:is_library() then
return
end
-- get lib/pkgconfig/*.pc or share/pkgconfig/*.pc file
local libpkgconfigdir = path.join(package:installdir(), "lib", "pkgconfig")
local sharepkgconfigdir = path.join(package:installdir(), "share", "pkgconfig")
local pcfile = (os.isdir(libpkgconfigdir) and find_file("*.pc", libpkgconfigdir))
or (os.isdir(sharepkgconfigdir) and find_file("*.pc", sharepkgconfigdir)) or nil
if pcfile then
return
end
-- trace
pcfile = path.join(libpkgconfigdir, package:name() .. ".pc")
vprint("patching %s ..", pcfile)
-- fetch package
local fetchinfo = package:fetch_librarydeps()
if not fetchinfo then
return
end
-- get libs
local libs = ""
local installdir = package:installdir()
for _, linkdir in ipairs(fetchinfo.linkdirs) do
if linkdir ~= path.join(installdir, "lib") then
libs = libs .. " -L" .. (linkdir:gsub("\\", "/"))
end
end
libs = libs .. " -L${libdir}"
for _, link in ipairs(fetchinfo.links) do
libs = libs .. " -l" .. link
end
for _, link in ipairs(fetchinfo.syslinks) do
libs = libs .. " -l" .. link
end
-- cflags
local cflags = ""
for _, includedir in ipairs(fetchinfo.includedirs or fetchinfo.sysincludedirs) do
if includedir ~= path.join(installdir, "include") then
cflags = cflags .. " -I" .. (includedir:gsub("\\", "/"))
end
end
cflags = cflags .. " -I${includedir}"
for _, define in ipairs(fetchinfo.defines) do
cflags = cflags .. " -D" .. define
end
-- patch a *.pc file
local file = io.open(pcfile, 'w')
if file then
file:print("prefix=%s", installdir:gsub("\\", "/"))
file:print("exec_prefix=${prefix}")
file:print("libdir=${exec_prefix}/lib")
file:print("includedir=${prefix}/include")
file:print("")
file:print("Name: %s", package:name())
file:print("Description: %s", package:description())
file:print("Version: %s", package:version_str())
file:print("Libs: %s", libs)
file:print("Libs.private: ")
file:print("Cflags: %s", cflags)
file:close()
end
end
-- Match to path like (string insides brackets is matched):
-- /home/user/.xmake/packages[/f/foo/v0.1.0/9adc96bd69124211aad7dd58a36f02ce]/lib
local _PACKAGE_VERSION_BUILDHASH_PATTERN = "[\\/]%w[\\/][^\\/]+[\\/][^\\/]+[\\/]" .. string.rep('%x', 32)
function _fix_path_for_file(file, search_pattern)
-- Replace path string before package pattern with local package install
-- directory.
-- Note: It's possible that package A references files in package B, thus we
-- need to match against all possible package install paths.
--
-- search_pattern should contain a whole and a sub capture.
-- The sub capture will be replaced with local install path.
-- The whole capture is to make the search more precise and less likely to
-- match non package path.
local prefix = core_package.installdir()
io.gsub(file, search_pattern, function(whole_value, value)
local mat = value:match(_PACKAGE_VERSION_BUILDHASH_PATTERN)
if not mat then
return nil
end
local result
local splitinfo = value:split(mat, {plain = true})
if #splitinfo == 2 then
-- /home/user/packages[/f/foo/buildhash]/v1.0
result = path.join(prefix, mat, splitinfo[2])
elseif #splitinfo == 1 then
if value:startswith(mat) then
-- path begins with matched pattern: [/f/foo/buildhash]/v1.0
result = path.join(prefix, value)
else
-- path ends with matched pattern: /home/user/packages[/f/foo/buildhash]
result = path.join(prefix, mat)
end
else
vprint("fix path split got more than 2 parts, something wrong?", whole_value)
end
if result then
result = result:gsub("\\", "/")
vprint("fix path: %s in %s", whole_value, file)
return whole_value:replace(value, result, {plain = true})
end
end)
end
-- fix paths for the precompiled package
-- @see https://github.com/xmake-io/xmake/issues/1671
function _fix_paths_for_precompiled_package(package)
local patterns = {
{
-- Fix path for cmake files.
-- "|include/**" means exclude all files under include directory.
-- Their are quite a few search paths used by cmake, so just look
-- for all ".cmake" files for most reliable result.
-- https://cmake.org/cmake/help/latest/command/find_package.html#config-mode-search-procedure
file_pattern = {"**.cmake|include/**"},
search_pattern = {'("(.-)")'},
},
{
-- Fix path for pkg-config .pc files.
-- 1. `varname=value` defines a variable, which may contain path.
-- 2. A package may reference another package with absolute path.
-- For example: glog.pc with gflags and unwind enabled contains something like following:
-- Libs: -L/absolute/path/to/gflags/lib -L /absolute/path/to/libunwind/lib ...
-- So searching for only prefix is not enough.
-- 3. If path contains spaces, it should be double quoted.
-- If not quoted, spaces should be backslash escaped, which we do
-- not fix for now.
-- For pkg-config behavior for spaces in path, refer to
-- https://github.com/golang/go/issues/16455#issuecomment-255900404
file_pattern = {"lib/pkgconfig/**.pc", "share/pkgconfig/**.pc"},
search_pattern = {"([%w_]+%s*=%s*(.-)\n)", "(%-[I|L]%s*(%S+))", '("(.-)")'},
},
}
-- If artifact contains installdir where it's built (remotedir), extract
-- path prefix and do plain replace with local install dir.
local remotedir
local manifest = package:manifest_load()
if manifest and manifest.artifacts then
remotedir = manifest.artifacts.remotedir
end
local remote_prefix
local local_prefix
if remotedir then
local idx = remotedir:find(_PACKAGE_VERSION_BUILDHASH_PATTERN)
if idx then
remote_prefix = remotedir:sub(1, idx)
local_prefix = core_package.installdir()
if not local_prefix:endswith(path.sep()) then
local_prefix = local_prefix .. path.sep()
end
else
wprint("no package buildhash pattern found in artifacts remotedir: %s", remotedir)
end
end
for _, pat in ipairs(patterns) do
for _, filepat in ipairs(pat.file_pattern) do
local filepattern = path.join(package:installdir(), filepat)
for _, file in ipairs(os.files(filepattern)) do
if remote_prefix then
local _, count = io.replace(file, remote_prefix, local_prefix, {plain = true})
-- maybe we need to translate path seperator
-- @see https://github.com/xmake-io/xmake/discussions/3008
if count == 0 and is_host("windows") then
io.replace(file, (remote_prefix:gsub("\\", "/")), local_prefix:gsub("\\", "/"), {plain = true})
end
else
for _, search_pattern in ipairs(pat.search_pattern) do
_fix_path_for_file(file, search_pattern)
end
end
end
end
end
end
-- get failed install directory
function _get_installdir_failed(package)
return path.join(package:cachedir(), "installdir.failed")
end
-- clear install directory
function _clear_installdir(package)
os.tryrm(package:installdir())
os.tryrm(_get_installdir_failed(package))
end
-- clear source directory
function _clear_sourcedir(package)
local sourcedir = package:data("cleanable_sourcedir")
if sourcedir then
os.tryrm(sourcedir)
end
end
-- enter working directory
function _enter_workdir(package)
-- get working directory of this package
local workdir = package:cachedir()
-- lock this package
package:lock()
-- enter directory
local oldir = nil
local sourcedir = package:sourcedir()
if sourcedir then
oldir = os.cd(sourcedir)
elseif #package:urls() > 0 then
-- only one root directory? skip it
local anchorfile = path.join(workdir, "source", "__sourceroot_anchor__.txt")
local filedirs = os.filedirs(path.join(workdir, "source", "*"))
if not os.isfile(anchorfile) and #filedirs == 1 and os.isdir(filedirs[1]) then
oldir = os.cd(filedirs[1])
else
oldir = os.cd(path.join(workdir, "source"))
end
end
if not oldir then
os.mkdir(workdir)
oldir = os.cd(workdir)
end
-- we need to copy source codes to the working directory with short path on windows
--
-- Because the target name and source file path of this project are too long,
-- it's absolute path exceeds the windows path length limit.
--
if is_host("windows") and package:policy("platform.longpaths") then
local sourcedir_tmp = os.tmpdir() .. ".dir"
os.tryrm(sourcedir_tmp)
os.cp(os.curdir(), sourcedir_tmp)
os.cd(sourcedir_tmp)
end
return oldir
end
-- leave working directory
function _leave_workdir(package, oldir)
-- clean the empty package directory
local installdir = package:installdir()
if os.emptydir(installdir) then
os.tryrm(installdir)
end
-- unlock this package
package:unlock()
-- leave source codes directory
if oldir then
os.cd(oldir)
end
-- clean source directory if it is no longer needed
_clear_sourcedir(package)
end
-- enter package install environments
function _enter_package_installenvs(package)
for _, dep in ipairs(package:orderdeps()) do
dep:envs_enter()
end
end
-- enter package test environments
function _enter_package_testenvs(package)
-- add compiler runtime library directory to $PATH
-- @see https://github.com/xmake-io/xmake-repo/pull/3606
if is_host("windows") and package:is_plat("windows", "mingw") then -- bin/*.dll for windows
local toolchains = package:toolchains()
if not toolchains then
local platform_inst = platform.load(package:plat(), package:arch())
toolchains = platform_inst:toolchains()
for _, toolchain_inst in ipairs(toolchains) do
if toolchain_inst:check() then
local runenvs = toolchain_inst:runenvs()
if runenvs and runenvs.PATH then
local envs = {PATH = runenvs.PATH}
os.addenvs(envs)
end
end
end
end
end
-- enter package environments
for _, dep in ipairs(package:orderdeps()) do
dep:envs_enter()
end
package:envs_enter()
end
function main(package)
-- enter working directory
local oldir = _enter_workdir(package)
-- init tipname
local tipname = package:name()
if package:version_str() then
tipname = tipname .. "-" .. package:version_str()
end
-- install it
local ok = true
local oldenvs = os.getenvs()
try
{
function ()
-- install the third-party package directly, e.g. brew::pcre2/libpcre2-8, conan::OpenSSL/1.0.2n@conan/stable
local installed_now = false
local script = package:script("install")
if package:is_thirdparty() then
if script ~= nil then
filter.call(script, package)
end
else
-- build and install package to the install directory
local force_reinstall = package:policy("package.install_always") or package:data("force_reinstall") or option.get("force")
if force_reinstall or not package:manifest_load() then
-- clear install directory
_clear_installdir(package)
-- download package resources
download_resources(package)
-- patch source codes of package
patch_sources(package)
-- enter the environments of all package dependencies
_enter_package_installenvs(package)
-- do install
if script ~= nil then
filter.call(script, package, {oldenvs = oldenvs})
end
-- install rules
local rulesdir = package:rulesdir()
if rulesdir and os.isdir(rulesdir) then
os.cp(rulesdir, package:installdir())
end
-- leave the environments of all package dependencies
os.setenvs(oldenvs)
-- save the package info to the manifest file
package:manifest_save()
installed_now = true
end
end
-- enter the package environments
_enter_package_testenvs(package)
-- fetch package and force to flush the cache
local fetchinfo = package:fetch({force = true})
if option.get("verbose") or option.get("diagnosis") then
print(fetchinfo)
end
assert(fetchinfo, "fetch %s failed!", tipname)
-- this package is installed now
if installed_now then
-- fix paths for the precompiled package
if package:is_precompiled() and not package:is_system() then
_fix_paths_for_precompiled_package(package)
end
-- patch pkg-config files for package
_patch_pkgconfig(package)
-- test it
test(package)
end
-- leave the package environments
os.setenvs(oldenvs)
-- trace
tty.erase_line_to_start().cr()
cprint("${yellow} => ${clear}install %s %s .. ${color.success}${text.success}", package:displayname(), package:version_str() or "")
end,
catch
{
function (errors)
-- show or save the last errors
local errorfile = path.join(package:installdir("logs"), "install.txt")
if errors then
if (option.get("verbose") or option.get("diagnosis")) then
cprint("${dim color.error}error: ${clear}%s", errors)
else
io.writefile(errorfile, errors .. "\n")
end
end
-- trace
tty.erase_line_to_start().cr()
cprint("${yellow} => ${clear}install %s %s .. ${color.failure}${text.failure}", package:displayname(), package:version_str() or "")
-- leave the package environments
os.setenvs(oldenvs)
-- copy the invalid package directory to cache
local installdir = package:installdir()
if os.isdir(installdir) then
local installdir_failed = _get_installdir_failed(package)
if not os.isdir(installdir_failed) then
os.cp(installdir, installdir_failed)
end
errorfile = path.join(installdir_failed, "logs", "install.txt")
end
os.tryrm(installdir)
-- is precompiled package? we can fallback to source package and try reinstall it again
if package:is_precompiled() then
ok = false
else
-- failed
if not package:requireinfo().optional then
if os.isfile(errorfile) then
if errors then
print("")
for idx, line in ipairs(errors:split("\n")) do
print(line)
if idx > 16 then
break
end
end
end
cprint("if you want to get more verbose errors, please see:")
cprint(" -> ${bright}%s", errorfile)
end
raise("install failed!")
end
end
end
}
}
_leave_workdir(package, oldir)
return ok
end
|
0 | repos/xmake/xmake/modules/private/action/require/impl | repos/xmake/xmake/modules/private/action/require/impl/actions/check.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.lua
--
-- imports
import("core.base.option")
import("core.project.config")
-- check the given package
function main(package, opt)
opt = opt or {}
-- we need not check it if this package is precompiled now
if package:is_precompiled() then
return
end
-- do check
local script = package:script("check")
if script then
script(package)
end
end
|
0 | repos/xmake/xmake/modules/private/action/require/impl | repos/xmake/xmake/modules/private/action/require/impl/actions/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("core.base.global")
import("core.base.tty")
import("core.base.hashset")
import("core.project.config")
import("core.package.package", {alias = "core_package"})
import("lib.detect.find_file")
import("lib.detect.find_directory")
import("private.action.require.impl.utils.filter")
import("private.action.require.impl.utils.url_filename")
import("net.http")
import("net.proxy")
import("devel.git")
import("utils.archive")
-- checkout codes from git
function _checkout(package, url, sourcedir, opt)
opt = opt or {}
-- we need to enable longpaths on windows
local longpaths = package:policy("platform.longpaths")
-- use previous source directory if exists
local packagedir = path.join(sourcedir, package:name())
if os.isdir(path.join(packagedir, ".git")) and
not (option.get("force") and package:branch()) then -- we need disable cache if we force to clone from the given branch
-- clean the previous build files
git.clean({repodir = packagedir, force = true, all = true})
-- reset the previous modified files
git.reset({repodir = packagedir, hard = true})
-- clean and reset submodules
if os.isfile(path.join(packagedir, ".gitmodules")) then
git.submodule.clean({repodir = packagedir, force = true, all = true})
git.submodule.reset({repodir = packagedir, hard = true, longpaths = longpaths})
end
tty.erase_line_to_start().cr()
return
end
-- we can use local package from the search directories directly if network is too slow
local localdir
local searchnames = {package:name() .. archive.extension(url),
path.basename(url_filename(url))}
for _, searchname in ipairs(searchnames) do
localdir = find_directory(searchname, core_package.searchdirs())
if localdir then
break
end
end
if localdir and os.isdir(path.join(localdir, ".git")) then
git.clean({repodir = localdir, force = true, all = true})
git.reset({repodir = localdir, hard = true})
if os.isfile(path.join(localdir, ".gitmodules")) then
git.submodule.clean({repodir = localdir, force = true, all = true})
git.submodule.reset({repodir = localdir, hard = true, longpaths = longpaths})
end
os.cp(localdir, packagedir)
tty.erase_line_to_start().cr()
return
end
-- remove temporary directory
os.rm(sourcedir .. ".tmp")
-- download package from branches?
packagedir = path.join(sourcedir .. ".tmp", package:name())
local branch = package:branch()
if branch then
-- we need to select the correct default branch
-- @see https://github.com/xmake-io/xmake/issues/3248
if branch == "@default" then
branch = nil
end
-- only shallow clone this branch
git.clone(url, {depth = 1, recursive = true, shallow_submodules = true, longpaths = longpaths, branch = branch, outputdir = packagedir})
-- download package from revision or tag?
else
-- get tag and revision?
local tag
local revision = package:revision(opt.url_alias)
if revision and (#revision ~= 40 or not revision:match("%w+")) then
tag = revision
end
if not tag then
tag = package:tag()
end
if not revision then
revision = tag or package:commit() or package:version_str()
end
-- only shallow clone this tag
-- @see https://github.com/xmake-io/xmake/issues/4151
if tag and git.clone.can_clone_tag() then
git.clone(url, {depth = 1, recursive = true, shallow_submodules = true, longpaths = longpaths, branch = tag, outputdir = packagedir})
else
-- clone whole history and tags
-- @see https://github.com/xmake-io/xmake/issues/5507
git.clone(url, {treeless = true, checkout = false, longpaths = longpaths, outputdir = packagedir})
-- attempt to checkout the given version
git.checkout(revision, {repodir = packagedir})
-- update all submodules
if os.isfile(path.join(packagedir, ".gitmodules")) and opt.url_submodules ~= false then
git.submodule.update({init = true, recursive = true, longpaths = longpaths, repodir = packagedir})
end
end
end
-- move to source directory
os.rm(sourcedir)
os.mv(sourcedir .. ".tmp", sourcedir)
-- trace
tty.erase_line_to_start().cr()
cprint("${yellow} => ${clear}clone %s %s .. ${color.success}${text.success}", url, package:version_str())
end
-- download codes from ftp/http/https
function _download(package, url, sourcedir, opt)
opt = opt or {}
-- get package file
local packagefile = url_filename(url)
if opt.download_only then
packagefile = package:name() .. "-" .. package:version_str() .. archive.extension(packagefile)
end
-- get sourcehash from the given url
--
-- we don't need sourcehash and skip checksum to try download it directly if no version list in package()
-- @see https://github.com/xmake-io/xmake/issues/930
-- https://github.com/xmake-io/xmake/issues/1009
--
local sourcehash = package:sourcehash(opt.url_alias)
assert(not package:is_verify() or not package:get("versions") or sourcehash, "cannot get source hash of %s in package(%s)", url, package:name())
-- the package file have been downloaded?
local cached = true
if not os.isfile(packagefile) or sourcehash ~= hash.sha256(packagefile) then
-- no cached
cached = false
-- attempt to remove package file first
os.tryrm(packagefile)
-- download or copy package file
if os.isfile(url) then
os.cp(url, packagefile)
else
local localfile
local searchnames = {package:name() .. "-" .. package:version_str() .. archive.extension(url),
packagefile}
-- match github name mangling https://github.com/xmake-io/xmake/issues/1343
local github_name = url_filename.github_filename(url)
if github_name then
table.insert(searchnames, github_name)
end
for _, searchname in ipairs(searchnames) do
localfile = find_file(searchname, core_package.searchdirs())
if localfile then
break
end
end
if localfile and os.isfile(localfile) then
-- we can use local package from the search directories directly if network is too slow
os.cp(localfile, packagefile)
else
http.download(url, packagefile, {
insecure = global.get("insecure-ssl"),
headers = opt.url_http_headers or package:policy("package.download.http_headers")})
end
end
-- check hash
if sourcehash and sourcehash ~= hash.sha256(packagefile) then
if package:is_precompiled() then
wprint("perhaps the local binary repository is not up to date, please run `xrepo update-repo` to update it and try again!")
end
raise("unmatched checksum, current hash(%s) != original hash(%s)", hash.sha256(packagefile):sub(1, 8), sourcehash:sub(1, 8))
end
end
-- we do not extract it if we download only it.
if opt.download_only then
return
end
-- extract package file
local sourcedir_tmp = sourcedir .. ".tmp"
os.rm(sourcedir_tmp)
local extension = archive.extension(packagefile)
local ok = try {function() archive.extract(packagefile, sourcedir_tmp, {excludes = opt.url_excludes}); return true end}
if ok then
-- move to source directory and we skip it to avoid long path issues on windows if only one root directory
os.rm(sourcedir)
local filedirs = os.filedirs(path.join(sourcedir_tmp, "*"))
if #filedirs == 1 and os.isdir(filedirs[1]) then
os.mv(filedirs[1], sourcedir)
-- we need to anchor it to avoid expand it when installing package
io.writefile(path.join(sourcedir, "__sourceroot_anchor__.txt"), "")
os.rm(sourcedir_tmp)
else
os.mv(sourcedir_tmp, sourcedir)
end
-- mark this sourcedir as cleanable
if not package:is_debug() then
package:data_set("cleanable_sourcedir", path.absolute(sourcedir))
end
elseif extension and extension ~= "" then
-- create an empty source directory if do not extract package file
os.tryrm(sourcedir)
os.mkdir(sourcedir)
raise("cannot extract %s, maybe missing extractor or invalid package file!", packagefile)
else
-- if it is not archive file, we only need to create empty source directory and use package:originfile()
os.tryrm(sourcedir)
os.mkdir(sourcedir)
end
-- save original file path
package:originfile_set(path.absolute(packagefile))
-- trace
tty.erase_line_to_start().cr()
if not cached then
cprint("${yellow} => ${clear}download %s .. ${color.success}${text.success}", url)
end
end
-- download codes from script
function _download_from_script(package, script, opt)
-- do download
script(package, opt)
-- trace
tty.erase_line_to_start().cr()
cprint("${yellow} => ${clear}download %s .. ${color.success}${text.success}", opt.url)
end
-- get sorted urls
function _urls(package)
-- sort urls from the version source
local urls = {{}, {}}
for _, url in ipairs(package:urls()) do
if git.checkurl(url) then
table.insert(urls[1], url)
elseif not package:is_verify() or not package:get("versions") or package:sourcehash(package:url_alias(url)) then
table.insert(urls[2], url)
end
end
if package:gitref() then
return table.join(urls[1], urls[2])
else
return table.join(urls[2], urls[1])
end
end
-- download the given package
function main(package, opt)
opt = opt or {}
-- get working directory of this package
local workdir = opt.outputdir or package:cachedir()
-- ensure the working directory first
os.mkdir(workdir)
-- enter the working directory
local oldir = os.cd(workdir)
-- lock this package
package:lock()
-- get urls
local urls = _urls(package)
assert(#urls > 0, "cannot get url of package(%s)", package:name())
-- download package from urls
local ok = false
local urls_failed = {}
for idx, url in ipairs(urls) do
local url_alias = package:url_alias(url)
local url_excludes = package:url_excludes(url)
local url_http_headers = package:url_http_headers(url)
local url_submodules = package:extraconf("urls", url, "submodules")
-- filter url
url = filter.handle(url, package)
-- use proxy url?
if not os.isfile(url) then
url = proxy.mirror(url) or url
end
-- download url
local allerrors = {}
ok = try
{
function ()
-- use debug source directory directly?
local debugdir = package:is_toplevel() and option.get("debugdir") or nil
if debugdir then
package:set("sourcedir", debugdir)
tty.erase_line_to_start().cr()
return true
end
-- download package
local sourcedir = "source"
local script = package:script("download")
if script then
_download_from_script(package, script, {
download_only = opt.download_only,
sourcedir = sourcedir,
url = url,
url_alias = url_alias,
url_excludes = url_excludes,
url_submodules = url_submodules})
elseif git.checkurl(url) then
_checkout(package, url, sourcedir, {
url_alias = url_alias,
url_submodules = url_submodules})
else
_download(package, url, sourcedir, {
download_only = opt.download_only,
url_alias = url_alias,
url_excludes = url_excludes,
url_http_headers = url_http_headers})
end
return true
end,
catch
{
function (errors)
-- show or save the last errors
if errors then
if (option.get("verbose") or option.get("diagnosis")) then
cprint("${dim color.error}error: ${clear}%s", errors)
else
table.insert(allerrors, errors)
end
end
-- trace
tty.erase_line_to_start().cr()
if git.checkurl(url) then
cprint("${yellow} => ${clear}clone %s %s .. ${color.failure}${text.failure}", url, package:version_str())
else
cprint("${yellow} => ${clear}download %s .. ${color.failure}${text.failure}", url)
end
table.insert(urls_failed, url)
-- failed? break it
if idx == #urls and not package:is_optional() then
if #urls_failed > 0 then
print("")
print("we can also download these packages manually:")
local searchnames = hashset.new()
for _, url_failed in ipairs(urls_failed) do
cprint(" ${yellow}- %s", url_failed)
if git.checkurl(url_failed) then
searchnames:insert(package:name() .. archive.extension(url_failed))
searchnames:insert(path.basename(url_filename(url_failed)))
else
local extension = archive.extension(url_failed)
if extension then
searchnames:insert(package:name() .. "-" .. package:version_str() .. extension)
end
searchnames:insert(url_filename(url_failed))
end
end
cprint("to the local search directories: ${bright}%s", table.concat(table.wrap(core_package.searchdirs()), path.envsep()))
cprint(" ${bright}- %s", table.concat(searchnames:to_array(), ", "))
cprint("and we can run `xmake g --pkg_searchdirs=/xxx` to set the search directories.")
end
if #allerrors then
raise(table.concat(allerrors, "\n"))
else
raise("download failed!")
end
end
end
}
}
if ok then
-- download only packages, we need not to install it, so we need flush console output
if opt.download_only then
tty.erase_line_to_start().cr()
if git.checkurl(url) then
cprint("${yellow} => ${clear}clone %s %s .. ${color.success}${text.success}", url, package:version_str())
else
cprint("${yellow} => ${clear}download %s .. ${color.success}${text.success}", url)
end
end
break
end
end
-- unlock this package
package:unlock()
-- leave working directory
os.cd(oldir)
return ok
end
|
0 | repos/xmake/xmake/modules/private/action/require/impl | repos/xmake/xmake/modules/private/action/require/impl/utils/requirekey.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 requirekey.lua
--
-- imports
import("core.base.hashset")
-- get require key from requireinfo
function main(requireinfo, opt)
opt = opt or {}
local key = ""
if opt.name then
key = key .. "/" .. opt.name
end
if opt.plat then
key = key .. "/" .. opt.plat
end
if opt.arch then
key = key .. "/" .. opt.arch
end
if opt.kind then
key = key .. "/" .. opt.kind
end
if opt.version then
key = key .. "/" .. opt.version
end
if requireinfo.label then
key = key .. "/" .. requireinfo.label
end
if requireinfo.system then
key = key .. "/system"
end
if requireinfo.private then
key = key .. "/private"
end
if key:startswith("/") then
key = key:sub(2)
end
local configs = requireinfo.configs
if configs then
local configs_order = {}
for k, v in pairs(configs) do
if type(v) == "table" then
v = string.serialize(v, {strip = true, indent = false, orderkeys = true})
end
table.insert(configs_order, k .. "=" .. tostring(v))
end
table.sort(configs_order)
key = key .. ":" .. string.serialize(configs_order, true)
end
if opt.hash then
if key == "" then
key = "_" -- we need to generate a fixed hash value
end
return hash.uuid(key):split("-", {plain = true})[1]:lower()
else
return key
end
end
|
0 | repos/xmake/xmake/modules/private/action/require/impl | repos/xmake/xmake/modules/private/action/require/impl/utils/url_filename.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 url_filename.lua
--
-- get raw filename
function raw_filename(url)
local urlpath = url:split('?', {plain = true})[1]
return path.filename(urlpath)
end
-- get filename from github name mangling
function github_filename(url)
local reponame = url:match("^https://github.com/[^/]-/([^/]-)/archive/")
if reponame then
local filename = raw_filename(url)
if filename:find("^v%d") then
filename = filename:match("^v(.+)")
end
return reponame .. "-" .. filename
end
end
-- get filename from url
function main(url)
return raw_filename(url)
end
|
0 | repos/xmake/xmake/modules/private/action/require/impl | repos/xmake/xmake/modules/private/action/require/impl/utils/get_requires.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 get_requires.lua
--
-- imports
import("core.base.option")
import("core.project.project")
-- get requires and extra config
function main(requires)
-- init requires
local requires_extra = nil
if not requires then
requires, requires_extra = project.requires_str()
end
if not requires or #requires == 0 then
return
end
-- get extra info
local extra = option.get("extra")
local extrainfo = nil
if extra then
local v, err = string.deserialize(extra)
if err then
raise(err)
else
extrainfo = v
end
end
-- force to use the given requires extra info
if extrainfo then
requires_extra = requires_extra or {}
for _, require_str in ipairs(requires) do
requires_extra[require_str] = extrainfo
end
end
return requires, requires_extra
end
|
0 | repos/xmake/xmake/modules/private/action/require/impl | repos/xmake/xmake/modules/private/action/require/impl/utils/filter.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 filter.lua
--
-- imports
import("core.base.filter")
import("core.base.option")
import("core.base.global")
import("core.project.config")
import("core.project.project")
import("core.sandbox.sandbox")
-- get filter
function _filter()
if _g.filter == nil then
_g.filter = filter.new()
_g.filter:register("common", function (variable)
-- attempt to get it directly from the configure
local result = config.get(variable)
if result == nil then
-- init maps
_g.common_maps = _g.common_maps or
{
host = os.host()
, subhost = os.subhost()
, tmpdir = function () return os.tmpdir() end
, curdir = function () return os.curdir() end
, scriptdir = function () return os.scriptdir() end
, globaldir = global.directory()
, configdir = config.directory()
, projectdir = project.directory()
, programdir = os.programdir()
}
-- map it
result = _g.common_maps[variable]
end
-- is script? call it
if type(result) == "function" then
result = result()
end
return result
end)
end
return _g.filter
end
-- the package handler
function _handler(package, strval)
-- @note cannot cache it, because the package instance will be changed
return function (variable)
local maps = {
version = function ()
if strval then
-- set_urls("https://sqlite.org/2018/sqlite-autoconf-$(version)000.tar.gz",
-- {version = function (version) return version:gsub("%.", "") end})
local version_filter = package:url_version(strval)
if version_filter then
local v = version_filter(package:version())
if v ~= nil then
-- may be semver version object
v = tostring(v)
end
return v
end
end
return package:version_str()
end
}
-- get value
local result = maps[variable]
if type(result) == "function" then
result = result()
end
return result
end
end
-- attach filter to the given script and call it
function call(script, package, opt)
-- get sandbox filter and handlers of the given script
local sandbox_filter = sandbox.filter(script)
local sandbox_handlers = sandbox_filter:handlers()
-- switch to the handlers of the current filter
sandbox_filter:set_handlers(_filter():handlers())
-- register package handler
sandbox_filter:register("package", _handler(package))
-- call it
script(package, opt)
-- restore handlers
sandbox_filter:set_handlers(sandbox_handlers)
end
-- handle the string value of package
function handle(strval, package)
-- register filter handler
_filter():register("package", _handler(package, strval))
-- handle string value
strval = _filter():handle(strval)
-- register filter handler
_filter():register("package", nil)
-- ok
return strval
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/trybuild/ndkbuild.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 ndkbuild.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("lib.detect.find_file")
-- get ndk directory
function _get_ndkdir()
local ndk = assert(config.get("ndk"), "ndkbuild: please uses `xmake f --ndk=` to set the ndk path!")
return path.absolute(ndk)
end
-- detect build-system and configuration file
function detect()
return find_file("Android.mk", path.join(os.curdir(), "jni"))
end
-- do clean
function clean()
-- get the ndk root directory
local ndk = _get_ndkdir()
assert(os.isdir(ndk), "%s not found!", ndk)
-- do clean
os.vexecv(path.join(ndk, "ndk-build"), {"clean"}, {envs = {NDK_ROOT = ndk}})
end
-- do build
function build()
-- only support the android platform now!
assert(is_plat("android"), "ndkbuild: please uses `xmake f -p android --trybuild=ndkbuild` to switch to android platform!")
-- get the ndk root directory
local ndk = _get_ndkdir()
assert(os.isdir(ndk), "%s not found!", ndk)
-- do build
local argv = {}
if option.get("verbose") then
table.insert(argv, "V=1")
end
local ndkbuild = path.join(ndk, "ndk-build")
if is_host("windows") then
ndkbuild = ndkbuild .. ".cmd"
end
os.vexecv(ndkbuild, argv, {envs = {NDK_ROOT = ndk}})
cprint("${color.success}build ok!")
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/trybuild/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.tool.toolchain")
import("lib.detect.find_file")
import("lib.detect.find_tool")
-- find project file
function _find_projectfile()
return find_file("*.sln", os.curdir())
end
-- detect build-system and configuration file
function detect()
if is_subhost("windows") then
return _find_projectfile()
end
end
-- do clean
function clean()
local projectfile = _find_projectfile()
local runenvs = toolchain.load("msvc"):runenvs()
local msbuild = find_tool("msbuild", {envs = runenvs})
local projectdata = io.readfile(projectfile)
if projectdata and projectdata:find("Any CPU", 1, true) then
platform = "Any CPU"
end
os.vexecv(msbuild.program, {projectfile, "-nologo", "-t:Clean", "-p:Configuration=Release", "-p:Platform=" .. platform}, {envs = runenvs})
end
-- do build
function build()
-- only support the current subsystem host platform now!
assert(is_subhost(config.plat()), "msbuild: %s not supported!", config.plat())
-- do build
local projectfile = _find_projectfile()
local runenvs = toolchain.load("msvc"):runenvs()
local msbuild = find_tool("msbuild", {envs = runenvs})
local platform = is_arch("x64") and "x64" or "Win32"
local projectdata = io.readfile(projectfile)
if projectdata and projectdata:find("Any CPU", 1, true) then
platform = "Any CPU"
end
os.vexecv(msbuild.program, {projectfile, "-nologo", "-t:Build", "-p:Configuration=Release", "-p:Platform=" .. platform}, {envs = runenvs})
cprint("${color.success}build ok!")
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/trybuild/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("core.project.config")
import("lib.detect.find_file")
import("lib.detect.find_tool")
-- detect build-system and configuration file
function detect()
return find_file("build.ninja", os.curdir())
end
-- do clean
function clean()
local ninja = assert(find_tool("ninja"), "ninja not found!")
local ninja_argv = {"-C", os.curdir()}
if option.get("verbose") or option.get("diagnosis") then
table.insert(ninja_argv, "-v")
end
table.insert(ninja_argv, "-t")
table.insert(ninja_argv, "clean")
os.vexecv(ninja.program, ninja_argv)
end
-- do build
function build()
local ninja = assert(find_tool("ninja"), "ninja not found!")
local ninja_argv = {"-C", os.curdir()}
if option.get("verbose") then
table.insert(ninja_argv, "-v")
end
table.insert(ninja_argv, "-j")
table.insert(ninja_argv, option.get("jobs"))
os.vexecv(ninja.program, ninja_argv)
cprint("${color.success}build ok!")
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/trybuild/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.project.config")
import("lib.detect.find_file")
import("lib.detect.find_tool")
-- detect build-system and configuration file
function detect()
return find_file("BUILD", os.curdir()) or find_file("BUILD.bazel", os.curdir())
end
-- do clean
function clean()
local bazel = assert(find_tool("bazel"), "bazel not found!")
os.vexecv(bazel.program, {"clean"})
end
-- do build
function build()
-- only support the current subsystem host platform now!
assert(is_subhost(config.plat()), "bazel: %s not supported!", config.plat())
-- do build
local bazel = assert(find_tool("bazel"), "bazel not found!")
os.vexecv(bazel.program, {"build"})
cprint("${color.success}build ok!")
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/trybuild/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.project.config")
import("core.tool.toolchain")
import("core.platform.platform")
import("lib.detect.find_file")
import("lib.detect.find_tool")
import("private.utils.toolchain", {alias = "toolchain_utils"})
-- get build directory
function _get_buildir()
return config.buildir() or "build"
end
-- get artifacts directory
function _get_artifacts_dir()
return path.absolute(path.join(_get_buildir(), "artifacts"))
end
-- get the build environment
function _get_buildenv(key)
local value = config.get(key)
if value == nil then
value = platform.toolconfig(key, config.plat())
end
if value == nil then
value = platform.tool(key, config.plat())
end
return value
end
-- get vs arch
function _get_vsarch()
local arch = get_config("arch") or os.arch()
if arch == "x86" or arch == "i386" then return "Win32" end
if arch == "x86_64" then return "x64" end
if arch == "arm64ec" then return "ARM64EC" end
if arch:startswith("arm64") then return "ARM64" end
if arch:startswith("arm") then return "ARM" end
return arch
end
-- get msvc
function _get_msvc()
local msvc = toolchain.load("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()
return os.joinenvs(_get_msvc():runenvs())
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
-- is cross compilation?
function _is_cross_compilation()
if not is_plat(os.subhost()) then
return true
end
if is_plat("macosx") and not is_arch(os.subarch()) then
return true
end
return false
end
function _get_cmake_system_processor()
-- on Windows, CMAKE_SYSTEM_PROCESSOR comes from PROCESSOR_ARCHITECTURE
-- on other systems it's the output of uname -m
if is_plat("windows") then
local archs = {
x86 = "x86",
x64 = "AMD64",
x86_64 = "AMD64",
arm = "ARM",
arm64 = "ARM64",
arm64ec = "ARM64EC"
}
return archs[os.subarch()] or os.subarch()
end
return os.subarch()
end
-- get configs for windows
function _get_configs_for_windows(configs, opt)
opt = opt or {}
local cmake_generator = opt.cmake_generator
if cmake_generator and not cmake_generator:find("Visual Studio", 1, true) then
return
end
table.insert(configs, "-A")
if is_arch("x86", "i386") then
table.insert(configs, "Win32")
else
table.insert(configs, "x64")
end
end
-- get configs for android
function _get_configs_for_android(configs)
-- https://developer.android.google.cn/ndk/guides/cmake
local ndk = config.get("ndk")
if ndk and os.isdir(ndk) then
local arch = config.arch()
local ndk_sdkver = config.get("ndk_sdkver")
local ndk_cxxstl = config.get("ndk_cxxstl")
table.insert(configs, "-DCMAKE_TOOLCHAIN_FILE=" .. path.join(ndk, "build/cmake/android.toolchain.cmake"))
if arch then
table.insert(configs, "-DANDROID_ABI=" .. arch)
end
if ndk_sdkver then
table.insert(configs, "-DANDROID_NATIVE_API_LEVEL=" .. ndk_sdkver)
end
if ndk_cxxstl then
table.insert(configs, "-DANDROID_STL=" .. ndk_cxxstl)
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
end
-- get configs for appleos
function _get_configs_for_appleos(configs)
local envs = {}
local cflags = table.join(table.wrap(_get_buildenv("cxflags")), _get_buildenv("cflags"))
local cxxflags = table.join(table.wrap(_get_buildenv("cxflags")), _get_buildenv("cxxflags"))
envs.CMAKE_C_FLAGS = table.concat(cflags, ' ')
envs.CMAKE_CXX_FLAGS = table.concat(cxxflags, ' ')
envs.CMAKE_ASM_FLAGS = table.concat(table.wrap(_get_buildenv("asflags")), ' ')
envs.CMAKE_STATIC_LINKER_FLAGS = table.concat(table.wrap(_get_buildenv("arflags")), ' ')
envs.CMAKE_EXE_LINKER_FLAGS = table.concat(table.wrap(_get_buildenv("ldflags")), ' ')
envs.CMAKE_SHARED_LINKER_FLAGS = table.concat(table.wrap(_get_buildenv("shflags")), ' ')
-- https://cmake.org/cmake/help/v3.17/manual/cmake-toolchains.7.html#id25
if is_plat("watchos") then
envs.CMAKE_SYSTEM_NAME = "watchOS"
if is_arch("x86_64", "i386") then
envs.CMAKE_OSX_SYSROOT = "watchsimulator"
end
elseif is_plat("iphoneos") then
envs.CMAKE_SYSTEM_NAME = "iOS"
if is_arch("x86_64", "i386") then
envs.CMAKE_OSX_SYSROOT = "iphonesimulator"
end
elseif _is_cross_compilation() then
envs.CMAKE_SYSTEM_NAME = "Darwin"
envs.CMAKE_SYSTEM_PROCESSOR = _get_cmake_system_processor()
end
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"
for k, v in pairs(envs) do
table.insert(configs, "-D" .. k .. "=" .. v)
end
end
-- get configs for mingw
function _get_configs_for_mingw(configs)
local envs = {}
local cflags = table.join(table.wrap(_get_buildenv("cxflags")), _get_buildenv("cflags"))
local cxxflags = table.join(table.wrap(_get_buildenv("cxflags")), _get_buildenv("cxxflags"))
local sdkdir = _get_buildenv("mingw") or _get_buildenv("sdk")
envs.CMAKE_C_COMPILER = _get_buildenv("cc")
envs.CMAKE_CXX_COMPILER = _get_buildenv("cxx")
envs.CMAKE_ASM_COMPILER = _get_buildenv("as")
envs.CMAKE_AR = _get_buildenv("ar")
envs.CMAKE_LINKER = _get_buildenv("ld")
envs.CMAKE_RANLIB = _get_buildenv("ranlib")
envs.CMAKE_C_FLAGS = table.concat(cflags, ' ')
envs.CMAKE_CXX_FLAGS = table.concat(cxxflags, ' ')
envs.CMAKE_ASM_FLAGS = table.concat(table.wrap(_get_buildenv("asflags")), ' ')
envs.CMAKE_STATIC_LINKER_FLAGS = table.concat(table.wrap(_get_buildenv("arflags")), ' ')
envs.CMAKE_EXE_LINKER_FLAGS = table.concat(table.wrap(_get_buildenv("ldflags")), ' ')
envs.CMAKE_SHARED_LINKER_FLAGS = table.concat(table.wrap(_get_buildenv("shflags")), ' ')
envs.CMAKE_SYSTEM_NAME = "Windows"
envs.CMAKE_SYSTEM_PROCESSOR = _get_cmake_system_processor()
-- avoid find and add system include/library path
envs.CMAKE_FIND_ROOT_PATH = sdkdir
envs.CMAKE_SYSROOT = 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"
for k, v in pairs(envs) do
table.insert(configs, "-D" .. k .. "=" .. v)
end
end
-- get configs for wasm
function _get_configs_for_wasm(configs)
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)
assert(emscripten_cmakefile, "Emscripten.cmake not found!")
_get_configs_for_generic(configs)
end
-- get configs for cross
function _get_configs_for_cross(configs)
local envs = {}
local cflags = table.join(table.wrap(_get_buildenv("cxflags")), _get_buildenv("cflags"))
local cxxflags = table.join(table.wrap(_get_buildenv("cxflags")), _get_buildenv("cxxflags"))
local sdkdir = _translate_paths(_get_buildenv("sdk"))
envs.CMAKE_C_COMPILER = _translate_bin_path(_get_buildenv("cc"))
envs.CMAKE_CXX_COMPILER = _translate_bin_path(_get_buildenv("cxx"))
envs.CMAKE_ASM_COMPILER = _translate_bin_path(_get_buildenv("as"))
envs.CMAKE_AR = _translate_bin_path(_get_buildenv("ar"))
-- https://github.com/xmake-io/xmake-repo/pull/1096
local cxx = envs.CMAKE_CXX_COMPILER
if cxx and (cxx:find("clang", 1, true) or cxx:find("gcc", 1, true)) 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.CMAKE_CXX_COMPILER = _translate_bin_path(dir and path.join(dir, name) or name)
end
-- @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
envs.CMAKE_LINKER = _translate_bin_path(_get_buildenv("ld"))
local ld = envs.CMAKE_LINKER
if ld and (ld:find("g++", 1, true) or ld:find("clang++", 1, true)) then
envs.CMAKE_CXX_LINK_EXECUTABLE = "<CMAKE_LINKER> <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>"
end
envs.CMAKE_RANLIB = _translate_bin_path(_get_buildenv("ranlib"))
envs.CMAKE_C_FLAGS = table.concat(cflags, ' ')
envs.CMAKE_CXX_FLAGS = table.concat(cxxflags, ' ')
envs.CMAKE_ASM_FLAGS = table.concat(table.wrap(_get_buildenv("asflags")), ' ')
envs.CMAKE_STATIC_LINKER_FLAGS = table.concat(table.wrap(_get_buildenv("arflags")), ' ')
envs.CMAKE_EXE_LINKER_FLAGS = table.concat(table.wrap(_get_buildenv("ldflags")), ' ')
envs.CMAKE_SHARED_LINKER_FLAGS = table.concat(table.wrap(_get_buildenv("shflags")), ' ')
envs.CMAKE_SYSTEM_NAME = "Linux"
-- avoid find and add system include/library path
envs.CMAKE_FIND_ROOT_PATH = sdkdir
envs.CMAKE_SYSROOT = 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"
for k, v in pairs(envs) do
table.insert(configs, "-D" .. k .. "=" .. v)
end
end
-- get configs for host toolchain
function _get_configs_for_host_toolchain(configs)
local envs = {}
local cflags = table.join(table.wrap(_get_buildenv("cxflags")), _get_buildenv("cflags"))
local cxxflags = table.join(table.wrap(_get_buildenv("cxflags")), _get_buildenv("cxxflags"))
local sdkdir = _translate_paths(_get_buildenv("sdk"))
envs.CMAKE_C_COMPILER = _translate_bin_path(_get_buildenv("cc"))
envs.CMAKE_CXX_COMPILER = _translate_bin_path(_get_buildenv("cxx"))
envs.CMAKE_ASM_COMPILER = _translate_bin_path(_get_buildenv("as"))
envs.CMAKE_AR = _translate_bin_path(_get_buildenv("ar"))
-- https://github.com/xmake-io/xmake-repo/pull/1096
local cxx = envs.CMAKE_CXX_COMPILER
if cxx and (cxx:find("clang", 1, true) or cxx:find("gcc", 1, true)) 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.CMAKE_CXX_COMPILER = _translate_bin_path(dir and path.join(dir, name) or name)
end
-- @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
envs.CMAKE_LINKER = _translate_bin_path(_get_buildenv("ld"))
local ld = envs.CMAKE_LINKER
if ld and (ld:find("g++", 1, true) or ld:find("clang++", 1, true)) then
envs.CMAKE_CXX_LINK_EXECUTABLE = "<CMAKE_LINKER> <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>"
end
envs.CMAKE_RANLIB = _translate_bin_path(_get_buildenv("ranlib"))
envs.CMAKE_C_FLAGS = table.concat(cflags, ' ')
envs.CMAKE_CXX_FLAGS = table.concat(cxxflags, ' ')
envs.CMAKE_ASM_FLAGS = table.concat(table.wrap(_get_buildenv("asflags")), ' ')
envs.CMAKE_STATIC_LINKER_FLAGS = table.concat(table.wrap(_get_buildenv("arflags")), ' ')
envs.CMAKE_EXE_LINKER_FLAGS = table.concat(table.wrap(_get_buildenv("ldflags")), ' ')
envs.CMAKE_SHARED_LINKER_FLAGS = table.concat(table.wrap(_get_buildenv("shflags")), ' ')
-- we don't need to set it as cross compilation if we just pass toolchain
-- https://github.com/xmake-io/xmake/issues/2170
if _is_cross_compilation() then
envs.CMAKE_SYSTEM_NAME = "Linux"
end
for k, v in pairs(envs) do
table.insert(configs, "-D" .. k .. "=" .. v)
end
end
-- get cmake generator for msvc
function _get_cmake_generator_for_msvc()
local vsvers =
{
["2022"] = "17",
["2019"] = "16",
["2017"] = "15",
["2015"] = "14",
["2013"] = "12",
["2012"] = "11",
["2010"] = "10",
["2008"] = "9"
}
local vs = _get_msvc():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(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()
end
table.insert(configs, "-G")
table.insert(configs, cmake_generator)
elseif is_plat("mingw") and is_subhost("msys") then
table.insert(configs, "-G")
table.insert(configs, "MSYS Makefiles")
elseif is_plat("mingw") and is_subhost("windows") then
table.insert(configs, "-G")
table.insert(configs, "MinGW Makefiles")
elseif is_plat("windows") then
table.insert(configs, "-G")
table.insert(configs, _get_cmake_generator_for_msvc())
elseif 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(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=" .. opt.artifacts_dir)
table.insert(configs, "-DCMAKE_INSTALL_LIBDIR:PATH=lib")
end
-- get configs
function _get_configs(opt)
local configs = {}
_get_configs_for_install(configs, opt)
_get_configs_for_generator(configs, opt)
if is_plat("windows") then
_get_configs_for_windows(configs, opt)
elseif is_plat("android") then
_get_configs_for_android(configs)
elseif is_plat("iphoneos", "watchos") or
-- for cross-compilation on macOS, @see https://github.com/xmake-io/xmake/issues/2804
(is_plat("macosx") and (get_config("appledev") or not is_arch(os.subarch()))) then
_get_configs_for_appleos(configs)
elseif is_plat("mingw") then
_get_configs_for_mingw(configs)
elseif is_plat("wasm") then
_get_configs_for_wasm(configs)
elseif _is_cross_compilation() then
_get_configs_for_cross(configs)
elseif config.get("toolchain") then
-- we still need find system libraries,
-- it just pass toolchain environments if the toolchain is compatible with host
if toolchain_utils.is_compatible_with_host(config.get("toolchain")) then
_get_configs_for_host_toolchain(configs)
else
_get_configs_for_cross(configs)
end
end
-- enable verbose?
if option.get("verbose") then
table.insert(configs, "-DCMAKE_VERBOSE_MAKEFILE=ON")
end
-- add extra user configs
local tryconfigs = config.get("tryconfigs")
if tryconfigs then
for _, item in ipairs(os.argv(tryconfigs)) do
table.insert(configs, tostring(item))
end
end
-- add build directory
table.insert(configs, '..')
return configs
end
-- build for msvc
function _build_for_msvc(opt)
local runenvs = _get_msvc_runenvs()
local msbuild = find_tool("msbuild", {envs = runenvs})
local slnfile = assert(find_file("*.sln", os.curdir()), "*.sln file not found!")
os.vexecv(msbuild.program, {slnfile, "-nologo", "-t:Build", "-m",
"-p:Configuration=" .. (is_mode("debug") and "Debug" or "Release"),
"-p:Platform=" .. _get_vsarch()}, {envs = runenvs})
local projfile = os.isfile("INSTALL.vcxproj") and "INSTALL.vcxproj" or "INSTALL.vcproj"
if os.isfile(projfile) then
os.vexecv(msbuild.program, {projfile, "/property:configuration=" .. (is_mode("debug") and "Debug" or "Release")}, {envs = runenvs})
end
end
-- build for make
function _build_for_make(opt)
local argv = {"-j" .. option.get("jobs")}
if option.get("verbose") then
table.insert(argv, "VERBOSE=1")
end
if is_host("bsd") then
os.vexecv("gmake", argv)
os.vexecv("gmake", {"install"})
else
os.vexecv("make", argv)
os.vexecv("make", {"install"})
end
end
-- build for ninja
function _build_for_ninja(opt)
local njob = option.get("jobs") or tostring(os.default_njob())
local ninja = assert(find_tool("ninja"), "ninja not found!")
local argv = {}
if option.get("diagnosis") then
table.insert(argv, "-v")
end
table.insert(argv, "-j")
table.insert(argv, njob)
local envs
if is_plat("windows") then
envs = _get_msvc_runenvs()
end
os.vexecv(ninja.program, argv, {envs = envs})
end
-- detect build-system and configuration file
function detect()
return find_file("CMakeLists.txt", os.curdir())
end
-- do clean
function clean()
local buildir = _get_buildir()
if os.isdir(buildir) then
local configfile = find_file("[mM]akefile", buildir) or (is_plat("windows") and find_file("*.sln", buildir))
if configfile then
local oldir = os.cd(buildir)
if is_plat("windows") then
local runenvs = _get_msvc_runenvs()
local msbuild = find_tool("msbuild", {envs = runenvs})
os.vexecv(msbuild.program, {configfile, "-nologo", "-t:Clean", "-p:Configuration=" .. (is_mode("debug") and "Debug" or "Release"), "-p:Platform=" .. (is_arch("x64") and "x64" or "Win32")}, {envs = runenvs})
else
os.vexec("make clean")
end
os.cd(oldir)
end
end
end
-- do build
function build()
-- get cmake
local cmake = assert(find_tool("cmake"), "cmake not found!")
-- get artifacts directory
local opt = {}
local artifacts_dir = _get_artifacts_dir()
if not os.isdir(artifacts_dir) then
os.mkdir(artifacts_dir)
end
os.cd(_get_buildir())
opt.artifacts_dir = artifacts_dir
-- exists $CMAKE_GENERATOR? use it
opt.cmake_generator = os.getenv("CMAKE_GENERATOR")
-- do configure
os.vexecv(cmake.program, _get_configs(opt))
-- do build
local cmake_generator = opt.cmake_generator
if cmake_generator then
if cmake_generator:find("Visual Studio", 1, true) then
_build_for_msvc(opt)
elseif cmake_generator == "Ninja" then
_build_for_ninja(opt)
elseif cmake_generator:find("Makefiles", 1, true) then
_build_for_make(opt)
else
raise("unknown cmake generator(%s)!", cmake_generator)
end
else
if is_plat("windows") then
_build_for_msvc(opt)
else
_build_for_make(opt)
end
end
cprint("output to ${bright}%s", artifacts_dir)
cprint("${color.success}build ok!")
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/trybuild/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_file")
-- detect build-system and configuration file
function detect()
return find_file("[mM]akefile", os.curdir())
end
-- do clean
function clean()
if is_subhost("windows") then
os.vexec("nmake clean")
else
os.vexec("make clean")
end
end
-- do build
function build()
assert(is_subhost(config.plat()), "make: %s not supported!", config.plat())
local argv = {}
if option.get("verbose") then
table.insert(argv, "VERBOSE=1")
end
if is_subhost("windows") then
os.vexecv("nmake", argv)
else
table.insert(argv, "-j" .. option.get("jobs"))
if is_host("bsd") then
os.vexecv("gmake", argv)
else
os.vexecv("make", argv)
end
end
cprint("${color.success}build ok!")
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/trybuild/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.platform.platform")
import("lib.detect.find_file")
import("lib.detect.find_tool")
-- get build directory
function _get_buildir()
return config.buildir() or "build"
end
-- get artifacts directory
function _get_artifacts_dir()
return path.absolute(path.join(_get_buildir(), "artifacts"))
end
-- is cross compilation?
function _is_cross_compilation()
if not is_plat(os.subhost()) then
return true
end
if is_plat("macosx") and not is_arch(os.subarch()) then
return true
end
return false
end
-- get pkg-config
function _get_pkgconfig()
if is_plat("windows") then
local pkgconf = find_tool("pkgconf")
if pkgconf then
return pkgconf.program
end
end
local pkgconfig = find_tool("pkg-config")
if pkgconfig then
return pkgconfig.program
end
end
-- get the build environment
function _get_buildenv(key)
local value = config.get(key)
if value == nil then
value = platform.toolconfig(key, config.plat())
end
if value == nil then
value = platform.tool(key, config.plat())
end
return value
end
-- get cross file
function _get_cross_file(buildir)
local crossfile = path.join(buildir, "cross_file.txt")
if not os.isfile(crossfile) then
local file = io.open(crossfile, "w")
-- binaries
file:print("[binaries]")
local cc = _get_buildenv("cc")
if cc then
-- we need to split it, maybe is `xcrun -sdk iphoneos clang`
file:print("c=['%s']", table.concat(os.argv(cc), "', '"))
end
local cxx = _get_buildenv("cxx")
if cxx then
file:print("cpp=['%s']", table.concat(os.argv(cxx), "', '"))
end
local ld = _get_buildenv("ld")
if ld then
file:print("ld=['%s']", table.concat(os.argv(ld), "', '"))
end
local ar = _get_buildenv("ar")
if ar then
file:print("ar=['%s']", table.concat(os.argv(ar), "', '"))
end
local strip = _get_buildenv("strip")
if strip then
file:print("strip='%s'", strip)
end
local ranlib = _get_buildenv("ranlib")
if ranlib then
file:print("ranlib='%s'", ranlib)
end
if is_plat("mingw") then
local mrc = _get_buildenv("mrc")
if mrc then
file:print("windres='%s'", mrc)
end
end
local cmake = find_tool("cmake")
if cmake then
file:print("cmake='%s'", cmake.program)
end
local pkgconfig = _get_pkgconfig()
if pkgconfig then
file:print("pkgconfig='%s'", pkgconfig)
end
file:print("")
-- built-in options
file:print("[built-in options]")
local cflags = table.join(table.wrap(_get_buildenv("cxflags")), _get_buildenv("cflags"))
local cxxflags = table.join(table.wrap(_get_buildenv("cxflags")), _get_buildenv("cxxflags"))
local asflags = table.wrap(_get_buildenv("asflags"))
local arflags = table.wrap(_get_buildenv("arflags"))
local ldflags = table.wrap(_get_buildenv("ldflags"))
local shflags = table.wrap(_get_buildenv("shflags"))
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
file:print("")
-- host machine
file:print("[host_machine]")
if is_plat("iphoneos", "macosx") then
local cpu
local cpu_family
if is_arch("arm64") then
cpu = "aarch64"
cpu_family = "aarch64"
elseif is_arch("armv7") then
cpu = "arm"
cpu_family = "arm"
elseif is_arch("x64", "x86_64") then
cpu = "x86_64"
cpu_family = "x86_64"
elseif is_arch("x86", "i386") then
cpu = "i686"
cpu_family = "x86"
else
raise("unsupported arch(%s)", config.arch())
end
file:print("system = 'darwin'")
file:print("cpu_family = '%s'", cpu_family)
file:print("cpu = '%s'", cpu)
file:print("endian = 'little'")
elseif is_plat("android") then
-- TODO
raise("android has been not supported now!")
elseif is_plat("mingw") then
local cpu
local cpu_family
if is_arch("x64", "x86_64") then
cpu = "x86_64"
cpu_family = "x86_64"
elseif is_arch("x86", "i386") then
cpu = "i686"
cpu_family = "x86"
else
raise("unsupported arch(%s)", config.arch())
end
file:print("system = 'windows'")
file:print("cpu_family = '%s'", cpu_family)
file:print("cpu = '%s'", cpu)
file:print("endian = 'little'")
elseif is_plat("wasm") then
file:print("system = 'emscripten'")
file:print("cpu_family = 'wasm32'")
file:print("cpu = 'wasm32'")
file:print("endian = 'little'")
elseif is_plat("cross") then
local cpu = config.arch()
if is_arch("arm64") then
cpu = "aarch64"
elseif is_arch("arm.*") then
cpu = "arm"
end
local cpu_family = cpu
file:print("system = '%s'", get_config("target_os") or "linux")
file:print("cpu_family = '%s'", cpu_family)
file:print("cpu = '%s'", cpu)
file:print("endian = 'little'")
end
file:print("")
file:close()
end
return crossfile
end
-- get configs
function _get_configs(artifacts_dir, buildir)
-- add prefix
local configs = {"--prefix=" .. artifacts_dir}
if configfile then
table.insert(configs, "--reconfigure")
end
-- add extra user configs
local tryconfigs = config.get("tryconfigs")
if tryconfigs then
for _, opt in ipairs(os.argv(tryconfigs)) do
table.insert(configs, tostring(opt))
end
end
-- add cross file
if _is_cross_compilation() then
table.insert(configs, "--cross-file=" .. _get_cross_file(buildir))
end
-- add build directory
table.insert(configs, buildir)
return configs
end
-- detect build-system and configuration file
function detect()
return find_file("meson.build", os.curdir())
end
-- do clean
function clean()
local buildir = _get_buildir()
if os.isdir(buildir) then
local configfile = find_file("build.ninja", buildir)
if configfile then
local ninja = assert(find_tool("ninja"), "ninja not found!")
local ninja_argv = {"-C", buildir}
if option.get("verbose") or option.get("diagnosis") then
table.insert(ninja_argv, "-v")
end
table.insert(ninja_argv, "-t")
table.insert(ninja_argv, "clean")
os.vexecv(ninja.program, ninja_argv)
if option.get("all") then
os.tryrm(buildir)
end
end
end
end
-- do build
function build()
-- get artifacts directory
local artifacts_dir = _get_artifacts_dir()
if not os.isdir(artifacts_dir) then
os.mkdir(artifacts_dir)
end
-- generate makefile
local buildir = _get_buildir()
local meson = assert(find_tool("meson"), "meson not found!")
local configfile = find_file("build.ninja", buildir)
if not configfile or os.mtime(config.filepath()) > os.mtime(configfile) then
os.vexecv(meson.program, _get_configs(artifacts_dir, buildir))
end
-- do build
local ninja = assert(find_tool("ninja"), "ninja not found!")
local ninja_argv = {"-C", buildir}
if option.get("verbose") then
table.insert(ninja_argv, "-v")
end
table.insert(ninja_argv, "-j")
table.insert(ninja_argv, option.get("jobs"))
os.vexecv(ninja.program, ninja_argv)
os.vexecv(ninja.program, table.join("install", ninja_argv))
cprint("output to ${bright}%s", artifacts_dir)
cprint("${color.success}build ok!")
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/trybuild/xrepo.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 xrepo.lua
--
-- imports
import("core.base.option")
import("core.base.semver")
import("core.project.config")
import("lib.detect.find_file")
import("lib.detect.find_tool")
import("private.action.require.impl.search_packages")
-- get build directory
function _get_buildir()
return config.buildir() or "build"
end
-- get artifacts directory
function _get_artifacts_dir()
return path.absolute(path.join(_get_buildir(), "artifacts"))
end
-- detect build-system and configuration file
function detect()
-- we need xrepo
local xrepo = find_tool("xrepo")
if not xrepo then
return
end
-- get package name and version
local dirname = path.filename(os.curdir())
local packagename = dirname
local version = semver.match(dirname)
if version then
local pos = dirname:find("v" .. version:rawstr(), 1, true) or dirname:find(version:rawstr(), 1, true)
if pos then
packagename = dirname:sub(1, pos - 1)
if packagename:endswith("-") or packagename:endswith("_") then
packagename = packagename:sub(1, #packagename - 1):lower()
end
end
end
packagename = packagename:trim()
if #packagename == 0 then
return
end
-- search packages
local result
local packages_found = search_packages(packagename, {description = false, require_version = version and version:rawstr() or nil})
for name, packages in pairs(packages_found) do
for _, package in ipairs(packages) do
if package.name == packagename or packagename:levenshtein(package.name) < 3 then
result = package
break
end
end
end
if result then
_g.package = result
if result.version then
return ("%s %s in %s"):format(result.name, result.version, result.reponame)
else
return ("%s in %s"):format(result.name, result.reponame)
end
end
end
-- get common configs
function _get_common_configs(argv)
table.insert(argv, "-y")
table.insert(argv, "--shallow")
table.insert(argv, "-v")
if option.get("diagnosis") then
table.insert(argv, "-D")
end
if config.get("plat") then
table.insert(argv, "-p")
table.insert(argv, config.get("plat"))
end
if config.get("arch") then
table.insert(argv, "-a")
table.insert(argv, config.get("arch"))
end
if config.get("mode") then
table.insert(argv, "-m")
table.insert(argv, config.get("mode"))
end
if config.get("kind") then
table.insert(argv, "-k")
table.insert(argv, config.get("kind"))
end
if config.get("toolchain") then
table.insert(argv, "--toolchain=" .. config.get("toolchain"))
end
local runtimes = config.get("runtimes") or config.get("vs_runtime")
if runtimes then
table.insert(argv, "-f")
table.insert(argv, "runtimes='" .. runtimes .. "'")
end
end
-- get install configs
function _get_install_configs(argv)
-- pass jobs
if option.get("jobs") then
table.insert(argv, "-j")
table.insert(argv, option.get("jobs"))
end
-- cross compilation
if config.get("sdk") then
table.insert(argv, "--sdk=" .. config.get("sdk"))
end
-- android
if config.get("ndk") then
table.insert(argv, "--ndk=" .. config.get("ndk"))
end
if option.get("ndk_sdkver") then
table.insert(argv, "--ndk_sdkver=" .. option.get("ndk_sdkver"))
end
if option.get("android_sdk") then
table.insert(argv, "--android_sdk=" .. option.get("android_sdk"))
end
if option.get("build_toolver") then
table.insert(argv, "--build_toolver=" .. option.get("build_toolver"))
end
if option.get("ndk_stdcxx") then
table.insert(argv, "--ndk_stdcxx=" .. option.get("ndk_stdcxx"))
end
if option.get("ndk_cxxstl") then
table.insert(argv, "--ndk_cxxstl=" .. option.get("ndk_cxxstl"))
end
-- mingw
if config.get("mingw") then
table.insert(argv, "--mingw=" .. config.get("mingw"))
end
-- msvc
if config.get("vs") then
table.insert(argv, "--vs=" .. config.get("vs"))
end
if config.get("vs_toolset") then
table.insert(argv, "--vs_toolset=" .. config.get("vs_toolset"))
end
if config.get("vs_sdkver") then
table.insert(argv, "--vs_sdkver=" .. config.get("vs_sdkver"))
end
-- xcode
if config.get("xcode") then
table.insert(argv, "--xcode=" .. config.get("xcode"))
end
if config.get("xcode_sdkver") then
table.insert(argv, "--xcode_sdkver=" .. config.get("xcode_sdkver"))
end
if config.get("target_minver") then
table.insert(argv, "--target_minver=" .. config.get("target_minver"))
end
if config.get("appledev") then
table.insert(argv, "--appledev=" .. config.get("appledev"))
end
end
-- do clean
function clean()
end
-- do build
function build()
-- get xrepo
local xrepo = assert(find_tool("xrepo"), "xrepo not found!")
-- get package info
local package = assert(_g.package, "package not found!")
-- do install for building
local argv = {"install"}
_get_common_configs(argv)
_get_install_configs(argv)
table.insert(argv, "-d")
table.insert(argv, ".")
if package.version then
table.insert(argv, package.name .. " " .. package.version)
else
table.insert(argv, package.name)
end
os.vexecv(xrepo.program, argv)
-- do export
local artifacts_dir = _get_artifacts_dir()
local argv = {"export"}
_get_common_configs(argv)
table.insert(argv, "-o")
table.insert(argv, artifacts_dir)
if package.version then
table.insert(argv, package.name .. " " .. package.version)
else
table.insert(argv, package.name)
end
os.vexecv(xrepo.program, argv)
cprint("output to ${bright}%s", artifacts_dir)
cprint("${color.success}build ok!")
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/trybuild/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.platform.platform")
import("lib.detect.find_file")
import("lib.detect.find_tool")
-- translate path
function _translate_path(p)
if p and is_host("windows") and is_plat("mingw") then
p = p:gsub("\\", "/")
end
return p
end
-- translate windows bin path
function _translate_windows_bin_path(bin_path)
if bin_path then
local argv = os.argv(bin_path)
argv[1] = argv[1]:gsub("\\", "/") .. ".exe"
return os.args(argv)
end
end
-- get build directory
function _get_buildir()
return config.buildir() or "build"
end
-- get artifacts directory
function _get_artifacts_dir()
return path.absolute(path.join(_get_buildir(), "artifacts"))
end
-- get the build environment
function _get_buildenv(key)
local value = config.get(key)
if value == nil then
value = platform.toolconfig(key, config.plat())
end
if value == nil then
value = platform.tool(key, config.plat())
end
return value
end
-- get the build environments
function _get_buildenvs()
local envs = {}
local cross = false
if not is_cross() then
local cflags = table.join(table.wrap(_get_buildenv("cxflags")), _get_buildenv("cflags"))
local cxxflags = table.join(table.wrap(_get_buildenv("cxflags")), _get_buildenv("cxxflags"))
local asflags = table.copy(table.wrap(_get_buildenv("asflags")))
local ldflags = table.copy(table.wrap(_get_buildenv("ldflags")))
if is_plat("linux") and 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, ' ')
else
cross = true
local cflags = table.join(table.wrap(_get_buildenv("cxflags")), _get_buildenv("cflags"))
local cxxflags = table.join(table.wrap(_get_buildenv("cxflags")), _get_buildenv("cxxflags"))
envs.CC = _get_buildenv("cc")
envs.AS = _get_buildenv("as")
envs.AR = _get_buildenv("ar")
envs.LD = _get_buildenv("ld")
envs.LDSHARED = _get_buildenv("sh")
envs.CPP = _get_buildenv("cpp")
envs.RANLIB = _get_buildenv("ranlib")
envs.CFLAGS = table.concat(cflags, ' ')
envs.CXXFLAGS = table.concat(cxxflags, ' ')
envs.ASFLAGS = table.concat(table.wrap(_get_buildenv("asflags")), ' ')
envs.ARFLAGS = table.concat(table.wrap(_get_buildenv("arflags")), ' ')
envs.LDFLAGS = table.concat(table.wrap(_get_buildenv("ldflags")), ' ')
envs.SHFLAGS = table.concat(table.wrap(_get_buildenv("shflags")), ' ')
end
-- cross-compilation? pass the full build environments
if cross then
local ar = envs.AR
if 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
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
elseif is_plat("cross") or (ar and ar:find("ar")) then
-- only for cross-toolchain
envs.CXX = _get_buildenv("cxx")
if not envs.ARFLAGS or envs.ARFLAGS == "" then
envs.ARFLAGS = "-cr"
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 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 to use clang++ as cxx, autoconf will use it as linker
-- https://github.com/xmake-io/xmake/issues/2170
local cxx = envs.CXX
if cxx 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
end
if option.get("verbose") then
print(envs)
end
return envs
end
-- get configs
function _get_configs(artifacts_dir)
-- add prefix
local configs = {}
table.insert(configs, "--prefix=" .. _translate_path(artifacts_dir))
-- add extra user configs
local tryconfigs = config.get("tryconfigs")
if tryconfigs then
for _, opt in ipairs(os.argv(tryconfigs)) do
table.insert(configs, tostring(opt))
end
end
-- add host for cross-complation
if is_cross() then
if 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[config.arch()] or triples.arm64))
elseif 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[config.arch()] or triples["armeabi-v7a"]))
elseif is_plat("mingw") then
local triples =
{
i386 = "i686-w64-mingw32",
x86_64 = "x86_64-w64-mingw32"
}
table.insert(configs, "--host=" .. (triples[config.arch()] or triples.i386))
elseif 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[config.arch()] or triples.i386))
elseif is_plat("cross") then
local host = config.arch()
if is_arch("arm64") then
host = "aarch64"
elseif is_arch("arm.*") then
host = "arm"
end
host = host .. "-" .. (get_config("target_os") or "linux")
table.insert(configs, "--host=" .. host)
else
raise("autoconf: unknown platform(%s)!", config.plat())
end
end
return configs
end
-- detect build-system and configuration file
function detect()
if not is_subhost("windows") then
return find_file("configure", os.curdir()) or
find_file("configure.ac", os.curdir()) or
find_file("autogen.sh", os.curdir())
end
end
-- do clean
function clean()
if find_file("[mM]akefile", os.curdir()) then
if option.get("all") then
os.vexec("make distclean")
os.tryrm(_get_artifacts_dir())
else
os.vexec("make clean")
end
end
end
-- do build
function build()
-- get artifacts directory
local artifacts_dir = _get_artifacts_dir()
if not os.isdir(artifacts_dir) then
os.mkdir(artifacts_dir)
end
-- generate configure
if not os.isfile("configure") then
if os.isfile("autogen.sh") then
os.vexecv("./autogen.sh", {}, {shell = true})
elseif os.isfile("configure.ac") or os.isfile("configure.in") then
local autoreconf = find_tool("autoreconf")
assert(autoreconf, "autoreconf not found!")
os.vexecv(autoreconf.program, {"--install", "--symlink"}, {shell = true})
end
end
-- do configure
local configfile = find_file("[mM]akefile", os.curdir())
if not configfile or os.mtime(config.filepath()) > os.mtime(configfile) then
os.vexecv("./configure", _get_configs(artifacts_dir), {shell = true, envs = _get_buildenvs()})
end
-- do build
local argv = {"-j" .. option.get("jobs")}
if option.get("verbose") then
table.insert(argv, "V=1")
end
if is_host("bsd") then
os.vexecv("gmake", argv)
os.vexec("gmake install")
else
os.vexecv("make", argv)
os.vexec("make install")
end
cprint("output to ${bright}%s", artifacts_dir)
cprint("${color.success}build ok!")
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/trybuild/xcodebuild.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 xcodebuild.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("lib.detect.find_directory")
-- detect build-system and configuration file
function detect()
if is_subhost("macosx") then
return find_directory("*.xcworkspace", os.curdir()) or find_directory("*.xcodeproj", os.curdir())
end
end
-- do clean
function clean()
os.exec("xcodebuild clean CODE_SIGN_IDENTITY=\"\" CODE_SIGNING_REQUIRED=NO")
end
-- do build
function build()
-- only support the current subsystem host platform now!
assert(is_subhost(config.plat()), "xcodebuild: %s not supported!", config.plat())
-- do build
os.exec("xcodebuild build CODE_SIGN_IDENTITY=\"\" CODE_SIGNING_REQUIRED=NO")
cprint("${color.success}build ok!")
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/trybuild/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 ruki
-- @file scons.lua
--
-- imports
import("core.base.option")
import("lib.detect.find_file")
import("lib.detect.find_tool")
-- detect build-system and configuration file
function detect()
return find_file("SConstruct", os.curdir())
end
-- do clean
function clean()
local scons = assert(find_tool("scons"), "scons not found!")
os.vexecv(scons.program, {"-c"})
end
-- do build
function build()
-- only support the current subsystem host platform now!
assert(is_subhost(config.plat()), "scons: %s not supported!", config.plat())
-- do build
local scons = assert(find_tool("scons"), "scons not found!")
os.vexec(scons.program)
cprint("${color.success}build ok!")
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/build/pcheader.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 pcheader.lua
--
-- imports
import("core.language.language")
import("object")
function config(target, langkind, opt)
local pcheaderfile = target:pcheaderfile(langkind)
if pcheaderfile then
local headerfile = target:autogenfile(pcheaderfile)
if target:is_plat("windows") and
target:has_tool(langkind == "cxx" and "cxx" or "cc", "cl", "clang_cl") then
-- fix `#pragma once` for msvc
-- https://github.com/xmake-io/xmake/issues/2667
if not os.isfile(headerfile) then
io.writefile(headerfile, ([[
#pragma system_header
#ifdef __cplusplus
#include "%s"
#endif // __cplusplus
]]):format(path.absolute(pcheaderfile):gsub("\\", "/")))
end
target:pcheaderfile_set(langkind, headerfile)
end
end
end
-- add batch jobs to build the precompiled header file
function build(target, langkind, opt)
local pcheaderfile = target:pcheaderfile(langkind)
if pcheaderfile then
local sourcefile = pcheaderfile
local objectfile = target:pcoutputfile(langkind)
local dependfile = target:dependfile(objectfile)
local sourcekind = language.langkinds()[langkind]
local sourcebatch = {sourcekind = sourcekind, sourcefiles = {sourcefile}, objectfiles = {objectfile}, dependfiles = {dependfile}}
object.build(target, sourcebatch, opt)
end
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/build/object.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 object.lua
--
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.tool.compiler")
import("core.project.depend")
import("private.cache.build_cache")
import("async.runjobs")
import("utils.progress")
import("private.service.distcc_build.client", {alias = "distcc_build_client"})
-- do build file
function _do_build_file(target, sourcefile, opt)
-- get build info
local objectfile = opt.objectfile
local dependfile = opt.dependfile
local sourcekind = opt.sourcekind
-- load compiler
local compinst = compiler.load(sourcekind, {target = target})
-- get compile flags
local compflags = compinst:compflags({target = target, sourcefile = sourcefile, configs = opt.configs})
-- load dependent info
local dependinfo = target:is_rebuilt() and {} or (depend.load(dependfile, {target = target}) or {})
-- dry run?
local dryrun = option.get("dry-run")
-- need build this object?
--
-- we need use `os.mtime(dependfile)` to determine the mtime of the dependfile to avoid objectfile corruption due to compilation interruptions
-- @see https://github.com/xmake-io/xmake/issues/748
--
-- we also need avoid the problem of not being able to recompile after the objectfile has been deleted
-- @see https://github.com/xmake-io/xmake/issues/2551#issuecomment-1183922208
local depvalues = {compinst:program(), compflags}
local lastmtime = os.isfile(objectfile) and os.mtime(dependfile) or 0
if not dryrun and not depend.is_changed(dependinfo, {lastmtime = lastmtime, values = depvalues}) then
return
end
-- is verbose?
local verbose = option.get("verbose")
-- exists ccache or distcc?
-- we just show cache/distc to avoid confusion with third-party ccache/distcc
local prefix = ""
if build_cache.is_enabled(target) and build_cache.is_supported(sourcekind) then
prefix = "cache "
end
if distcc_build_client.is_distccjob() and distcc_build_client.singleton():has_freejobs() then
prefix = prefix .. "distc "
end
-- trace progress info
if not opt.quiet then
progress.show(opt.progress, "${color.build.object}%scompiling.$(mode) %s", prefix, sourcefile)
end
-- trace verbose info
if verbose then
-- show the full link command with raw arguments, it will expand @xxx.args for msvc/link on windows
print(compinst:compcmd(sourcefile, objectfile, {compflags = compflags, rawargs = true}))
end
if not dryrun then
-- do compile
dependinfo.files = {}
assert(compinst:compile(sourcefile, objectfile, {dependinfo = dependinfo, compflags = compflags}))
-- update files and values to the depfiles
dependinfo.values = depvalues
table.insert(dependinfo.files, sourcefile)
-- add precompiled header to the depfiles when building sourcefile
local build_pch
local pcxxoutputfile = target:pcoutputfile("cxx")
local pcoutputfile = target:pcoutputfile("c")
if pcxxoutputfile or pcoutputfile then
-- https://github.com/xmake-io/xmake/issues/3988
local extension = path.extension(sourcefile)
if (extension:startswith(".h") or extension == ".inl") then
build_pch = true
end
end
if target:has_sourcekind("cxx") and pcxxoutputfile and not build_pch then
table.insert(dependinfo.files, pcxxoutputfile)
end
if target:has_sourcekind("cc") and pcoutputfile and not build_pch then
table.insert(dependinfo.files, pcoutputfile)
end
depend.save(dependinfo, dependfile)
end
end
-- build object
function build_object(target, sourcefile, opt)
local script = target:script("build_file", _do_build_file)
if script then
script(target, sourcefile, opt)
end
end
-- build the source files
function build(target, sourcebatch, opt)
for i = 1, #sourcebatch.sourcefiles do
local sourcefile = sourcebatch.sourcefiles[i]
opt.objectfile = sourcebatch.objectfiles[i]
opt.dependfile = sourcebatch.dependfiles[i]
opt.sourcekind = assert(sourcebatch.sourcekind, "%s: sourcekind not found!", sourcefile)
build_object(target, sourcefile, opt)
end
end
-- add batch jobs to build the source files
function main(target, batchjobs, sourcebatch, opt)
local rootjob = opt.rootjob
for i = 1, #sourcebatch.sourcefiles do
local sourcefile = sourcebatch.sourcefiles[i]
local objectfile = sourcebatch.objectfiles[i]
local dependfile = sourcebatch.dependfiles[i]
local sourcekind = assert(sourcebatch.sourcekind, "%s: sourcekind not found!", sourcefile)
batchjobs:addjob(sourcefile, function (index, total, jobopt)
local build_opt = table.join({objectfile = objectfile, dependfile = dependfile, sourcekind = sourcekind, progress = jobopt.progress}, opt)
build_object(target, sourcefile, build_opt)
end, {rootjob = rootjob, distcc = opt.distcc})
end
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/update/fetch_version.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, ruki
-- @file fetch_version.lua
--
-- imports
import("core.base.semver")
import("core.base.option")
import("core.base.task")
import("net.http")
import("devel.git")
import("net.fasturl")
-- the official git sources for xmake
local official_sources =
{
"https://github.com/xmake-io/xmake.git",
"[email protected]:xmake-io/xmake.git",
"https://gitlab.com/tboox/xmake.git",
"https://gitee.com/tboox/xmake.git"
}
-- get version and url of provided xmakever
function main(xmakever)
-- init xmakever
xmakever = xmakever or "latest"
-- parse url and commit
local commitish = nil
local custom_url = nil
local seg = xmakever:split('#', { plain = true, limit = 2, strict = true })
if #seg == 2 then
if #seg[1] ~= 0 then
custom_url = seg[1]
end
commitish = seg[2]
else
if xmakever:find(':', 1, true) then
custom_url = xmakever
else
commitish = xmakever
end
end
local urls = nil
if custom_url then
urls = { git.asgiturl(custom_url) or custom_url }
vprint("using custom source: %s ..", urls[1] )
else
urls = official_sources
end
commitish = (commitish and #commitish > 0) and commitish or "latest"
-- sort urls
if #urls > 1 then
fasturl.add(urls)
urls = fasturl.sort(urls)
end
-- get version
local version = nil
local tags, branches
for _, url in ipairs(urls) do
tags, branches = git.refs(url)
if tags or branches then
version = semver.select(commitish, tags or {}, tags or {}, branches or {})
break
end
end
return {is_official = (urls == official_sources), urls = urls, version = (version or "master"), tags = tags, branches = branches}
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/run/runenvs.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, OpportunityLiu, SirLynix
-- @file runenvs.lua
--
-- imports
import("core.base.hashset")
-- add search directories for all dependent shared libraries on windows
function _make_runpath_on_windows(target)
local pathenv = {}
local searchdirs = hashset.new()
local function insert(dir)
if not path.is_absolute(dir) then
dir = path.absolute(dir, os.projectdir())
end
if searchdirs:insert(dir) then
table.insert(pathenv, dir)
end
end
-- recursively add targets and dep targets linkdirs
local seentargets = hashset.new()
local function insert_target(target)
if seentargets:insert(target) then
for _, linkdir in ipairs(target:get("linkdirs")) do
insert(linkdir)
end
for _, opt in ipairs(target:orderopts()) do
for _, linkdir in ipairs(opt:get("linkdirs")) do
insert(linkdir)
end
end
for _, pkg in ipairs(target:orderpkgs()) do
for _, linkdir in ipairs(pkg:get("linkdirs")) do
insert(linkdir)
end
end
for _, dep in ipairs(target:orderdeps()) do
if dep:kind() == "shared" then
insert(dep:targetdir())
end
insert_target(dep)
end
for _, toolchain in ipairs(target:toolchains()) do
local runenvs = toolchain:runenvs()
if runenvs and runenvs.PATH then
for _, env in ipairs(path.splitenv(runenvs.PATH)) do
insert(env)
end
end
end
end
end
insert_target(target)
return pathenv
end
-- flatten envs ({PATH = {"A", "B"}} => {PATH = "A;B"})
function _flatten_envs(envs)
local flatten_envs = {}
for name, values in pairs(envs) do
flatten_envs[name] = path.joinenv(values)
end
return flatten_envs
end
-- join addenvs and setenvs in a common envs table
function join(addenvs, setenvs)
local envs = os.joinenvs(addenvs and _flatten_envs(addenvs) or {})
if setenvs then
envs = os.joinenvs(envs, _flatten_envs(setenvs))
end
return envs
end
-- recursively add package envs
function _add_target_pkgenvs(addenvs, target, targets_added)
if targets_added[target:name()] then
return
end
targets_added[target:name()] = true
local pkgenvs = target:pkgenvs()
if pkgenvs then
for name, values in pairs(pkgenvs) do
values = path.splitenv(values)
local oldenvs = addenvs[name]
if oldenvs then
table.join2(oldenvs, values)
else
addenvs[name] = values
end
end
end
for _, dep in ipairs(target:orderdeps()) do
_add_target_pkgenvs(addenvs, dep, targets_added)
end
end
-- deduplicate envs
-- @see https://github.com/xmake-io/xmake/issues/5184
function _dedup_envs(envs)
local envs_new = {}
for k, v in pairs(envs) do
if type(v) == "table" then
envs_new[k] = table.unique(v)
else
envs_new[k] = v
end
end
return envs_new
end
function make(target)
-- add run environments
local setenvs = {}
local addenvs = {}
local runenvs = target:get("runenvs")
if runenvs then
for name, values in pairs(runenvs) do
addenvs[name] = table.wrap(values)
end
end
local runenv = target:get("runenv")
if runenv then
for name, value in pairs(runenv) do
setenvs[name] = table.wrap(value)
if addenvs[name] then
utils.warning(format("both add_runenvs and set_runenv called on environment variable \"%s\", the former one will be ignored.", name))
addenvs[name] = nil
end
end
end
-- add package run environments
_add_target_pkgenvs(addenvs, target, {})
-- add search directories for all dependent shared libraries on windows
if target:is_plat("windows") or (target:is_plat("mingw") and is_host("windows")) then
local pathenv = addenvs["PATH"] or setenvs["PATH"]
local runpath = _make_runpath_on_windows(target)
if pathenv == nil then
addenvs["PATH"] = runpath
else
table.join2(pathenv, runpath)
end
end
-- deduplicate envs
if addenvs then
addenvs = _dedup_envs(addenvs)
end
if setenvs then
setenvs = _dedup_envs(setenvs)
end
return addenvs, setenvs
end
|
0 | repos/xmake/xmake/modules/private/action | repos/xmake/xmake/modules/private/action/clean/remove_files.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 remove_files.lua
--
-- imports
import("core.base.option")
-- remove the given files or (empty) directories
function main(filedirs, opt)
opt = opt or {}
for _, filedir in ipairs(filedirs) do
-- os.exists will return false if symlink -> not found, but we need still remove this symlink
if os.exists(filedir) or os.islink(filedir) then
-- we cannot use os.tryrm, because we need raise exception if remove failed with `uninstall --admin`
os.rm(filedir, {emptydirs = option.get("all") or opt.emptydir})
end
end
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/xrepo/complete.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 glcraft
-- @file complete.lua
--
import("private.utils.completer")
function main(pos, config, ...)
local comp = completer.new(pos, config, {...})
local word = table.concat(comp:words(), " ") or ""
position = tonumber(pos) or 0
local has_space = word:endswith(" ") or position > #word
word = word:trim()
local argv = os.argv(word)
if argv[1] then
-- normailize word to remove "xrepo"
if is_host("windows") and argv[1]:lower() == "xrepo.exe" then
argv[1] = "xrepo"
end
if argv[1] == "xrepo" then
table.remove(argv, 1)
end
end
local items = {}
for _, scriptfile in ipairs(os.files(path.join(os.scriptdir(), "action", "*.lua"))) do
local action_name = path.basename(scriptfile)
local action = import("private.xrepo.action." .. action_name, {anonymous = true})
local options, _, description = action.menu_options()
items[action_name] = {
description = description,
options = options,
}
end
if has_space then
comp:complete(items, argv, "")
else
local completing = table.remove(argv)
comp:complete(items, argv, completing or "")
end
end |
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/xrepo/main.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 main.lua
--
-- imports
import("core.base.text")
import("core.base.option")
-- show version
function _show_version()
-- show title
cprint("${bright}xRepo %s/xmake, A cross-platform C/C++ package manager based on Xmake.", xmake.version())
-- show copyright
cprint("Copyright (C) 2015-present Ruki Wang, ${underline}tboox.org${clear}, ${underline}xmake.io${clear}")
print("")
-- show logo
local logo = [[
__ ___ ___ ______ ____ _____
\ \/ / | _ \| ____| _ \/ _ |
> < | |_) | _| | |_) | |_| |
/_/\_\_| \___|_____|_| |____/
by ruki, xmake.io
]]
option.show_logo(logo, {seed = 680})
end
-- get main menu options
function _menu_options()
-- main menu options
local options = {}
-- show menu in narrow mode?
local function menu_isnarrow()
local width = os.getwinsize().width
return width > 0 and width < 60
end
-- show all actions
local function show_actions()
print("")
cprint("${bright}Actions:")
-- get action names
local repo_actions = {}
local package_actions = {}
for _, scriptfile in ipairs(os.files(path.join(os.scriptdir(), "action", "*.lua"))) do
local action_name = path.basename(scriptfile)
if action_name:endswith("-repo") then
table.insert(repo_actions, action_name)
else
table.insert(package_actions, action_name)
end
end
table.sort(repo_actions)
table.sort(package_actions)
-- make action content
local tablecontent = {}
local narrow = menu_isnarrow()
for _, action_name in ipairs(table.join(package_actions, repo_actions)) do
local action = import("private.xrepo.action." .. action_name, {anonymous = true})
local _, _, description = action.menu_options()
local taskline = string.format(narrow and " %s" or " %s", action_name)
table.insert(tablecontent, {taskline, description})
end
-- set table styles
tablecontent.style = {"${color.menu.main.task.name}"}
tablecontent.width = {nil, "auto"}
tablecontent.sep = narrow and " " or " "
-- print table
io.write(text.table(tablecontent))
end
-- show options of main program
local function show_options()
-- show usage
cprint("${bright}Usage: $${clear cyan}xrepo [action] [options]")
-- show actions
show_actions()
-- show options
option.show_options(options, "main")
end
return options, show_options
end
-- parse options
function _parse_options(...)
-- get action and arguments
local argv = table.pack(...)
local action_name = nil
if #argv > 0 and not argv[1]:startswith('-') then
action_name = argv[1]
argv = table.slice(argv, 2)
end
-- get menu
local action, options, show_options
if action_name then
action = assert(import("private.xrepo.action." .. action_name, {anonymous = true, try = true}), "xrepo: action %s not found!", action_name)
options, show_options = action.menu_options()
else
options, show_options = _menu_options()
end
-- insert common options
local common_options =
{
{'q', "quiet", "k", nil, "Quiet operation." },
{'y', "yes", "k", nil, "Input yes by default if need user confirm." },
{nil, "root", "k", nil, "Allow to run xrepo as root." },
{},
{'v', "verbose", "k", nil, "Print lots of verbose information for users."},
{'D', "diagnosis", "k", nil, "Print lots of diagnosis information." },
{nil, "version", "k", nil, "Print the version number and exit." },
{'h', "help", "k", nil, "Print this help message and exit." },
{category = action and "action" or nil},
}
for _, opt in irpairs(common_options) do
table.insert(options, 1, opt)
end
-- parse argument options
local menu = {}
local results, errors = option.raw_parse(argv, options)
if results then
menu.options = results
end
menu.action = action
menu.action_name = action_name
menu.show_help = function ()
_show_version()
show_options()
end
return menu, errors
end
-- main entry
function main(...)
-- parse argument options
local menu, errors = _parse_options(...)
if errors then
menu.show_help()
raise(errors)
end
-- show help?
local options = menu.options
if not options or options.help then
return menu.show_help()
end
-- show version?
if options.version then
return _show_version()
end
-- init option
option.save()
for k, v in pairs(options) do
option.set(k, v)
end
-- tell xmake that xrepo is currently being used
os.setenv("XREPO_WORKING", "y")
-- do action
if menu.action then
menu.action()
else
menu.show_help()
end
end
|
0 | repos/xmake/xmake/modules/private/xrepo | repos/xmake/xmake/modules/private/xrepo/quick_search/cache.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 glcraft
-- @file cache.lua
--
import("core.base.json")
import("core.cache.globalcache")
import("core.package.package", {alias = "core_package"})
import("private.action.require.impl.repository")
local cache = globalcache.cache("quick_search")
-- search package directories from repositories
function _list_package_dirs()
-- find the package directories from all repositories
local unique = {}
local packageinfos = {}
for _, repo in ipairs(repository.repositories()) do
for _, file in ipairs(os.files(path.join(repo:directory(), "packages", "*", "*", "xmake.lua"))) do
local dir = path.directory(file)
local subdirname = path.basename(path.directory(dir))
if #subdirname == 1 then -- ignore l/luajit/port/xmake.lua
local packagename = path.filename(dir)
if not unique[packagename] then
table.insert(packageinfos, {name = packagename, repo = repo, packagedir = path.directory(file)})
unique[packagename] = true
end
end
end
end
return packageinfos
end
-- check cache content exists
function _init()
if table.empty(cache:data()) then
update()
end
end
-- update the cache file
function update()
for _, packageinfo in ipairs(_list_package_dirs()) do
local package = core_package.load_from_repository(packageinfo.name, packageinfo.packagedir, {repo = packageinfo.repo})
cache:set(packageinfo.name, {
description = package:description(),
versions = package:versions(),
})
end
cache:save()
end
-- remove the cache file
function clear()
cache:clear()
cache:save()
end
-- get the cache data
function get()
_init()
return cache:data()
end
function find(name)
_init()
local list_result = {}
for packagename, packagedata in pairs(cache:data()) do
if packagename:startswith(name) then
table.insert(list_result, {name = packagename, data = packagedata})
end
end
return list_result
end
|
0 | repos/xmake/xmake/modules/private/xrepo | repos/xmake/xmake/modules/private/xrepo/quick_search/completion.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 glcraft
-- @file complete.lua
--
import("private.xrepo.quick_search.cache")
-- complete xrepo packages
function _xmake_package_complete(complete, opt)
local candidates = {}
local found = cache.find(complete)
for _, candidate in ipairs(found) do
table.insert(candidates, {value = candidate.name, description = candidate.data.description})
end
return candidates
end
function main(complete, opt)
local prefix = ""
-- if help menu, do nothing
if opt.helpmenu then
return {}
end
-- check prefix if present
if complete:find("::", 1, true) then
prefix = complete:sub(1, complete:find("::", 1, true) - 1)
complete = complete:sub(complete:find("::", 1, true) + 2)
end
local packages
-- complete xmake packages
if prefix == "" or prefix == "xmake" then
packages = _xmake_package_complete(complete, opt)
end
-- to prevent shell completion misunderstandings,
-- we put back the prefix
if packages and prefix ~= "" then
for _, package in ipairs(packages) do
package.value = prefix .. "::" .. package.value
end
end
return packages or {}
end |
0 | repos/xmake/xmake/modules/private/xrepo | repos/xmake/xmake/modules/private/xrepo/action/export.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 export.lua
--
-- imports
import("core.base.option")
import("core.base.task")
-- get menu options
function menu_options()
-- description
local description = "Export the given packages."
-- menu options
local options =
{
{'k', "kind", "kv", nil, "Enable static/shared library.",
values = {"static", "shared"} },
{'p', "plat", "kv", nil, "Set the given platform." },
{'a', "arch", "kv", nil, "Set the given architecture." },
{'m', "mode", "kv", nil, "Set the given mode.",
values = {"release", "debug"} },
{'f', "configs", "kv", nil, "Set the given extra package configs.",
"e.g.",
" - xrepo export -f \"runtimes='MD'\" zlib",
" - xrepo export -f \"regex=true,thread=true\" boost"},
{},
{nil, "includes", "kv", nil, "Includes extra lua configuration files."},
{nil, "toolchain", "kv", nil, "Set the toolchain name." },
{nil, "shallow", "k", nil, "Does not export dependent packages."},
{'o', "packagedir", "kv", "packages","Set the exported packages directory."},
{nil, "packages", "vs", nil, "The packages list.",
"e.g.",
" - xrepo export zlib boost",
" - xrepo export -p iphoneos -a arm64 \"zlib >=1.2.0\"",
" - xrepo export -p android -m debug \"pcre2 10.x\"",
" - xrepo export -p mingw -k shared zlib",
" - xrepo export conan::zlib/1.2.11 vcpkg::zlib"}
}
-- show menu options
local function show_options()
-- show usage
cprint("${bright}Usage: $${clear cyan}xrepo export [options] packages")
-- show description
print("")
print(description)
-- show options
option.show_options(options, "export")
end
return options, show_options, description
end
-- export packages
function _export_packages(packages)
-- is package configuration file? e.g. xrepo export xxx.lua
--
-- xxx.lua
-- add_requires("libpng", {system = false})
-- add_requireconfs("libpng.*", {configs = {shared = true}})
local packagefile
if type(packages) == "string" or #packages == 1 then
local filepath = table.unwrap(packages)
if type(filepath) == "string" and filepath:endswith(".lua") and os.isfile(filepath) then
packagefile = path.absolute(filepath)
end
end
-- add includes to rcfiles
local rcfiles = {}
local includes = option.get("includes")
if includes then
table.join2(rcfiles, path.splitenv(includes))
end
-- enter working project directory
local oldir = os.curdir()
local subdir = "working"
if packagefile then
subdir = subdir .. "-" .. hash.uuid(packagefile):split('-')[1]
end
local workdir = path.join(os.tmpdir(), "xrepo", subdir)
if not os.isdir(workdir) then
os.mkdir(workdir)
os.cd(workdir)
os.vrunv(os.programfile(), {"create", "-P", "."})
else
os.cd(workdir)
end
if packagefile then
assert(os.isfile("xmake.lua"), "xmake.lua not found!")
io.writefile("xmake.lua", ('includes("%s")\ntarget("test", {kind = "phony"})'):format((packagefile:gsub("\\", "/"))))
end
-- do configure first
local config_argv = {"f", "-c", "--require=n"}
if option.get("diagnosis") then
table.insert(config_argv, "-vD")
end
if option.get("plat") then
table.insert(config_argv, "-p")
table.insert(config_argv, option.get("plat"))
end
if option.get("arch") then
table.insert(config_argv, "-a")
table.insert(config_argv, option.get("arch"))
end
if option.get("toolchain") then
table.insert(config_argv, "--toolchain=" .. option.get("toolchain"))
end
local mode = option.get("mode")
if mode then
table.insert(config_argv, "-m")
table.insert(config_argv, mode)
end
local kind = option.get("kind")
if kind then
table.insert(config_argv, "-k")
table.insert(config_argv, kind)
end
local envs = {}
if #rcfiles > 0 then
envs.XMAKE_RCFILES = path.joinenv(rcfiles)
end
os.vrunv(os.programfile(), config_argv, {envs = envs})
-- do export
local require_argv = {"require", "--export"}
if option.get("yes") then
table.insert(require_argv, "-y")
end
if option.get("verbose") then
table.insert(require_argv, "-v")
end
if option.get("diagnosis") then
table.insert(require_argv, "-D")
end
if option.get("shallow") then
table.insert(require_argv, "--shallow")
end
local packagedir = option.get("packagedir")
if packagedir and not path.is_absolute(packagedir) then
packagedir = path.absolute(packagedir, oldir)
end
if packagedir then
table.insert(require_argv, "--packagedir=" .. packagedir)
end
local extra = {system = false}
if mode == "debug" then
extra.debug = true
end
if kind then
extra.configs = extra.configs or {}
extra.configs.shared = kind == "shared"
end
local configs = option.get("configs")
if configs then
extra.configs = extra.configs or {}
local extra_configs, errors = ("{" .. configs .. "}"):deserialize()
if extra_configs then
table.join2(extra.configs, extra_configs)
else
raise(errors)
end
end
if not packagefile then
if extra then
local extra_str = string.serialize(extra, {indent = false, strip = true})
table.insert(require_argv, "--extra=" .. extra_str)
end
table.join2(require_argv, packages)
end
os.vexecv(os.programfile(), require_argv, {envs = envs})
end
-- export packages in current project
function _export_current_packages(packages)
-- do export
local require_argv = {export = true}
if option.get("yes") then
require_argv.yes = true
end
if option.get("verbose") then
require_argv.verbose = true
end
if option.get("diagnosis") then
require_argv.diagnosis = true
end
local packagedir = option.get("packagedir")
if packagedir and not path.is_absolute(packagedir) then
packagedir = path.absolute(packagedir, oldir)
end
if packagedir then
require_argv.packagedir = packagedir
end
local extra = {system = false}
local mode = option.get("mode")
if mode == "debug" then
extra.debug = true
end
local kind = option.get("kind")
if kind then
extra.configs = extra.configs or {}
extra.configs.shared = kind == "shared"
end
local configs = option.get("configs")
if configs then
extra.configs = extra.configs or {}
local extra_configs, errors = ("{" .. configs .. "}"):deserialize()
if extra_configs then
table.join2(extra.configs, extra_configs)
else
raise(errors)
end
end
if extra then
local extra_str = string.serialize(extra, {indent = false, strip = true})
require_argv.extra = extra_str
end
task.run("require", require_argv)
end
-- main entry
function main()
local packages = option.get("packages")
if packages then
_export_packages(packages)
elseif os.isfile(os.projectfile()) then
_export_current_packages()
else
raise("please specify the packages to be exported.")
end
end
|
0 | repos/xmake/xmake/modules/private/xrepo | repos/xmake/xmake/modules/private/xrepo/action/search.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.lua
--
-- imports
import("core.base.option")
-- get menu options
function menu_options()
-- description
local description = "Search the given packages."
-- menu options
local options =
{
{nil, "packages", "vs", nil, "The packages list (support lua pattern).",
"e.g.",
" - xrepo search zlib boost",
" - xrepo search \"pcre*\""}
}
-- show menu options
local function show_options()
-- show usage
cprint("${bright}Usage: $${clear cyan}xrepo search [options] packages")
-- show description
print("")
print(description)
-- show options
option.show_options(options, "search")
end
return options, show_options, description
end
-- search packages
function _search_packages(packages)
-- enter working project directory
local workdir = path.join(os.tmpdir(), "xrepo", "working")
if not os.isdir(workdir) then
os.mkdir(workdir)
os.cd(workdir)
os.vrunv(os.programfile(), {"create", "-P", "."})
else
os.cd(workdir)
end
-- do configure first
local config_argv = {"f", "-c"}
if option.get("diagnosis") then
table.insert(config_argv, "-vD")
end
os.vrunv(os.programfile(), config_argv)
-- do search
local require_argv = {"require", "--search"}
if option.get("verbose") then
table.insert(require_argv, "-v")
end
if option.get("diagnosis") then
table.insert(require_argv, "-D")
end
table.join2(require_argv, packages)
os.vexecv(os.programfile(), require_argv)
end
-- main entry
function main()
local packages = option.get("packages")
if packages then
_search_packages(packages)
else
raise("please specify the package to be searched.")
end
end
|
0 | repos/xmake/xmake/modules/private/xrepo | repos/xmake/xmake/modules/private/xrepo/action/env.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 env.lua
--
-- imports
import("core.base.option")
import("core.base.task")
import("core.base.hashset")
import("core.base.global")
import("core.project.config")
import("core.project.project")
import("core.tool.toolchain")
import("lib.detect.find_tool")
import("private.action.run.runenvs")
import("private.action.require.impl.package")
import("private.action.require.impl.utils.get_requires")
-- get menu options
function menu_options()
-- description
local description = "Set environment and execute command, or print environment."
-- menu options
local options =
{
{'k', "kind", "kv", nil, "Enable static/shared library.",
values = {"static", "shared"} },
{'p', "plat", "kv", nil, "Set the given platform." },
{'a', "arch", "kv", nil, "Set the given architecture." },
{'m', "mode", "kv", nil, "Set the given mode.",
values = {"release", "debug"} },
{nil, "show", "k", nil, "Only show environment information." },
{'f', "configs", "kv", nil, "Set the given extra package configs.",
"e.g.",
" - xrepo env -f \"runtimes='MD'\" zlib cmake ..",
" - xrepo env -f \"regex=true,thread=true\" \"zlib,boost\" cmake .."},
{nil, "add", "k", nil, "Add global environment config.",
"e.g.",
" - xrepo env --add base.lua",
" - xrepo env --add myenv.lua"},
{nil, "remove", "k", nil, "Remove global environment config.",
"e.g.",
" - xrepo env --remove base",
" - xrepo env --remove myenv"},
{"l", "list", "k", nil, "List all global environment configs.",
"e.g.",
" - xrepo env --list"},
{'b', "bind", "kv", nil, "Bind the specified environment or package.",
"e.g.",
" - xrepo env -b base shell",
" - xrepo env -b myenv shell",
" - xrepo env -b \"python 3.x\" shell",
" - xrepo env -b \"cmake,ninja,python 3.x\" shell",
" - xrepo env -b \"luajit 2.x\" luajit xx.lua"},
{},
{nil, "program", "v", nil, "Set the program name to be run.",
"e.g.",
" - xrepo env",
" - xrepo env bash",
" - xrepo env shell (it will load bash/sh/cmd automatically)",
" - xrepo env python",
" - xrepo env luajit xx.lua"},
{nil, "arguments", "vs", nil, "Set the program arguments to be run"}
}
-- show menu options
local function show_options()
-- show usage
cprint("${bright}Usage: $${clear cyan}xrepo env [options] [program] [arguments]")
-- show description
print("")
print(description)
-- show options
option.show_options(options, "env")
end
return options, show_options, description
end
-- enter the working project
function _enter_project()
local workdir = path.join(os.tmpdir(), "xrepo", "working")
if not os.isdir(workdir) then
os.mkdir(workdir)
os.cd(workdir)
os.vrunv(os.programfile(), {"create", "-P", "."})
else
os.cd(workdir)
os.rm("*")
os.vrunv(os.programfile(), {"create", "-P", "."})
end
project.chdir(workdir)
end
-- remove repeat environment values
function _deduplicate_pathenv(value)
if value then
local itemset = {}
local results = {}
for _, item in ipairs(path.splitenv(value)) do
if not itemset[item] then
table.insert(results, item)
itemset[item] = true
end
end
if #results > 0 then
value = path.joinenv(results)
end
end
return value
end
-- get environment directory
function _get_envsdir()
return path.join(global.directory(), "envs")
end
-- get builtin environment directory
function _get_envsdir_builtin()
return path.join(os.programdir(), "scripts", "xrepo", "envs")
end
-- get bound environment or packages
function _get_boundenv(opt)
local bind = (opt and opt.bind) or option.get("bind")
if bind then
for _, envsdir in ipairs({_get_envsdir(), _get_envsdir_builtin()}) do
local envfile = path.join(envsdir, bind .. ".lua")
if envfile and os.isfile(envfile) then
return envfile
end
end
end
return bind
end
-- add values to environment variable
function _addenvs(envs, name, ...)
local values = {...}
if #values > 0 then
local oldenv = envs[name]
local appendenv = path.joinenv(values)
if oldenv == "" or oldenv == nil then
envs[name] = appendenv
else
envs[name] = appendenv .. path.envsep() .. oldenv
end
end
end
-- add package environments
function _package_addenvs(envs, instance)
-- only for xmake::package
if instance:is_system() then
return
end
-- add run envs, e.g. PATH, LD_LIBRARY_PATH, DYLD_LIBRARY_PATH
local installdir = instance:installdir()
for name, values in pairs(instance:envs()) do
_addenvs(envs, name, table.unpack(table.wrap(values)))
end
-- add library envs, e.g. ACLOCAL_PATH, PKG_CONFIG_PATH, CMAKE_PREFIX_PATH
if instance:is_library() then
local pkgconfig = path.join(installdir, "lib", "pkgconfig")
if os.isdir(pkgconfig) then
_addenvs(envs, "PKG_CONFIG_PATH", pkgconfig)
end
pkgconfig = path.join(installdir, "share", "pkgconfig")
if os.isdir(pkgconfig) then
_addenvs(envs, "PKG_CONFIG_PATH", pkgconfig)
end
local aclocal = path.join(installdir, "share", "aclocal")
if os.isdir(aclocal) then
_addenvs(envs, "ACLOCAL_PATH", aclocal)
end
_addenvs(envs, "CMAKE_PREFIX_PATH", installdir)
if instance:is_plat("windows") then
_addenvs(envs, "INCLUDE", path.join(installdir, "include"))
_addenvs(envs, "LIBPATH", path.join(installdir, "lib"))
else
_addenvs(envs, "CPATH", path.join(installdir, "include"))
_addenvs(envs, "LIBRARY_PATH", path.join(installdir, "lib"))
end
end
end
-- add toolchain environments
function _toolchain_addenvs(envs)
for _, name in ipairs(project.get("target.toolchains")) do
local toolchain_opt = project.extraconf("target.toolchains", name)
local toolchain_inst = toolchain.load(name, toolchain_opt)
if toolchain_inst then
for k, v in pairs(toolchain_inst:runenvs()) do
_addenvs(envs, k, table.unpack(path.splitenv(v)))
end
end
end
end
-- add target environments
function _target_addenvs(envs)
for _, target in ipairs(project.ordertargets()) do
if target:is_binary() then
_addenvs(envs, "PATH", target:targetdir())
elseif target:is_shared() then
if is_host("windows") then
_addenvs(envs, "PATH", target:targetdir())
elseif is_host("macosx") then
_addenvs(envs, "DYLD_LIBRARY_PATH", target:targetdir())
else
_addenvs(envs, "LD_LIBRARY_PATH", target:targetdir())
end
end
-- add run environments
local addrunenvs = runenvs.make(target)
for name, values in pairs(addrunenvs) do
_addenvs(envs, name, table.unpack(table.wrap(values)))
end
end
end
-- get package environments
function _package_getenvs(opt)
local envs = os.getenvs()
local boundenv = _get_boundenv(opt)
local has_envfile = false
local packages = nil
if boundenv and os.isfile(boundenv) then
has_envfile = true
else
packages = boundenv or option.get("program")
end
local oldir = os.curdir()
if (os.isfile(os.projectfile()) and not boundenv) or has_envfile then
if has_envfile then
_enter_project()
table.insert(project.rcfiles(), boundenv)
end
task.run("config", {}, {disable_dump = true})
_toolchain_addenvs(envs)
local requires, requires_extra = get_requires()
for _, instance in ipairs(package.load_packages(requires, {requires_extra = requires_extra})) do
_package_addenvs(envs, instance)
end
if not has_envfile then
_target_addenvs(envs)
end
elseif packages then
_enter_project()
local envfile = os.tmpfile() .. ".lua"
packages = packages:split(',', {plain = true})
local file = io.open(envfile, "w")
for _, requirename in ipairs(packages) do
file:print("add_requires(\"%s\")", requirename)
end
file:close()
table.insert(project.rcfiles(), envfile)
task.run("config", {}, {disable_dump = true})
local requires, requires_extra = get_requires()
for _, instance in ipairs(package.load_packages(requires, {requires_extra = requires_extra})) do
_package_addenvs(envs, instance)
end
end
local results = {}
for k, v in pairs(envs) do
results[k] = _deduplicate_pathenv(v)
end
os.cd(oldir)
return results
end
-- get environment setting script
function _get_env_script(envs, shell, del)
local prefix = ""
local connector = "="
local suffix = ""
local default = ""
if shell == "powershell" or shell == "pwsh" then
prefix = "[Environment]::SetEnvironmentVariable('"
connector = "','"
suffix = "')"
default = "$Null"
elseif shell == "cmd" then
prefix = "@set \""
suffix = "\""
elseif shell:endswith("sh") then
if del then
prefix = "unset '"
connector = "'"
else
prefix = "export '"
connector = "'='"
suffix = "'"
end
end
local exceptions = hashset.of("_", "PS1", "PROMPT", "!;", "!EXITCODE")
local ret = ""
if del then
for name, _ in pairs(envs) do
if not exceptions:has(name) then
ret = ret .. prefix .. name .. connector .. default .. suffix .. "\n"
end
end
else
for name, value in pairs(envs) do
if not exceptions:has(name) then
ret = ret .. prefix .. name .. connector .. value .. suffix .. "\n"
end
end
end
return ret
end
-- get prompt
function _get_prompt(bnd)
bnd = bnd or option.get("bind")
local prompt
local boundenv = _get_boundenv({bind = bnd})
if boundenv then
if os.isfile(boundenv) then
prompt = path.basename(boundenv)
else
prompt = boundenv:sub(1, math.min(#boundenv, 16))
if boundenv ~= prompt then
prompt = prompt .. ".."
end
end
prompt = "[" .. prompt .. "]"
elseif not bnd then
assert(os.isfile(os.projectfile()), "xmake.lua not found!")
prompt = path.filename(os.projectdir())
prompt = "[" .. prompt .. "]"
end
return prompt or ""
end
-- get information of current virtual environment
function info(key, bnd)
if key == "prompt" then
local prompt = _get_prompt(bnd)
io.write(prompt)
elseif key == "envfile" then
print(os.tmpfile())
elseif key == "config" then
_package_getenvs({bind = bnd})
elseif key:startswith("script.") then
local shell = key:match("script%.(.+)")
io.write(_get_env_script(_package_getenvs({bind = bnd}), shell, false))
elseif key:startswith("backup.") then
local shell = key:match("backup%.(.+)")
-- remove current environment variables first
io.write(_get_env_script(_package_getenvs({bind = bnd}), shell, true))
io.write(_get_env_script(os.getenvs(), shell, false))
end
end
-- run shell
function _run_shell(envs)
local shell = os.shell()
if shell == "pwsh" or shell == "powershell" then
os.execv("pwsh", option.get("arguments"), {envs = envs})
elseif shell:endswith("sh") then
local prompt = _get_prompt()
local ps1 = os.getenv("PS1")
if ps1 then
prompt = prompt .. ps1
elseif is_host("macosx") then
prompt = prompt .. " \\W > "
else
prompt = prompt .. " > "
end
os.execv(shell, option.get("arguments"), {envs = table.join({PS1 = prompt}, envs)})
elseif shell == "cmd" or is_host("windows") then
local prompt = _get_prompt()
prompt = prompt .. " $P$G"
local args = table.join({"/k", "set PROMPT=" .. prompt}, option.get("arguments"))
os.execv("cmd", args, {envs = envs})
else
assert("shell not found!")
end
end
function main()
if option.get("list") then
local envname = option.get("program")
if envname then
for _, envsdir in ipairs({_get_envsdir(), _get_envsdir_builtin()}) do
local envfile = path.join(envsdir, envname .. ".lua")
if os.isfile(envfile) then
print("%s:", envfile)
io.cat(envfile)
end
end
else
print("%s (builtin):", _get_envsdir_builtin())
local count = 0
for _, envfile in ipairs(os.files(path.join(_get_envsdir_builtin(), "*.lua"))) do
local envname = path.basename(envfile)
print(" - %s", envname)
count = count + 1
end
print("%s:", _get_envsdir())
for _, envfile in ipairs(os.files(path.join(_get_envsdir(), "*.lua"))) do
local envname = path.basename(envfile)
print(" - %s", envname)
count = count + 1
end
print("envs(%d) found!", count)
end
elseif option.get("add") then
local envfile = assert(option.get("program"), "please set environment config file!")
if os.isfile(envfile) then
os.vcp(envfile, path.join(_get_envsdir(), path.filename(envfile)))
end
elseif option.get("remove") then
local envname = assert(option.get("program"), "please set environment config name!")
os.rm(path.join(_get_envsdir(), envname .. ".lua"))
else
local program = option.get("program")
if program and program == "shell" and not is_subhost("windows") then
wprint("The shell was not integrated with xmake. Some features might be missing. Please switch to your default shell, and run `xmake update --integrate` to integrate the shell.")
end
local envs = _package_getenvs()
if program and not option.get("show") then
if envs and envs.PATH then
os.setenv("PATH", envs.PATH)
end
if program == "shell" then
_run_shell(envs)
else
os.execv(program, option.get("arguments"), {envs = envs})
end
else
print(envs)
end
end
end
|
0 | repos/xmake/xmake/modules/private/xrepo | repos/xmake/xmake/modules/private/xrepo/action/add-repo.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 add-repo.lua
--
-- imports
import("core.base.option")
-- get menu options
function menu_options()
-- description
local description = "Add the given remote repository url."
-- menu options
local options =
{
{nil, "name", "v", nil, "The repository name." },
{nil, "url", "v", nil, "The repository url" },
{nil, "branch", "v", nil, "The repository branch" }
}
-- show menu options
local function show_options()
-- show usage
cprint("${bright}Usage: $${clear cyan}xrepo add-repo [options] name url [branch]")
-- show description
print("")
print(description)
-- show options
option.show_options(options, "add-repo")
end
return options, show_options, description
end
-- add repository
function _add_repository(name, url, branch)
-- enter working project directory
local workdir = path.join(os.tmpdir(), "xrepo", "working")
if not os.isdir(workdir) then
os.mkdir(workdir)
os.cd(workdir)
os.vrunv(os.programfile(), {"create", "-P", "."})
else
os.cd(workdir)
end
-- add it
local repo_argv = {"repo", "--add", "--global"}
if option.get("verbose") then
table.insert(repo_argv, "-v")
end
if option.get("diagnosis") then
table.insert(repo_argv, "-D")
end
table.insert(repo_argv, name)
table.insert(repo_argv, url)
if branch then
table.insert(repo_argv, branch)
end
os.vexecv(os.programfile(), repo_argv)
end
-- main entry
function main()
local name = option.get("name")
local url = option.get("url")
if name and url then
_add_repository(name, url, option.get("branch"))
else
raise("please specify the repository name and url to be added.")
end
end
|
0 | repos/xmake/xmake/modules/private/xrepo | repos/xmake/xmake/modules/private/xrepo/action/remove.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 remove.lua
--
-- imports
import("core.base.option")
import("private.action.require.impl.remove_packages", {alias = "remove_all_packages"})
-- get menu options
function menu_options()
-- description
local description = "Remove the given packages."
-- menu options
local options =
{
{'k', "kind", "kv", nil, "Enable static/shared library.",
values = {"static", "shared"} },
{'p', "plat", "kv", nil, "Set the given platform." },
{'a', "arch", "kv", nil, "Set the given architecture." },
{'m', "mode", "kv", nil, "Set the given mode.",
values = {"release", "debug"} },
{'f', "configs", "kv", nil, "Set the given extra package configs.",
"e.g.",
" - xrepo remove -f \"runtimes='MD'\" zlib",
" - xrepo remove -f \"regex=true,thread=true\" boost"},
{nil, "toolchain", "kv", nil, "Set the toolchain name." },
{},
{nil, "all", "k", nil, "Remove all packages and ignore extra package configs.",
"If `--all` is enabled, the package name parameter will support lua pattern",
"e.g.",
" - xrepo remove --all",
" - xrepo remove --all zlib boost",
" - xrepo remove --all zl* boo*"},
{nil, "packages", "vs", nil, "The packages list.",
"e.g.",
" - xrepo remove zlib boost",
" - xrepo remove -p iphoneos -a arm64 \"zlib >=1.2.0\"",
" - xrepo remove -p android -m debug \"pcre2 10.x\"",
" - xrepo remove -p mingw -k shared zlib",
" - xrepo remove conan::zlib/1.2.11 vcpkg::zlib"}
}
-- show menu options
local function show_options()
-- show usage
cprint("${bright}Usage: $${clear cyan}xrepo remove [options] packages")
-- show description
print("")
print(description)
-- show options
option.show_options(options, "remove")
end
return options, show_options, description
end
-- remove packages
function _remove_packages(packages)
-- is package configuration file? e.g. xrepo install xxx.lua
--
-- xxx.lua
-- add_requires("libpng", {system = false})
-- add_requireconfs("libpng.*", {configs = {shared = true}})
local packagefile
if type(packages) == "string" or #packages == 1 then
local filepath = table.unwrap(packages)
if type(filepath) == "string" and filepath:endswith(".lua") and os.isfile(filepath) then
packagefile = path.absolute(filepath)
end
end
-- add includes to rcfiles
local rcfiles = {}
local includes = option.get("includes")
if includes then
table.join2(rcfiles, path.splitenv(includes))
end
-- enter working project directory
local subdir = "working"
if packagefile then
subdir = subdir .. "-" .. hash.uuid(packagefile):split('-')[1]
end
local workdir = path.join(os.tmpdir(), "xrepo", subdir)
if not os.isdir(workdir) then
os.mkdir(workdir)
os.cd(workdir)
os.vrunv(os.programfile(), {"create", "-P", "."})
else
os.cd(workdir)
end
if packagefile then
assert(os.isfile("xmake.lua"), "xmake.lua not found!")
io.writefile("xmake.lua", ('includes("%s")\ntarget("test", {kind = "phony"})'):format((packagefile:gsub("\\", "/"))))
end
-- do configure first
local config_argv = {"f", "-c", "--require=n"}
if option.get("diagnosis") then
table.insert(config_argv, "-vD")
end
if option.get("plat") then
table.insert(config_argv, "-p")
table.insert(config_argv, option.get("plat"))
end
if option.get("arch") then
table.insert(config_argv, "-a")
table.insert(config_argv, option.get("arch"))
end
local mode = option.get("mode")
if mode then
table.insert(config_argv, "-m")
table.insert(config_argv, mode)
end
local kind = option.get("kind")
if kind then
table.insert(config_argv, "-k")
table.insert(config_argv, kind)
end
if option.get("toolchain") then
table.insert(config_argv, "--toolchain=" .. option.get("toolchain"))
end
local envs = {}
if #rcfiles > 0 then
envs.XMAKE_RCFILES = path.joinenv(rcfiles)
end
os.vrunv(os.programfile(), config_argv, {envs = envs})
-- do remove
local require_argv = {"require", "--uninstall"}
if option.get("yes") then
table.insert(require_argv, "-y")
end
if option.get("verbose") then
table.insert(require_argv, "-v")
end
if option.get("diagnosis") then
table.insert(require_argv, "-D")
end
local extra = {system = false}
if mode == "debug" then
extra.debug = true
end
if kind then
extra.configs = extra.configs or {}
extra.configs.shared = kind == "shared"
end
local configs = option.get("configs")
if configs then
extra.configs = extra.configs or {}
local extra_configs, errors = ("{" .. configs .. "}"):deserialize()
if extra_configs then
table.join2(extra.configs, extra_configs)
else
raise(errors)
end
end
if not packagefile then
-- avoid overriding extra configs in add_requires/xmake.lua
if extra then
local extra_str = string.serialize(extra, {indent = false, strip = true})
table.insert(require_argv, "--extra=" .. extra_str)
end
table.join2(require_argv, packages)
end
os.vexecv(os.programfile(), require_argv)
end
-- main entry
function main()
local packages = option.get("packages")
if option.get("all") then
remove_all_packages(packages)
elseif packages then
_remove_packages(packages)
else
raise("please specify the packages to be removed.")
end
end
|
0 | repos/xmake/xmake/modules/private/xrepo | repos/xmake/xmake/modules/private/xrepo/action/fetch.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 fetch.lua
--
-- imports
import("core.base.option")
-- get menu options
function menu_options()
-- description
local description = "Fetch library information of the given installed packages."
-- menu options
local options =
{
{'k', "kind", "kv", nil, "Enable static/shared library.",
values = {"static", "shared"} },
{'p', "plat", "kv", nil, "Set the given platform." },
{'a', "arch", "kv", nil, "Set the given architecture." },
{'m', "mode", "kv", nil, "Set the given mode.",
values = {"release", "debug"} },
{'f', "configs", "kv", nil, "Set the given extra package configs.",
"e.g.",
" - xrepo fetch --configs=\"runtimes='MD'\" zlib",
" - xrepo fetch --configs=\"regex=true,thread=true\" boost"},
{nil, "system", "k", "false", "Only fetch package on current system."},
{},
{nil, "toolchain", "kv", nil, "Set the toolchain name." },
{nil, "includes", "kv", nil, "Includes extra lua configuration files.",
"e.g.",
" - xrepo fetch -p cross --toolchain=mytool --includes='toolchain1.lua" .. path.envsep() .. "toolchain2.lua'"},
{nil, "deps", "k", nil, "Fetch packages with dependencies." },
{nil, "cflags", "k", nil, "Fetch cflags of the given packages." },
{nil, "ldflags", "k", nil, "Fetch ldflags of the given packages."},
{'e', "external", "k", nil, "Show cflags as external packages with -isystem."},
{nil, "json", "k", nil, "Output package info as json format." },
{},
{nil, "packages", "vs", nil, "The packages list.",
"e.g.",
" - xrepo fetch zlib boost",
" - xrepo fetch /tmp/zlib.lua",
" - xrepo fetch -p iphoneos -a arm64 \"zlib >=1.2.0\"",
" - xrepo fetch -p android -m debug \"pcre2 10.x\"",
" - xrepo fetch -p mingw -k shared zlib",
" - xrepo fetch conan::zlib/1.2.11 vcpkg::zlib",
" - xrepo fetch brew::zlib",
" - xrepo fetch system::zlib (from pkgconfig, brew, /usr/lib ..)",
" - xrepo fetch pkgconfig::zlib"}
}
-- show menu options
local function show_options()
-- show usage
cprint("${bright}Usage: $${clear cyan}xrepo fetch [options] packages")
-- show description
print("")
print(description)
-- show options
option.show_options(options, "fetch")
end
return options, show_options, description
end
-- fetch packages
function _fetch_packages(packages)
-- is package configuration file? e.g. xrepo install xxx.lua
--
-- xxx.lua
-- add_requires("libpng", {system = false})
-- add_requireconfs("libpng.*", {configs = {shared = true}})
local packagefile
if type(packages) == "string" or #packages == 1 then
local filepath = table.unwrap(packages)
if type(filepath) == "string" and filepath:endswith(".lua") and os.isfile(filepath) then
packagefile = path.absolute(filepath)
end
end
-- add includes to rcfiles
local rcfiles = {}
local includes = option.get("includes")
if includes then
table.join2(rcfiles, path.splitenv(includes))
end
-- enter working project directory
local subdir = "working"
if packagefile then
subdir = subdir .. "-" .. hash.uuid(packagefile):split('-')[1]
end
local workdir = path.join(os.tmpdir(), "xrepo", subdir)
if not os.isdir(workdir) then
os.mkdir(workdir)
os.cd(workdir)
os.vrunv(os.programfile(), {"create", "-P", "."})
else
os.cd(workdir)
end
if packagefile then
assert(os.isfile("xmake.lua"), "xmake.lua not found!")
io.writefile("xmake.lua", ('includes("%s")\ntarget("test", {kind = "phony"})'):format((packagefile:gsub("\\", "/"))))
end
-- do configure first
local config_argv = {"f", "-c", "--require=n"}
if option.get("diagnosis") then
table.insert(config_argv, "-vD")
end
if option.get("plat") then
table.insert(config_argv, "-p")
table.insert(config_argv, option.get("plat"))
end
if option.get("arch") then
table.insert(config_argv, "-a")
table.insert(config_argv, option.get("arch"))
end
if option.get("toolchain") then
table.insert(config_argv, "--toolchain=" .. option.get("toolchain"))
end
local mode = option.get("mode")
if mode then
table.insert(config_argv, "-m")
table.insert(config_argv, mode)
end
local kind = option.get("kind")
if kind then
table.insert(config_argv, "-k")
table.insert(config_argv, kind)
end
local envs = {}
if #rcfiles > 0 then
envs.XMAKE_RCFILES = path.joinenv(rcfiles)
end
os.vrunv(os.programfile(), config_argv, {envs = envs})
-- do fetch
local require_argv = {"require", "--fetch"}
if option.get("yes") then
table.insert(require_argv, "-y")
end
if option.get("verbose") then
table.insert(require_argv, "-v")
end
if option.get("diagnosis") then
table.insert(require_argv, "-D")
end
local fetchmodes = {}
if option.get("deps") then
table.insert(fetchmodes, "deps")
end
if option.get("cflags") then
table.insert(fetchmodes, "cflags")
end
if option.get("ldflags") then
table.insert(fetchmodes, "ldflags")
end
if option.get("external") then
table.insert(fetchmodes, "external")
end
if option.get("json") then
table.insert(fetchmodes, "json")
end
if #fetchmodes > 0 then
table.insert(require_argv, "--fetch_modes=" .. table.concat(fetchmodes, ','))
end
local extra = {system = option.get("system")}
if mode == "debug" then
extra.debug = true
end
if kind then
extra.configs = extra.configs or {}
extra.configs.shared = kind == "shared"
end
local configs = option.get("configs")
if configs then
extra.configs = extra.configs or {}
local extra_configs, errors = ("{" .. configs .. "}"):deserialize()
if extra_configs then
table.join2(extra.configs, extra_configs)
else
raise(errors)
end
end
if not packagefile then
-- avoid overriding extra configs in add_requires/xmake.lua
if extra then
local extra_str = string.serialize(extra, {indent = false, strip = true})
table.insert(require_argv, "--extra=" .. extra_str)
end
table.join2(require_argv, packages)
end
os.vexecv(os.programfile(), require_argv, {envs = envs})
end
-- main entry
function main()
local packages = option.get("packages")
if packages then
_fetch_packages(packages)
else
raise("please specify the package to be fetched.")
end
end
|
0 | repos/xmake/xmake/modules/private/xrepo | repos/xmake/xmake/modules/private/xrepo/action/info.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 info.lua
--
-- imports
import("core.base.option")
-- get menu options
function menu_options()
-- description
local description = "Show information of the given packages."
-- menu options
local options =
{
{'k', "kind", "kv", nil, "Enable static/shared library.",
values = {"static", "shared"} },
{'p', "plat", "kv", nil, "Set the given platform." },
{'a', "arch", "kv", nil, "Set the given architecture." },
{'m', "mode", "kv", nil, "Set the given mode.",
values = {"release", "debug"} },
{'f', "configs", "kv", nil, "Set the given extra package configs.",
"e.g.",
" - xrepo fetch --configs=\"runtimes='MD'\" zlib",
" - xrepo fetch --configs=\"regex=true,thread=true\" boost"},
{},
{nil, "packages", "vs", nil, "The packages list.",
"e.g.",
" - xrepo info zlib boost"}
}
-- show menu options
local function show_options()
-- show usage
cprint("${bright}Usage: $${clear cyan}xrepo info [options] packages")
-- show description
print("")
print(description)
-- show options
option.show_options(options, "info")
end
return options, show_options, description
end
-- info packages
function _info_packages(packages)
-- enter working project directory
local workdir = path.join(os.tmpdir(), "xrepo", "working")
if not os.isdir(workdir) then
os.mkdir(workdir)
os.cd(workdir)
os.vrunv(os.programfile(), {"create", "-P", "."})
else
os.cd(workdir)
end
-- do configure first
local config_argv = {"f", "-c"}
if option.get("diagnosis") then
table.insert(config_argv, "-vD")
end
if option.get("plat") then
table.insert(config_argv, "-p")
table.insert(config_argv, option.get("plat"))
end
if option.get("arch") then
table.insert(config_argv, "-a")
table.insert(config_argv, option.get("arch"))
end
local mode = option.get("mode")
if mode then
table.insert(config_argv, "-m")
table.insert(config_argv, mode)
end
local kind = option.get("kind")
if kind then
table.insert(config_argv, "-k")
table.insert(config_argv, kind)
end
os.vrunv(os.programfile(), config_argv)
-- show info
local require_argv = {"require", "--info"}
if option.get("verbose") then
table.insert(require_argv, "-v")
end
if option.get("diagnosis") then
table.insert(require_argv, "-D")
end
local extra = {system = false}
if mode == "debug" then
extra.debug = true
end
if kind then
extra.configs = extra.configs or {}
extra.configs.shared = kind == "shared"
end
local configs = option.get("configs")
if configs then
extra.configs = extra.configs or {}
local extra_configs, errors = ("{" .. configs .. "}"):deserialize()
if extra_configs then
table.join2(extra.configs, extra_configs)
else
raise(errors)
end
end
if extra then
local extra_str = string.serialize(extra, {indent = false, strip = true})
table.insert(require_argv, "--extra=" .. extra_str)
end
table.join2(require_argv, packages)
os.vexecv(os.programfile(), require_argv)
end
-- main entry
function main()
local packages = option.get("packages")
if packages then
_info_packages(packages)
else
raise("please specify the packages to be viewed.")
end
end
|
0 | repos/xmake/xmake/modules/private/xrepo | repos/xmake/xmake/modules/private/xrepo/action/list-repo.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 list-repo.lua
--
-- imports
import("core.base.option")
-- get menu options
function menu_options()
-- description
local description = "List all remote repositories."
-- menu options
local options = {}
-- show menu options
local function show_options()
-- show usage
cprint("${bright}Usage: $${clear cyan}xrepo list-repo [options]")
-- show description
print("")
print(description)
-- show options
option.show_options(options, "list-repo")
end
return options, show_options, description
end
-- list repository
function list_repository()
-- enter working project directory
local workdir = path.join(os.tmpdir(), "xrepo", "working")
if not os.isdir(workdir) then
os.mkdir(workdir)
os.cd(workdir)
os.vrunv(os.programfile(), {"create", "-P", "."})
else
os.cd(workdir)
end
-- list it
local repo_argv = {"repo", "--list", "--global"}
if option.get("verbose") then
table.insert(repo_argv, "-v")
end
if option.get("diagnosis") then
table.insert(repo_argv, "-D")
end
os.vexecv(os.programfile(), repo_argv)
end
-- main entry
function main()
list_repository()
end
|
0 | repos/xmake/xmake/modules/private/xrepo | repos/xmake/xmake/modules/private/xrepo/action/import.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 import.lua
--
-- imports
import("core.base.option")
import("core.base.task")
-- get menu options
function menu_options()
-- description
local description = "Import the given packages."
-- menu options
local options =
{
{'k', "kind", "kv", nil, "Enable static/shared library.",
values = {"static", "shared"} },
{'p', "plat", "kv", nil, "Set the given platform." },
{'a', "arch", "kv", nil, "Set the given architecture." },
{'m', "mode", "kv", nil, "Set the given mode.",
values = {"release", "debug"} },
{'f', "configs", "kv", nil, "Set the given extra package configs.",
"e.g.",
" - xrepo import -f \"runtimes='MD'\" zlib",
" - xrepo import -f \"regex=true,thread=true\" boost"},
{},
{'i', "packagedir", "kv", "packages","Set the imported packages directory."},
{nil, "packages", "vs", nil, "The packages list.",
"e.g.",
" - xrepo import zlib boost",
" - xrepo import -p iphoneos -a arm64 \"zlib >=1.2.0\"",
" - xrepo import -p android -m debug \"pcre2 10.x\"",
" - xrepo import -p mingw -k shared zlib",
" - xrepo import conan::zlib/1.2.11 vcpkg::zlib"}
}
-- show menu options
local function show_options()
-- show usage
cprint("${bright}Usage: $${clear cyan}xrepo import [options] packages")
-- show description
print("")
print(description)
-- show options
option.show_options(options, "import")
end
return options, show_options, description
end
-- import packages
function _import_packages(packages)
-- enter working project directory
local oldir = os.curdir()
local workdir = path.join(os.tmpdir(), "xrepo", "working")
if not os.isdir(workdir) then
os.mkdir(workdir)
os.cd(workdir)
os.vrunv(os.programfile(), {"create", "-P", "."})
else
os.cd(workdir)
end
-- do configure first
local config_argv = {"f", "-c"}
if option.get("diagnosis") then
table.insert(config_argv, "-vD")
end
if option.get("plat") then
table.insert(config_argv, "-p")
table.insert(config_argv, option.get("plat"))
end
if option.get("arch") then
table.insert(config_argv, "-a")
table.insert(config_argv, option.get("arch"))
end
local mode = option.get("mode")
if mode then
table.insert(config_argv, "-m")
table.insert(config_argv, mode)
end
local kind = option.get("kind")
if kind then
table.insert(config_argv, "-k")
table.insert(config_argv, kind)
end
os.vrunv(os.programfile(), config_argv)
-- do import
local require_argv = {"require", "--import"}
if option.get("yes") then
table.insert(require_argv, "-y")
end
if option.get("verbose") then
table.insert(require_argv, "-v")
end
if option.get("diagnosis") then
table.insert(require_argv, "-D")
end
local packagedir = option.get("packagedir")
if packagedir and not path.is_absolute(packagedir) then
packagedir = path.absolute(packagedir, oldir)
end
if packagedir then
table.insert(require_argv, "--packagedir=" .. packagedir)
end
local extra = {system = false}
if mode == "debug" then
extra.debug = true
end
if kind then
extra.configs = extra.configs or {}
extra.configs.shared = kind == "shared"
end
local configs = option.get("configs")
if configs then
extra.configs = extra.configs or {}
local extra_configs, errors = ("{" .. configs .. "}"):deserialize()
if extra_configs then
table.join2(extra.configs, extra_configs)
else
raise(errors)
end
end
if extra then
local extra_str = string.serialize(extra, {indent = false, strip = true})
table.insert(require_argv, "--extra=" .. extra_str)
end
table.join2(require_argv, packages)
os.vexecv(os.programfile(), require_argv)
end
-- import packages in current project
function _import_current_packages(packages)
-- do import
local require_argv = {import = true}
if option.get("yes") then
require_argv.yes = true
end
if option.get("verbose") then
require_argv.verbose = true
end
if option.get("diagnosis") then
require_argv.diagnosis = true
end
local packagedir = option.get("packagedir")
if packagedir and not path.is_absolute(packagedir) then
packagedir = path.absolute(packagedir, oldir)
end
if packagedir then
require_argv.packagedir = packagedir
end
local extra = {system = false}
local mode = option.get("mode")
if mode == "debug" then
extra.debug = true
end
local kind = option.get("kind")
if kind then
extra.configs = extra.configs or {}
extra.configs.shared = kind == "shared"
end
local configs = option.get("configs")
if configs then
extra.configs = extra.configs or {}
local extra_configs, errors = ("{" .. configs .. "}"):deserialize()
if extra_configs then
table.join2(extra.configs, extra_configs)
else
raise(errors)
end
end
if extra then
local extra_str = string.serialize(extra, {indent = false, strip = true})
require_argv.extra = extra_str
end
task.run("require", require_argv)
end
-- main entry
function main()
local packages = option.get("packages")
if packages then
_import_packages(packages)
elseif os.isfile(os.projectfile()) then
_import_current_packages()
else
raise("please specify the packages to be imported.")
end
end
|
0 | repos/xmake/xmake/modules/private/xrepo | repos/xmake/xmake/modules/private/xrepo/action/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("core.base.option")
-- get menu options
function menu_options()
-- description
local description = "Install the given packages."
-- menu options
local options =
{
{'k', "kind", "kv", nil, "Enable static/shared library.",
values = {"static", "shared"} },
{'p', "plat", "kv", nil, "Set the given platform." },
{'a', "arch", "kv", nil, "Set the given architecture." },
{'m', "mode", "kv", nil, "Set the given mode.",
values = {"release", "debug"} },
{'f', "configs", "kv", nil, "Set the given extra package configs.",
"e.g.",
" - xrepo install -f \"runtimes='MD'\" zlib",
" - xrepo install -f \"regex=true,thread=true\" boost"},
{'j', "jobs", "kv", tostring(os.default_njob()),
"Set the number of parallel compilation jobs."},
{nil, "linkjobs", "kv", nil, "Set the number of parallel link jobs."},
{nil, "includes", "kv", nil, "Includes extra lua configuration files.",
"e.g.",
" - xrepo install -p cross --toolchain=mytool --includes='toolchain1.lua" .. path.envsep() .. "toolchain2.lua'"},
{category = "Visual Studio SDK Configuration" },
{nil, "vs", "kv", nil, "The Microsoft Visual Studio"
, " e.g. --vs=2017" },
{nil, "vs_toolset", "kv", nil, "The Microsoft Visual Studio Toolset Version"
, " e.g. --vs_toolset=14.0" },
{nil, "vs_sdkver", "kv", nil, "The Windows SDK Version of Visual Studio"
, " e.g. --vs_sdkver=10.0.15063.0" },
{category = "Android NDK Configuration" },
{nil, "ndk", "kv", nil, "The NDK directory" },
{nil, "ndk_sdkver", "kv", nil, "The SDK Version for NDK (default: auto)" },
{nil, "android_sdk", "kv", nil, "The Android SDK Directory" },
{nil, "build_toolver", "kv", nil, "The Build Tool Version of Android SDK" },
{nil, "ndk_stdcxx", "kv", nil, "Use stdc++ library for NDK" },
{nil, "ndk_cxxstl", "kv", nil, "The stdc++ stl library for NDK",
" - c++_static",
" - c++_shared",
" - gnustl_static",
" - gnustl_shared",
" - stlport_shared",
" - stlport_static" },
{category = "Cross Compilation Configuration" },
{nil, "sdk", "kv", nil, "Set the SDK directory of cross toolchain." },
{nil, "toolchain", "kv", nil, "Set the toolchain name." },
{category = "MingW Configuration" },
{nil, "mingw", "kv", nil, "Set the MingW SDK directory." },
{category = "XCode SDK Configuration" },
{nil, "xcode", "kv", nil, "The Xcode Application Directory" },
{nil, "xcode_sdkver", "kv", nil, "The SDK Version for Xcode" },
{nil, "target_minver", "kv", nil, "The Target Minimal Version" },
{nil, "appledev", "kv", nil, "The Apple Device Type", values = {"simulator", "iphone", "watchtv", "appletv", "catalyst"}},
{category = "Debug Configuration" },
{'d', "debugdir", "kv", nil, "The source directory of the current package for debugging. It will enable --force/--shallow by default."},
{category = "Other Configuration" },
{nil, "force", "k", nil, "Force to reinstall all package dependencies."},
{nil, "shallow", "k", nil, "Does not install dependent packages."},
{nil, "build", "k", nil, "Always build and install packages from source."},
{},
{nil, "packages", "vs", nil, "The packages list.",
"e.g.",
" - xrepo install zlib boost",
" - xrepo install /tmp/zlib.lua",
" - xrepo install -p iphoneos -a arm64 \"zlib >=1.2.0\"",
" - xrepo install -p android [--ndk=/xxx] -m debug \"pcre2 10.x\"",
" - xrepo install -p mingw [--mingw=/xxx] -k shared zlib",
" - xrepo install conan::zlib/1.2.11 vcpkg::zlib",
values = function (complete, opt) return import("private.xrepo.quick_search.completion")(complete, opt) end}
}
-- show menu options
local function show_options()
-- show usage
cprint("${bright}Usage: $${clear cyan}xrepo install [options] packages")
-- show description
print("")
print(description)
-- show options
option.show_options(options, "install")
end
return options, show_options, description
end
-- install packages
function _install_packages(packages)
-- is package configuration file? e.g. xrepo install xxx.lua
--
-- xxx.lua
-- add_requires("libpng", {system = false})
-- add_requireconfs("libpng.*", {configs = {shared = true}})
local packagefile
if type(packages) == "string" or #packages == 1 then
local filepath = table.unwrap(packages)
if type(filepath) == "string" and filepath:endswith(".lua") and os.isfile(filepath) then
packagefile = path.absolute(filepath)
end
end
-- add includes to rcfiles
local rcfiles = {}
local includes = option.get("includes")
if includes then
table.join2(rcfiles, path.splitenv(includes))
end
-- enter working project directory
local subdir = "working"
if packagefile then
subdir = subdir .. "-" .. hash.uuid(packagefile):split('-')[1]
end
local origindir = os.curdir()
local workdir = path.join(os.tmpdir(), "xrepo", subdir)
if not os.isdir(workdir) then
os.mkdir(workdir)
os.cd(workdir)
os.vrunv(os.programfile(), {"create", "-P", "."})
else
os.cd(workdir)
end
if packagefile then
assert(os.isfile("xmake.lua"), "xmake.lua not found!")
io.writefile("xmake.lua", ('includes("%s")\ntarget("test", {kind = "phony"})'):format((packagefile:gsub("\\", "/"))))
end
-- disable xmake-stats
os.setenv("XMAKE_STATS", "false")
-- do configure first
local config_argv = {"f", "-c", "--require=n"}
if option.get("diagnosis") then
table.insert(config_argv, "-vD")
end
if option.get("plat") then
table.insert(config_argv, "-p")
table.insert(config_argv, option.get("plat"))
end
if option.get("arch") then
table.insert(config_argv, "-a")
table.insert(config_argv, option.get("arch"))
end
local mode = option.get("mode")
if mode then
table.insert(config_argv, "-m")
table.insert(config_argv, mode)
end
local kind = option.get("kind")
if kind then
table.insert(config_argv, "-k")
table.insert(config_argv, kind)
end
-- for android
if option.get("ndk") then
table.insert(config_argv, "--ndk=" .. option.get("ndk"))
end
if option.get("ndk_sdkver") then
table.insert(config_argv, "--ndk_sdkver=" .. option.get("ndk_sdkver"))
end
if option.get("android_sdk") then
table.insert(config_argv, "--android_sdk=" .. option.get("android_sdk"))
end
if option.get("build_toolver") then
table.insert(config_argv, "--build_toolver=" .. option.get("build_toolver"))
end
if option.get("ndk_stdcxx") then
table.insert(config_argv, "--ndk_stdcxx=" .. option.get("ndk_stdcxx"))
end
if option.get("ndk_cxxstl") then
table.insert(config_argv, "--ndk_cxxstl=" .. option.get("ndk_cxxstl"))
end
-- for cross toolchain
if option.get("sdk") then
table.insert(config_argv, "--sdk=" .. option.get("sdk"))
end
if option.get("toolchain") then
table.insert(config_argv, "--toolchain=" .. option.get("toolchain"))
end
-- for mingw
if option.get("mingw") then
table.insert(config_argv, "--mingw=" .. option.get("mingw"))
end
-- for vs
if option.get("vs") then
table.insert(config_argv, "--vs=" .. option.get("vs"))
end
if option.get("vs_toolset") then
table.insert(config_argv, "--vs_toolset=" .. option.get("vs_toolset"))
end
if option.get("vs_sdkver") then
table.insert(config_argv, "--vs_sdkver=" .. option.get("vs_sdkver"))
end
-- for xcode
if option.get("xcode") then
table.insert(config_argv, "--xcode=" .. option.get("xcode"))
end
if option.get("xcode_sdkver") then
table.insert(config_argv, "--xcode_sdkver=" .. option.get("xcode_sdkver"))
end
if option.get("target_minver") then
table.insert(config_argv, "--target_minver=" .. option.get("target_minver"))
end
if option.get("appledev") then
table.insert(config_argv, "--appledev=" .. option.get("appledev"))
end
local envs = {}
if #rcfiles > 0 then
envs.XMAKE_RCFILES = path.joinenv(rcfiles)
end
os.vrunv(os.programfile(), config_argv, {envs = envs})
-- do install
local require_argv = {"require"}
if option.get("yes") then
table.insert(require_argv, "-y")
end
if option.get("verbose") then
table.insert(require_argv, "-v")
end
if option.get("diagnosis") then
table.insert(require_argv, "-D")
end
if option.get("jobs") then
table.insert(require_argv, "-j")
table.insert(require_argv, option.get("jobs"))
end
if option.get("linkjobs") then
table.insert(require_argv, "--linkjobs=" .. option.get("linkjobs"))
end
local is_debug = false
local sourcedir = option.get("debugdir")
if sourcedir then
is_debug = true
table.insert(require_argv, "--debugdir=" .. path.absolute(sourcedir, origindir))
end
if option.get("force") or is_debug then
table.insert(require_argv, "--force")
end
if option.get("shallow") or is_debug then
table.insert(require_argv, "--shallow")
end
if option.get("build") or is_debug then
table.insert(require_argv, "--build")
end
local extra = {system = false}
if mode == "debug" then
extra.debug = true
end
if kind then
extra.configs = extra.configs or {}
extra.configs.shared = kind == "shared"
end
local configs = option.get("configs")
if configs then
extra.system = false
extra.configs = extra.configs or {}
local extra_configs, errors = ("{" .. configs .. "}"):deserialize()
if extra_configs then
table.join2(extra.configs, extra_configs)
else
raise(errors)
end
end
if not packagefile then
-- avoid overriding extra configs in add_requires/xmake.lua
if extra then
local extra_str = string.serialize(extra, {indent = false, strip = true})
table.insert(require_argv, "--extra=" .. extra_str)
end
table.join2(require_argv, packages)
end
os.vexecv(os.programfile(), require_argv, {envs = envs})
end
-- main entry
function main()
local packages = option.get("packages")
if packages then
_install_packages(packages)
else
raise("please specify the packages to be installed.")
end
end
|
0 | repos/xmake/xmake/modules/private/xrepo | repos/xmake/xmake/modules/private/xrepo/action/scan.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 scan.lua
--
-- imports
import("core.base.option")
-- get menu options
function menu_options()
-- description
local description = "Scan the given or all installed packages."
-- menu options
local options =
{
{nil, "packages", "vs", nil, "The packages list (support lua pattern).",
"e.g.",
" - xrepo scan",
" - xrepo scan zlib",
" - xrepo scan zlib bo*"}
}
-- show menu options
local function show_options()
-- show usage
cprint("${bright}Usage: $${clear cyan}xrepo scan [options] [packages]")
-- show description
print("")
print(description)
-- show options
option.show_options(options, "scan")
end
return options, show_options, description
end
-- scan packages
function _scan_packages(packages)
-- enter working project directory
local workdir = path.join(os.tmpdir(), "xrepo", "working")
if not os.isdir(workdir) then
os.mkdir(workdir)
os.cd(workdir)
os.vrunv(os.programfile(), {"create", "-P", "."})
else
os.cd(workdir)
end
-- do configure first
local config_argv = {"f", "-c"}
if option.get("diagnosis") then
table.insert(config_argv, "-vD")
end
os.vrunv(os.programfile(), config_argv)
-- do scan
local require_argv = {"require", "--scan"}
if option.get("yes") then
table.insert(require_argv, "-y")
end
if option.get("verbose") then
table.insert(require_argv, "-v")
end
if option.get("diagnosis") then
table.insert(require_argv, "-D")
end
if packages then
table.join2(require_argv, packages)
end
os.vexecv(os.programfile(), require_argv)
end
-- main entry
function main()
_scan_packages(option.get("packages"))
end
|
0 | repos/xmake/xmake/modules/private/xrepo | repos/xmake/xmake/modules/private/xrepo/action/update-repo.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 update-repo.lua
--
-- imports
import("core.base.option")
-- get menu options
function menu_options()
-- description
local description = "Update all local repositories from remote."
-- menu options
local options = {}
-- show menu options
local function show_options()
-- show usage
cprint("${bright}Usage: $${clear cyan}xrepo update-repo [options]")
-- show description
print("")
print(description)
-- show options
option.show_options(options, "update-repo")
end
return options, show_options, description
end
-- update repository
function update_repository()
-- enter working project directory
local workdir = path.join(os.tmpdir(), "xrepo", "working")
if not os.isdir(workdir) then
os.mkdir(workdir)
os.cd(workdir)
os.vrunv(os.programfile(), {"create", "-P", "."})
else
os.cd(workdir)
end
-- update it
local repo_argv = {"repo", "--update"}
if option.get("verbose") then
table.insert(repo_argv, "-v")
end
if option.get("diagnosis") then
table.insert(repo_argv, "-D")
end
os.vexecv(os.programfile(), repo_argv)
end
-- main entry
function main()
update_repository()
end
|
0 | repos/xmake/xmake/modules/private/xrepo | repos/xmake/xmake/modules/private/xrepo/action/rm-repo.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 rm-repo.lua
--
-- imports
import("core.base.option")
-- get menu options
function menu_options()
-- description
local description = "Remove the given remote repository."
-- menu options
local options =
{
{nil, "all", "k", nil, "Remove all added repositories."},
{nil, "name", "v", nil, "The repository name."}
}
-- show menu options
local function show_options()
-- show usage
cprint("${bright}Usage: $${clear cyan}xrepo rm-repo [options] [name]")
-- show description
print("")
print(description)
-- show options
option.show_options(options, "rm-repo")
end
return options, show_options, description
end
-- remove repository
function remove_repository(name)
-- enter working project directory
local workdir = path.join(os.tmpdir(), "xrepo", "working")
if not os.isdir(workdir) then
os.mkdir(workdir)
os.cd(workdir)
os.vrunv(os.programfile(), {"create", "-P", "."})
else
os.cd(workdir)
end
-- remove it
local repo_argv = {"repo", "--remove", "--global"}
if option.get("verbose") then
table.insert(repo_argv, "-v")
end
if option.get("diagnosis") then
table.insert(repo_argv, "-D")
end
table.insert(repo_argv, name)
os.vexecv(os.programfile(), repo_argv)
end
-- clear repository
function clear_repository()
-- enter working project directory
local workdir = path.join(os.tmpdir(), "xrepo", "working")
if not os.isdir(workdir) then
os.mkdir(workdir)
os.cd(workdir)
os.vrunv(os.programfile(), {"create", "-P", "."})
else
os.cd(workdir)
end
-- clear all
local repo_argv = {"repo", "--clear", "--global"}
if option.get("verbose") then
table.insert(repo_argv, "-v")
end
if option.get("diagnosis") then
table.insert(repo_argv, "-D")
end
os.vexecv(os.programfile(), repo_argv)
end
-- main entry
function main()
local name = option.get("name")
if name then
remove_repository(name)
elseif option.get("all") then
clear_repository()
else
raise("please specify the repository name to be removed.")
end
end
|
0 | repos/xmake/xmake/modules/private/xrepo | repos/xmake/xmake/modules/private/xrepo/action/clean.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 clean.lua
--
-- imports
import("core.base.option")
-- get menu options
function menu_options()
-- description
local description = "Clear all package caches and remove all not-referenced packages."
-- menu options
local options =
{
{nil, "cache", "k", nil, "Just clean packages cache."},
{nil, "packages", "vs", nil, "The packages list (support lua pattern).",
"e.g.",
" - xrepo clean",
" - xrepo clean zlib",
" - xrepo clean zlib bo*"}
}
-- show menu options
local function show_options()
-- show usage
cprint("${bright}Usage: $${clear cyan}xrepo clean [options] [packages]")
-- show description
print("")
print(description)
-- show options
option.show_options(options, "clean")
end
return options, show_options, description
end
-- clean packages
function _clean_packages(packages)
-- enter working project directory
local workdir = path.join(os.tmpdir(), "xrepo", "working")
if not os.isdir(workdir) then
os.mkdir(workdir)
os.cd(workdir)
os.vrunv(os.programfile(), {"create", "-P", "."})
else
os.cd(workdir)
end
-- do configure first
local config_argv = {"f", "-c"}
if option.get("diagnosis") then
table.insert(config_argv, "-vD")
end
os.vrunv(os.programfile(), config_argv)
-- do clean
local require_argv = {"require", "--clean"}
if option.get("yes") then
table.insert(require_argv, "-y")
end
if option.get("verbose") then
table.insert(require_argv, "-v")
end
if option.get("diagnosis") then
table.insert(require_argv, "-D")
end
if option.get("cache") then
table.insert(require_argv, "--clean_modes=cache")
end
if packages then
table.join2(require_argv, packages)
end
os.vexecv(os.programfile(), require_argv)
end
-- main entry
function main()
_clean_packages(option.get("packages"))
end
|
0 | repos/xmake/xmake/modules/private/xrepo | repos/xmake/xmake/modules/private/xrepo/action/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")
-- get menu options
function menu_options()
-- description
local description = "Only download the given package source archive files."
-- menu options
local options =
{
{'k', "kind", "kv", nil, "Enable static/shared library.",
values = {"static", "shared"} },
{'p', "plat", "kv", nil, "Set the given platform." },
{'a', "arch", "kv", nil, "Set the given architecture." },
{'m', "mode", "kv", nil, "Set the given mode.",
values = {"release", "debug"} },
{'f', "configs", "kv", nil, "Set the given extra package configs.",
"e.g.",
" - xrepo download -f \"runtimes='MD'\" zlib",
" - xrepo download -f \"regex=true,thread=true\" boost"},
{'j', "jobs", "kv", tostring(os.default_njob()),
"Set the number of parallel download jobs."},
{nil, "includes", "kv", nil, "Includes extra lua configuration files.",
"e.g.",
" - xrepo download -p cross --toolchain=mytool --includes='toolchain1.lua" .. path.envsep() .. "toolchain2.lua'"},
{category = "Other Configuration" },
{nil, "force", "k", nil, "Force to redownload all packages."},
{'o', "outputdir", "kv", "packages","Set the packages download output directory."},
{},
{nil, "packages", "vs", nil, "The packages list.",
"e.g.",
" - xrepo download zlib boost",
" - xrepo download /tmp/zlib.lua",
" - xrepo download -p iphoneos -a arm64 \"zlib >=1.2.0\"",
" - xrepo download -p android [--ndk=/xxx] -m debug \"pcre2 10.x\"",
" - xrepo download -p mingw [--mingw=/xxx] -k shared zlib",
" - xrepo download conan::zlib/1.2.11 vcpkg::zlib",
values = function (complete, opt) return import("private.xrepo.quick_search.completion")(complete, opt) end}
}
-- show menu options
local function show_options()
-- show usage
cprint("${bright}Usage: $${clear cyan}xrepo download [options] packages")
-- show description
print("")
print(description)
-- show options
option.show_options(options, "download")
end
return options, show_options, description
end
-- download packages
function _download_packages(packages)
-- is package configuration file? e.g. xrepo download xxx.lua
--
-- xxx.lua
-- add_requires("libpng", {system = false})
-- add_requireconfs("libpng.*", {configs = {shared = true}})
local packagefile
if type(packages) == "string" or #packages == 1 then
local filepath = table.unwrap(packages)
if type(filepath) == "string" and filepath:endswith(".lua") and os.isfile(filepath) then
packagefile = path.absolute(filepath)
end
end
-- add includes to rcfiles
local rcfiles = {}
local includes = option.get("includes")
if includes then
table.join2(rcfiles, path.splitenv(includes))
end
-- enter working project directory
local subdir = "working"
if packagefile then
subdir = subdir .. "-" .. hash.uuid(packagefile):split('-')[1]
end
local origindir = os.curdir()
local workdir = path.join(os.tmpdir(), "xrepo", subdir)
if not os.isdir(workdir) then
os.mkdir(workdir)
os.cd(workdir)
os.vrunv(os.programfile(), {"create", "-P", "."})
else
os.cd(workdir)
end
if packagefile then
assert(os.isfile("xmake.lua"), "xmake.lua not found!")
io.writefile("xmake.lua", ('includes("%s")\ntarget("test", {kind = "phony"})'):format((packagefile:gsub("\\", "/"))))
end
-- disable xmake-stats
os.setenv("XMAKE_STATS", "false")
-- do configure first
local config_argv = {"f", "-c", "--require=n"}
if option.get("diagnosis") then
table.insert(config_argv, "-vD")
end
if option.get("plat") then
table.insert(config_argv, "-p")
table.insert(config_argv, option.get("plat"))
end
if option.get("arch") then
table.insert(config_argv, "-a")
table.insert(config_argv, option.get("arch"))
end
local mode = option.get("mode")
if mode then
table.insert(config_argv, "-m")
table.insert(config_argv, mode)
end
local kind = option.get("kind")
if kind then
table.insert(config_argv, "-k")
table.insert(config_argv, kind)
end
local envs = {}
if #rcfiles > 0 then
envs.XMAKE_RCFILES = path.joinenv(rcfiles)
end
os.vrunv(os.programfile(), config_argv, {envs = envs})
-- do download
local require_argv = {"require", "--download"}
if option.get("yes") then
table.insert(require_argv, "-y")
end
if option.get("verbose") then
table.insert(require_argv, "-v")
end
if option.get("diagnosis") then
table.insert(require_argv, "-D")
end
if option.get("jobs") then
table.insert(require_argv, "-j")
table.insert(require_argv, option.get("jobs"))
end
if option.get("force") then
table.insert(require_argv, "--force")
end
local outputdir = option.get("outputdir")
if outputdir then
if not path.is_absolute(outputdir) then
outputdir = path.absolute(outputdir, os.workingdir())
end
table.insert(require_argv, "--packagedir=" .. outputdir)
end
local extra = {system = false}
if mode == "debug" then
extra.debug = true
end
if kind then
extra.configs = extra.configs or {}
extra.configs.shared = kind == "shared"
end
local configs = option.get("configs")
if configs then
extra.system = false
extra.configs = extra.configs or {}
local extra_configs, errors = ("{" .. configs .. "}"):deserialize()
if extra_configs then
table.join2(extra.configs, extra_configs)
else
raise(errors)
end
end
if not packagefile then
-- avoid overriding extra configs in add_requires/xmake.lua
if extra then
local extra_str = string.serialize(extra, {indent = false, strip = true})
table.insert(require_argv, "--extra=" .. extra_str)
end
table.join2(require_argv, packages)
end
os.vexecv(os.programfile(), require_argv, {envs = envs})
end
-- main entry
function main()
local packages = option.get("packages")
if packages then
_download_packages(packages)
else
raise("please specify the packages to be downloaded.")
end
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/utils/target.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 target.lua
--
-- imports
import("core.base.option")
-- does this flag belong to this tool?
-- @see https://github.com/xmake-io/xmake/issues/3022
--
-- e.g.
-- for all: add_cxxflags("-g")
-- only for clang: add_cxxflags("clang::-stdlib=libc++")
-- only for clang and multiple flags: add_cxxflags("-stdlib=libc++", "-DFOO", {tools = "clang"})
--
function flag_belong_to_tool(target, flag, toolinst, extraconf)
local for_this_tool = true
local flagconf = extraconf and extraconf[flag]
if type(flag) == "string" and flag:find("::", 1, true) then
for_this_tool = false
local splitinfo = flag:split("::", {plain = true})
local toolname = splitinfo[1]
if toolname == toolinst:name() then
flag = splitinfo[2]
for_this_tool = true
end
elseif flagconf and flagconf.tools then
for_this_tool = table.contains(table.wrap(flagconf.tools), toolinst:name())
end
if for_this_tool then
return flag
end
end
-- translate flags in tool
function translate_flags_in_tool(target, flagkind, flags)
local extraconf = target:extraconf(flagkind)
local sourcekind
local linkerkind
if flagkind == "cflags" then
sourcekind = "cc"
elseif flagkind == "cxxflags" or flagkind == "cxflags" then
sourcekind = "cxx"
elseif flagkind == "asflags" then
sourcekind = "as"
elseif flagkind == "cuflags" then
sourcekind = "cu"
elseif flagkind == "ldflags" or flagkind == "shflags" then
-- pass
else
raise("unknown flag kind %s", flagkind)
end
local toolinst = sourcekind and target:compiler(sourcekind) or target:linker()
-- does this flag belong to this tool?
-- @see https://github.com/xmake-io/xmake/issues/3022
--
-- e.g.
-- for all: add_cxxflags("-g")
-- only for clang: add_cxxflags("clang::-stdlib=libc++")
-- only for clang and multiple flags: add_cxxflags("-stdlib=libc++", "-DFOO", {tools = "clang"})
--
local result = {}
for _, flag in ipairs(flags) do
flag = flag_belong_to_tool(target, flag, toolinst, extraconf)
if flag then
table.insert(result, flag)
end
end
return result
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/utils/batchcmds.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 batchcmds.lua
--
-- imports
import("core.base.option")
import("core.base.object")
import("core.base.tty")
import("core.base.colors")
import("core.project.depend")
import("core.theme.theme")
import("core.tool.linker")
import("core.tool.compiler")
import("core.language.language")
import("utils.progress", {alias = "progress_utils"})
import("utils.binary.rpath", {alias = "rpath_utils"})
-- define module
local batchcmds = batchcmds or object { _init = {"_TARGET", "_CMDS", "_DEPINFO", "_tip"}}
-- show text
function _show(showtext, progress)
if option.get("verbose") then
cprint(showtext)
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(showtext)
else
tty.erase_line_to_start().cr()
local msg = showtext
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:percent()) == 100 then
print("")
_g.showing_without_scroll = false
else
_g.showing_without_scroll = true
end
io.flush()
end
end
end
-- run command: show
function _runcmd_show(cmd, opt)
local showtext = cmd.showtext
if showtext then
_show(showtext, cmd.progress)
end
end
-- run command: os.runv
function _runcmd_runv(cmd, opt)
if cmd.program then
if not opt.dryrun then
os.runv(cmd.program, cmd.argv, cmd.opt)
end
end
end
-- run command: os.vrunv
function _runcmd_vrunv(cmd, opt)
if cmd.program then
if opt.dryrun then
vprint(os.args(table.join(cmd.program, cmd.argv)))
else
os.vrunv(cmd.program, cmd.argv, cmd.opt)
end
end
end
-- run command: os.execv
function _runcmd_execv(cmd, opt)
if cmd.program then
if opt.dryrun then
print(os.args(table.join(cmd.program, cmd.argv)))
else
os.execv(cmd.program, cmd.argv, cmd.opt)
end
end
end
-- run command: os.vexecv
function _runcmd_vexecv(cmd, opt)
if cmd.program then
if opt.dryrun then
print(os.args(table.join(cmd.program, cmd.argv)))
else
os.vexecv(cmd.program, cmd.argv, cmd.opt)
end
end
end
-- run command: os.mkdir
function _runcmd_mkdir(cmd, opt)
local dir = cmd.dir
if not opt.dryrun and not os.isdir(dir) then
os.mkdir(dir)
end
end
-- run command: os.cd
function _runcmd_cd(cmd, opt)
local dir = cmd.dir
if not opt.dryrun then
os.cd(dir)
end
end
-- run command: os.rm
function _runcmd_rm(cmd, opt)
local filepath = cmd.filepath
if not opt.dryrun then
os.tryrm(filepath, opt)
end
end
-- run command: os.rmdir
function _runcmd_rmdir(cmd, opt)
local dir = cmd.dir
if not opt.dryrun and os.isdir(dir) then
os.tryrm(dir, opt)
end
end
-- run command: os.cp
function _runcmd_cp(cmd, opt)
if not opt.dryrun then
os.cp(cmd.srcpath, cmd.dstpath, opt.opt)
end
end
-- run command: os.mv
function _runcmd_mv(cmd, opt)
if not opt.dryrun then
os.mv(cmd.srcpath, cmd.dstpath, opt.opt)
end
end
-- run command: os.ln
function _runcmd_ln(cmd, opt)
if not opt.dryrun then
os.ln(cmd.srcpath, cmd.dstpath, opt.opt)
end
end
-- run command: clean rpath
function _runcmd_clean_rpath(cmd, opt)
if not opt.dryrun then
rpath_utils.clean(cmd.filepath, opt.opt)
end
end
-- run command: insert rpath
function _runcmd_insert_rpath(cmd, opt)
if not opt.dryrun then
rpath_utils.insert(cmd.filepath, cmd.rpath, opt.opt)
end
end
-- run command: remove rpath
function _runcmd_remove_rpath(cmd, opt)
if not opt.dryrun then
rpath_utils.remove(cmd.filepath, cmd.rpath, opt.opt)
end
end
-- run command: change rpath
function _runcmd_change_rpath(cmd, opt)
if not opt.dryrun then
rpath_utils.change(cmd.filepath, cmd.rpath_old, cmd.rpath_new, opt.opt)
end
end
-- run command
function _runcmd(cmd, opt)
local kind = cmd.kind
local maps = _g.maps
if not maps then
maps =
{
show = _runcmd_show,
runv = _runcmd_runv,
vrunv = _runcmd_vrunv,
execv = _runcmd_execv,
vexecv = _runcmd_vexecv,
mkdir = _runcmd_mkdir,
rmdir = _runcmd_rmdir,
cd = _runcmd_cd,
rm = _runcmd_rm,
cp = _runcmd_cp,
mv = _runcmd_mv,
ln = _runcmd_ln,
clean_rpath = _runcmd_clean_rpath,
insert_rpath = _runcmd_insert_rpath,
remove_rpath = _runcmd_remove_rpath,
change_rpath = _runcmd_change_rpath
}
_g.maps = maps
end
local script = maps[kind]
if script then
script(cmd, opt)
end
end
-- run commands
function _runcmds(cmds, opt)
for _, cmd in ipairs(cmds) do
_runcmd(cmd, opt)
end
end
-- is empty? no commands
function batchcmds:empty()
return #self:cmds() == 0
end
-- get commands
function batchcmds:cmds()
return self._CMDS
end
-- add command: os.runv
function batchcmds:runv(program, argv, opt)
table.insert(self:cmds(), {kind = "runv", program = program, argv = argv, opt = opt})
end
-- add command: os.vrunv
function batchcmds:vrunv(program, argv, opt)
table.insert(self:cmds(), {kind = "vrunv", program = program, argv = argv, opt = opt})
end
-- add command: os.execv
function batchcmds:execv(program, argv, opt)
table.insert(self:cmds(), {kind = "execv", program = program, argv = argv, opt = opt})
end
-- add command: os.vexecv
function batchcmds:vexecv(program, argv, opt)
table.insert(self:cmds(), {kind = "vexecv", program = program, argv = argv, opt = opt})
end
-- add command: compiler.compile
function batchcmds:compile(sourcefiles, objectfile, opt)
-- bind target if exists
opt = opt or {}
opt.target = self._TARGET
-- wrap path for sourcefiles, because we need to translate path for project generator
if type(sourcefiles) == "table" then
local sourcefiles_wrap = {}
for _, sourcefile in ipairs(sourcefiles) do
table.insert(sourcefiles_wrap, path(sourcefile))
end
sourcefiles = sourcefiles_wrap
else
sourcefiles = path(sourcefiles)
end
-- load compiler and get compilation command
local sourcekind = opt.sourcekind
if not sourcekind and (type(sourcefiles) == "string" or path.instance_of(sourcefiles)) then
sourcekind = language.sourcekind_of(tostring(sourcefiles))
end
local compiler_inst = compiler.load(sourcekind, opt)
local _, argv = compiler_inst:compargv(sourcefiles, path(objectfile), opt)
-- add compilation command and bind run environments of compiler
self:mkdir(path.directory(objectfile))
self:compilev(argv, table.join({sourcekind = sourcekind, compiler = compiler_inst}, opt))
end
-- add command: compiler.compilev
function batchcmds:compilev(argv, opt)
-- bind target if exists
opt = opt or {}
opt.target = self._TARGET
-- load compiler and get compilation command
local compiler_inst = opt.compiler
if not compiler_inst then
local sourcekind = opt.sourcekind
compiler_inst = compiler.load(sourcekind, opt)
end
-- we need to translate path for the project generator
local patterns = {"^([%-/]external:I)(.*)",
"^([%-/]I)(.*)",
"^([%-/]Fp)(.*)",
"^([%-/]Fd)(.*)",
"^([%-/]Yu)(.*)",
"^([%-/]FI)(.*)"}
for idx, item in ipairs(argv) do
if type(item) == "string" then
for _, pattern in ipairs(patterns) do
local _, count = item:gsub(pattern, function (prefix, value)
argv[idx] = path(value, function (p) return prefix .. p end)
end)
if count > 0 then
break
end
end
end
end
-- add compilation command and bind run environments of compiler
self:vrunv(compiler_inst:program(), argv, {envs = table.join(compiler_inst:runenvs(), opt.envs)})
end
-- add command: linker.link
function batchcmds:link(objectfiles, targetfile, opt)
-- bind target if exists
local target = self._TARGET
opt = opt or {}
opt.target = target
-- wrap path for objectfiles, because we need to translate path for project generator
local objectfiles_wrap = {}
for _, objectfile in ipairs(objectfiles) do
table.insert(objectfiles_wrap, path(objectfile))
end
objectfiles = objectfiles_wrap
-- load linker and get link command
local linker_inst = target and target:linker() or linker.load(opt.targetkind, opt.sourcekinds, opt)
local program, argv = linker_inst:linkargv(objectfiles, path(targetfile), opt)
-- we need to translate path for the project generator
local patterns = {"^([%-/]L)(.*)",
"^([%-/]F)(.*)",
"^([%-/]libpath:)(.*)"}
for idx, item in ipairs(argv) do
if type(item) == "string" then
for _, pattern in ipairs(patterns) do
local _, count = item:gsub(pattern, function (prefix, value)
argv[idx] = path(value, function (p) return prefix .. p end)
end)
if count > 0 then
break
end
end
end
end
-- add link command and bind run environments of linker
self:mkdir(path.directory(targetfile))
self:vrunv(program, argv, {envs = table.join(linker_inst:runenvs(), opt.envs)})
end
-- add command: os.mkdir
function batchcmds:mkdir(dir)
table.insert(self:cmds(), {kind = "mkdir", dir = dir})
end
-- add command: os.rmdir
function batchcmds:rmdir(dir, opt)
table.insert(self:cmds(), {kind = "rmdir", dir = dir, opt = opt})
end
-- add command: os.rm
function batchcmds:rm(filepath, opt)
table.insert(self:cmds(), {kind = "rm", filepath = filepath, opt = opt})
end
-- add command: os.cp
function batchcmds:cp(srcpath, dstpath, opt)
table.insert(self:cmds(), {kind = "cp", srcpath = srcpath, dstpath = dstpath, opt = opt})
end
-- add command: os.mv
function batchcmds:mv(srcpath, dstpath, opt)
table.insert(self:cmds(), {kind = "mv", srcpath = srcpath, dstpath = dstpath, opt = opt})
end
-- add command: os.ln
function batchcmds:ln(srcpath, dstpath, opt)
table.insert(self:cmds(), {kind = "ln", srcpath = srcpath, dstpath = dstpath, opt = opt})
end
-- add command: os.cd
function batchcmds:cd(dir, opt)
table.insert(self:cmds(), {kind = "cd", dir = dir, opt = opt})
end
-- add command: show
function batchcmds:show(format, ...)
local showtext = string.format(format, ...)
table.insert(self:cmds(), {kind = "show", showtext = showtext})
end
-- add command: clean rpath
function batchcmds:clean_rpath(filepath, opt)
table.insert(self:cmds(), {kind = "clean_rpath", filepath = filepath, opt = opt})
end
-- add command: insert rpath
function batchcmds:insert_rpath(filepath, rpath, opt)
table.insert(self:cmds(), {kind = "insert_rpath", filepath = filepath, rpath = rpath, opt = opt})
end
-- add command: remove rpath
function batchcmds:remove_rpath(filepath, rpath, opt)
table.insert(self:cmds(), {kind = "remove_rpath", filepath = filepath, rpath = rpath, opt = opt})
end
-- add command: change rpath
function batchcmds:change_rpath(filepath, rpath_old, rpath_new, opt)
table.insert(self:cmds(), {kind = "change_rpath", filepath = filepath, rpath_old = rpath_old, rpath_new = rpath_new, opt = opt})
end
-- add raw command for the specific generator or xpack format
function batchcmds:rawcmd(kind, rawstr)
table.insert(self:cmds(), {kind = kind, rawstr = rawstr})
end
-- add command: show progress
function batchcmds:show_progress(progress, format, ...)
if progress then
local showtext = progress_utils.text(progress, format, ...)
table.insert(self:cmds(), {kind = "show", showtext = showtext, progress = progress})
end
end
-- get depinfo
function batchcmds:depinfo()
return self._DEPINFO
end
-- add dependent files
function batchcmds:add_depfiles(...)
local depinfo = self._DEPINFO or {}
depinfo.files = depinfo.files or {}
table.join2(depinfo.files, ...)
self._DEPINFO = depinfo
end
-- add dependent values
function batchcmds:add_depvalues(...)
local depinfo = self._DEPINFO or {}
depinfo.values = depinfo.values or {}
table.join2(depinfo.values, ...)
self._DEPINFO = depinfo
end
-- set the last mtime of dependent files and values
function batchcmds:set_depmtime(lastmtime)
local depinfo = self._DEPINFO or {}
depinfo.lastmtime = lastmtime
self._DEPINFO = depinfo
end
-- set cache file of depend info
function batchcmds:set_depcache(cachefile)
local depinfo = self._DEPINFO or {}
depinfo.dependfile = cachefile
self._DEPINFO = depinfo
end
-- run cmds
function batchcmds:runcmds(opt)
opt = opt or {}
if self:empty() then
return
end
local depinfo = self:depinfo()
if depinfo and depinfo.files then
depend.on_changed(function ()
_runcmds(self:cmds(), opt)
end, table.join(depinfo, {dryrun = opt.dryrun, changed = opt.changed}))
else
_runcmds(self:cmds(), opt)
end
end
-- new a batch commands for rule/xx_xxcmd_xxx()
--
-- @params opt options, e.g. {target = ..}
--
function new(opt)
opt = opt or {}
return batchcmds {_TARGET = opt.target, _CMDS = {}}
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/utils/complete_helper.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 complete_helper.lua
--
-- imports
import("core.project.project")
import("core.project.config")
-- get targets
function targets()
return try
{
function ()
config.load()
return table.orderkeys(project.targets())
end
}
end
-- get runnable targets
function runable_targets(complete, opt)
return try
{
function ()
config.load()
local targets = project.targets()
local runable = {}
for k, v in table.orderpairs(targets) do
if (v:script("run") or v:is_binary()) and (not complete or k:startswith(complete)) then
table.insert(runable, k)
end
end
return runable
end
}
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/utils/complete.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, glcraft
-- @file complete.lua
--
-- imports
import("core.base.option")
import("core.base.task")
import("private.utils.completer")
function main(pos, config, ...)
local comp = completer.new(pos, config, {...})
local word = table.concat(comp:words(), " ") or ""
position = tonumber(pos) or 0
local has_space = word:endswith(" ") or position > #word
word = word:trim()
local argv = os.argv(word)
if argv[1] then
-- normailize word to remove "xmake"
if is_host("windows") and argv[1]:lower() == "xmake.exe" then
argv[1] = "xmake"
end
if argv[1] == "xmake" then
table.remove(argv, 1)
end
end
local items = {}
local tasks = task.names()
for _, name in ipairs(tasks) do
items[name] = option.taskmenu(name)
end
if has_space then
comp:complete(items, argv, "")
else
local completing = table.remove(argv)
comp:complete(items, argv, completing or "")
end
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/utils/rule_groups.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 rule_groups.lua
--
-- imports
import("core.base.option")
import("core.project.rule")
import("core.project.config")
import("core.project.project")
-- get rule
-- @note we need to get rule from target first, because we maybe will inject and replace builtin rule in target
function get_rule(target, rulename)
local ruleinst = assert(target:rule(rulename) or project.rule(rulename) or rule.rule(rulename), "unknown rule: %s", rulename)
return ruleinst
end
-- get max depth of rule
function _get_rule_max_depth(target, ruleinst, depth)
local max_depth = depth
for _, depname in ipairs(ruleinst:get("deps")) do
local dep = get_rule(target, depname)
local dep_depth = depth
if ruleinst:extraconf("deps", depname, "order") then
dep_depth = dep_depth + 1
end
local cur_depth = _get_rule_max_depth(target, dep, dep_depth)
if cur_depth > max_depth then
max_depth = cur_depth
end
end
return max_depth
end
-- build sourcebatch groups for target
function _build_sourcebatch_groups_for_target(groups, target, sourcebatches)
local group = groups[1]
for _, sourcebatch in pairs(sourcebatches) do
local rulename = assert(sourcebatch.rulename, "unknown rule for sourcebatch!")
local item = group[rulename] or {}
item.target = target
item.sourcebatch = sourcebatch
group[rulename] = item
end
end
-- build sourcebatch groups for rules
function _build_sourcebatch_groups_for_rules(groups, target, sourcebatches)
for _, sourcebatch in pairs(sourcebatches) do
local rulename = assert(sourcebatch.rulename, "unknown rule for sourcebatch!")
local ruleinst = get_rule(target, rulename)
local depth = _get_rule_max_depth(target, ruleinst, 1)
local group = groups[depth]
if group == nil then
group = {}
groups[depth] = group
end
local item = group[rulename] or {}
item.rule = ruleinst
item.sourcebatch = sourcebatch
group[rulename] = item
end
end
-- build sourcebatch groups by rule dependencies order, e.g. `add_deps("qt.ui", {order = true})`
--
-- @see https://github.com/xmake-io/xmake/issues/2814
--
function build_sourcebatch_groups(target, sourcebatches)
local groups = {{}}
_build_sourcebatch_groups_for_target(groups, target, sourcebatches)
_build_sourcebatch_groups_for_rules(groups, target, sourcebatches)
if #groups > 0 then
groups = table.reverse(groups)
end
return groups
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/utils/statistics.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 statistics.lua
--
-- imports
import("core.base.option")
import("core.base.process")
import("core.project.config")
import("core.platform.platform")
import("utils.ci.is_running", {alias = "ci_is_running"})
import("private.action.update.fetch_version")
import("private.action.require.impl.packagenv")
-- statistics is enabled?
function _is_enabled()
-- disable statistics? need not post it
local stats = (os.getenv("XMAKE_STATS") or ""):lower()
if stats == "false" then
return false
end
-- is running on ci(travis/appveyor/...)? need not post it
if ci_is_running() then
os.setenv("XMAKE_STATS", "false")
return false
end
return true
end
-- post statistics info and only post once everyday when building each project
--
-- clone the xmake-stats(only an empty repo) to update the traffic(git clones) info in github
--
-- the traffic info in github (just be approximate numbers):
--
-- Clones: the number of projects which build using xmake everyday
-- Unique cloners: the number of users everyday
--
function post()
-- enter project directory
local oldir = os.cd(os.projectdir())
-- get the project directory name
local projectname = path.basename(os.projectdir())
-- has been posted today or statistics is disable?
local outputdir = path.join(os.tmpdir(), "stats", os.date("%y%m%d"), projectname)
local markfile = outputdir .. ".mark"
if os.isdir(outputdir) or os.isfile(markfile) or not _is_enabled() then
return
end
-- mark as posted first, avoid posting it repeatly
io.writefile(markfile, "ok")
-- init argument list
local argv = {"lua", path.join(os.scriptdir(), "statistics.lua")}
for _, name in ipairs({"root", "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
-- try to post it in background
try
{
function ()
process.openv(os.programfile(), argv, {stdout = path.join(os.tmpdir(), projectname .. ".stats.log"), detach = true}):close()
end
}
-- leave project directory
os.cd(oldir)
end
-- the main function
function main()
-- in project?
if not os.isfile(os.projectfile()) then
return
end
-- load config
config.load()
-- load platform
platform.load(config.plat())
-- enter the environments of git
local oldenvs = packagenv.enter("git")
-- get the project directory name
local projectname = path.basename(os.projectdir())
-- clone the xmake-stats repo to update the traffic(git clones) info in github
local outputdir = path.join(os.tmpdir(), "stats", os.date("%y%m%d"), projectname)
if not os.isdir(outputdir) then
try
{
function ()
import("devel.git.clone")
clone("https://github.com/xmake-io/xmake-stats.git", {depth = 1, branch = "master", outputdir = outputdir})
print("post to traffic ok!")
end
}
end
-- fetch the latest version
local versionfile = path.join(os.tmpdir(), "latest_version")
if not os.isfile(versionfile) then
local fetchinfo = try { function () return fetch_version() end }
if fetchinfo then
io.save(versionfile, fetchinfo)
end
end
-- leave the environments of git
os.setenvs(oldenvs)
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/utils/bcsave.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 bcsave.lua
--
-- imports
import("core.base.option")
import("lib.luajit.bcsave")
-- the options
local options =
{
{'s', "strip", "k", false, "Strip the debug info." }
, {nil, "rootname", "kv", nil, "Set the display root path name." }
, {'o', "outputdir", "kv", nil, "Set the output directory of bitcode files." }
, {'x', "excludedirs", "kv", nil, "Set the excluded directories." }
, {nil, "sourcedir", "v", os.programdir(), "Set the directory of lua source files." }
}
-- save lua files to bitcode files in the given directory
function save(sourcedir, outputdir, opt)
-- init source directory and options
opt = opt or {}
sourcedir = path.absolute(sourcedir or os.programdir())
outputdir = outputdir and path.absolute(outputdir) or sourcedir
assert(os.isdir(sourcedir), "%s not found!", sourcedir)
-- trace
print("generating bitcode files from %s ..", sourcedir)
-- save all lua files to bitcode files
local total_lua = 0
local total_bc = 0
local pattern = path.join(sourcedir, "**.lua")
if opt.excludedirs then
pattern = pattern .. "|" .. opt.excludedirs
end
local override = (outputdir == sourcedir)
for _, luafile in ipairs(os.files(pattern)) do
-- get relative lua file path
local relativepath = path.relative(luafile, sourcedir)
-- get display path
local displaypath = opt.rootname and path.join(opt.rootname, relativepath) or relativepath
-- get bitcode file path
local bcfile = override and os.tmpfile() or path.join(outputdir, relativepath)
-- generate bitcode file
-- @note we disable cache to ensure all display paths are correct
bcsave(luafile, bcfile, {strip = opt.strip, displaypath = displaypath, nocache = true})
-- trace
local luasize = os.filesize(luafile)
local bcsize = os.filesize(bcfile)
total_lua = total_lua + luasize
total_bc = total_bc + bcsize
vprint("generating %s (%d => %d) ..", displaypath, luasize, bcsize)
-- override?
if override then
os.cp(bcfile, luafile)
end
end
-- trace
cprint("${bright}bitcode files have been generated in %s, size: %d => %d", outputdir, total_lua, total_bc)
end
-- main entry
function main(...)
-- parse arguments
local argv = {...}
local opt = option.parse(argv, options, "Save all lua files to bitcode files."
, ""
, "Usage: xmake l private.utils.bcsave [options]")
-- save bitcode files
save(opt.sourcedir, opt.outputdir, opt)
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/utils/trim_trailing_spaces.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 trim_trailing_spaces.lua
--
function main(pattern)
for _, filepath in ipairs(os.files(pattern)) do
local filedata = io.readfile(filepath)
if filedata then
local filedata2 = {}
for _, line in ipairs(filedata:split('\n', {strict = true})) do
line = line:rtrim()
table.insert(filedata2, line)
end
io.writefile(filepath, table.concat(filedata2, "\n"))
end
end
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/utils/toolchain.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 toolchain.lua
--
import("core.base.semver")
import("core.tool.linker")
import("core.tool.compiler")
import("core.language.language")
-- is the compatible with the host?
function is_compatible_with_host(name)
if is_host("linux", "macosx", "bsd") then
if name:startswith("clang") or name:startswith("gcc") or name == "llvm" then
return true
end
elseif is_host("windows") then
if name == "msvc" or name == "llvm" or name == "clang-cl" then
return true
end
end
end
-- get vs toolset version, e.g. v143, v144, ..
function get_vs_toolset_ver(vs_toolset)
local toolset_ver
if vs_toolset then
local verinfo = semver.new(vs_toolset)
toolset_ver = "v" .. verinfo:major() .. (tostring(verinfo:minor()):sub(1, 1) or "0")
-- @see https://github.com/xmake-io/xmake/pull/5176
if toolset_ver and toolset_ver == "v144" and verinfo:ge("14.40") and verinfo:lt("14.43") then
toolset_ver = "v143"
end
end
return toolset_ver
end
-- map compiler flags for package
function map_compflags_for_package(package, langkind, name, values)
-- @note we need to patch package:sourcekinds(), because it wiil be called nf_runtime for gcc/clang
package.sourcekinds = function (self)
local sourcekind = language.langkinds()[langkind]
return sourcekind
end
local flags = compiler.map_flags(langkind, name, values, {target = package})
package.sourcekinds = nil
return flags
end
-- map linker flags for package
function map_linkflags_for_package(package, targetkind, sourcekinds, name, values)
-- @note we need to patch package:sourcekinds(), because it wiil be called nf_runtime for gcc/clang
package.sourcekinds = function (self)
return sourcekinds
end
local flags = linker.map_flags(targetkind, sourcekinds, name, values, {target = package})
package.sourcekinds = nil
return flags
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/utils/executable_path.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 executable_path.lua
--
-- get executable file path
--
-- e.g.
-- "/usr/bin/xcrun -sdk macosx clang" -> "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang"
--
-- @see
-- https://github.com/xmake-io/xmake/issues/3159
-- https://github.com/xmake-io/xmake/issues/3286
-- https://github.com/xmake-io/xmake-repo/pull/1840#issuecomment-1434096993
function main(program)
local program_map = _g.program_map
if program_map == nil then
program_map = {}
_g.program_map = program_map
end
local filepath = program_map[program]
if filepath then
return filepath
end
if is_host("macosx") and program:find("xcrun -sdk", 1, true) then
local cmd = program:gsub("xcrun %-sdk (%S+) (%S+)", function (plat, cc)
return "xcrun -sdk " .. plat .. " -f " .. cc
end)
local splitinfo = cmd:split("%s")
local result = try {function() return os.iorunv(splitinfo[1], table.slice(splitinfo, 2) or {}) end}
if result then
result = result:trim()
if #result > 0 then
filepath = result
end
end
end
-- patch .exe
-- @see https://github.com/xmake-io/xmake/discussions/4781
if is_host("windows") and path.is_absolute(program) then
local program_exe = program .. ".exe"
if os.isfile(program_exe) then
program = program_exe
end
end
if not filepath then
filepath = program
end
program_map[program] = filepath
return filepath
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/utils/upgrade_vsproj.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 upgrade_vsproj.lua
--
-- imports
import("core.base.option")
import("core.tool.toolchain")
import("plugins.project.vstudio.impl.vsinfo", {rootdir = os.programdir()})
import("private.utils.toolchain", {alias = "toolchain_utils"})
-- the options
local options = {
{nil, "vs", "kv", nil, "Set the vs version. (default: latest)." }
, {nil, "vs_toolset", "kv", nil, "Set the vs toolset." }
, {nil, "vs_sdkver", "kv", nil, "Set the vs sdk version." }
, {nil, "vs_projectfiles", "vs", nil, "Set the solution or project files." }
}
-- upgrade *.sln
function _upgrade_sln(projectfile, opt)
opt = opt or {}
local msvc = opt.msvc or import("core.tool.toolchain").load("msvc")
local vs_version = opt.vs or msvc:config("vs")
local vs_info = assert(vsinfo(tonumber(vs_version)), "unknown vs version!")
io.gsub(projectfile, "Microsoft Visual Studio Solution File, Format Version %d+%.%d+",
"Microsoft Visual Studio Solution File, Format Version " .. vs_info.solution_version .. ".00")
io.gsub(projectfile, "# Visual Studio %d+", "# Visual Studio " .. vs_version)
end
-- upgrade *.vcxproj
function _upgrade_vcxproj(projectfile, opt)
opt = opt or {}
local msvc = opt.msvc or import("core.tool.toolchain").load("msvc")
local vs_version = opt.vs or msvc:config("vs")
local vs_info = assert(vsinfo(tonumber(vs_version)), "unknown vs version!")
local vs_sdkver = opt.vs_sdkver or msvc:config("vs_sdkver") or vs_info.sdk_version
local vs_toolset = toolchain_utils.get_vs_toolset_ver(opt.vs_toolset or msvc:config("vs_toolset")) or vs_info.toolset_version
local vs_toolsver = vs_info.project_version
io.gsub(projectfile, "<PlatformToolset>v%d+</PlatformToolset>",
"<PlatformToolset>" .. vs_toolset .. "</PlatformToolset>")
io.gsub(projectfile, "<WindowsTargetPlatformVersion>.*</WindowsTargetPlatformVersion>",
"<WindowsTargetPlatformVersion>" .. vs_sdkver .. "</WindowsTargetPlatformVersion>")
if vs_toolsver then
io.gsub(projectfile, "ToolsVersion=\".-\"", "ToolsVersion=\"" .. vs_toolsver .. "\"")
end
end
-- upgrade vs project file
function upgrade(projectfile, opt)
if projectfile:endswith(".sln") then
_upgrade_sln(projectfile, opt)
elseif projectfile:endswith(".vcxproj") or projectfile:endswith(".props") then
_upgrade_vcxproj(projectfile, opt)
end
end
-- https://github.com/xmake-io/xmake/issues/3871
function main(...)
local argv = {...}
local opt = option.parse(argv, options, "Upgrade all the vs project files."
, ""
, "Usage: xmake l private.utils.upgrade_vsproj [options]")
for _, projectfile in ipairs(opt.vs_projectfiles) do
upgrade(projectfile, opt)
end
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/utils/completer.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, glcraft
-- @file complete.lua
--
-- imports
import("core.base.option")
import("core.base.cli")
local completer = {}
function completer.new(pos, config, words)
local instance = table.inherit(completer)
instance._POSITION = 0
instance._CONFIG = {}
instance._WORDS = {}
instance._DEFAULT_COMMAND = ""
instance:set_config(config)
instance:set_position(pos)
instance:set_words(words)
return instance
end
function completer:_print_candidate(candidate)
if candidate.value and #candidate.value ~= 0 then
printf(candidate.value)
if not self:config("nospace") and candidate.is_complete then
print(" ")
else
print("")
end
end
end
function completer:_print_candidates(candidates)
if self:config("json") then
import("core.base.json")
print(json.encode(candidates))
else
for _, v in ipairs(candidates) do
self:_print_candidate(v)
end
end
end
function completer:_find_candidates(candidates, find)
if type(candidates) ~= 'table' then
return {}
end
local has_candidate = false
local results = table.new(#candidates, 0)
-- find candidate starts with find str
for _, v in ipairs(candidates) do
if tostring(v):startswith(find) then
table.insert(results, v)
has_candidate = true
end
end
-- stop searching if found any
if has_candidate then
return results
end
-- find candidate contains find str
for _, v in ipairs(candidates) do
if tostring(v):find(find, 1, true) then
table.insert(results, v)
end
end
return results
end
function completer:_complete_item(items, name)
local found_candidates = {}
for _, v in ipairs(self:_find_candidates(table.keys(items), name)) do
table.insert(found_candidates, { value = v, is_complete = true, description = items[v].description })
end
self:_print_candidates(found_candidates)
return #found_candidates > 0
end
-- complete values of kv
function completer:_complete_option_kv_v(options, current, completing, name, value)
-- find completion option
local opt
for _, v in ipairs(options) do
if v[3] == "kv" and (v[1] == name or v[2] == name) then
opt = v
break
end
end
if not opt then
return false
end
-- show candidates of values
local values = opt.values
if type(values) == "function" then
values = values(value, current)
end
if values == nil and type(opt[4]) == "boolean" then
values = { "yes", "no" }
-- ignore existing input
value = ""
end
-- match values starts with value first
local found_candidates = {}
local nokey = self:config("nokey")
for _, v in ipairs(self:_find_candidates(values, value)) do
if nokey then
table.insert(found_candidates, { value = v, is_complete = true })
else
table.insert(found_candidates, { value = format("--%s=%s", name, v), is_complete = true })
end
end
self:_print_candidates(found_candidates)
-- whether any candidates has been found, finish complete since we don't have more info
return true
end
-- complete keys of kv
function completer:_complete_option_kv_k(options, current, completing, name)
local opcandi = table.new(0, 10)
for _, opt in ipairs(options) do
if opt[2] and current[opt[2]] == nil and (opt[3] == "kv" or opt[3] == "k") then
opcandi[opt[2]] = opt
end
end
local found_candidates = {}
for _, k in ipairs(self:_find_candidates((table.keys(opcandi)), name)) do
local opt = opcandi[k]
local name = format((opt[3] == "k") and "--%s" or "--%s=", opt[2])
table.insert(found_candidates, { value = name, description = opt[5], is_complete = (opt[3] == "k") })
end
self:_print_candidates(found_candidates)
return true
end
function completer:_complete_option_kv(options, current, completing)
local name, value
if completing == "-" or completing == "--" then
name = ""
elseif completing:startswith("--") then
local parg = cli.parsev({completing})[1]
if parg.type == "option" then
name, value = parg.key, parg.value
elseif parg.type == "flag" then
name = parg.key
end
elseif completing:startswith("-") then
-- search full names only
return true
end
if value then
-- complete values
return self:_complete_option_kv_v(options, current, completing, name, value)
else
-- complete keys
return self:_complete_option_kv_k(options, current, completing, name)
end
end
-- complete options v and vs
function completer:_complete_option_v(options, current, completing)
-- find completion option
local opt
local optvs
for _, v in ipairs(options) do
if v[3] == "v" and current[v[2] or v[1]] == nil then
opt = v
end
if v[3] == "vs" and not optvs then
optvs = v
end
end
-- transform values array to candidates array
local function _transform_values(values)
local candidates = {}
if #values > 0 and type(values[1]) == "string" then
for _, v in ipairs(values) do
if v:startswith(completing) then
table.insert(candidates, { value = v, is_complete = true })
end
end
else
for _, v in ipairs(values) do
v.is_complete = true
table.insert(candidates, v)
end
end
return candidates
end
-- filter candidates with completing
local function _filter_candidates(candidates)
local found_candidates = {}
for _, v in ipairs(candidates) do
if v.value:find(completing, 1, true) then
v.is_complete = true
table.insert(found_candidates, v)
end
end
return found_candidates
end
-- get completion candidates from values option
local function _values_into_candidates(values)
if values == nil then
return {}
elseif type(values) == "function" then
-- no need to filter result of values() as we consider values() already filter candidates
return _transform_values(values(completing, current))
else
return _filter_candidates(_transform_values(values))
end
end
-- get candidates from values option
local found_candidates = {}
if opt then
found_candidates = _values_into_candidates(opt.values)
end
-- get candidates from values option
if optvs and #found_candidates == 0 then
found_candidates = _values_into_candidates(optvs.values)
end
self:_print_candidates(found_candidates)
return #found_candidates > 0
end
function completer:_complete_option(options, segs, completing)
local current_options = try {
function()
return option.raw_parse(segs, options, { populate_defaults = false, allow_unknown = true })
end
}
-- current options is invalid
if not current_options then return false end
-- current context is wrong
if not self:config("reenter") and (current_options.file or current_options.project) then
local args = {"lua", "private.utils.complete", tostring(position), table.concat(self._CONFIG, "-") .. "-reenter", table.unpack(raw_words) }
if current_options.file then
table.insert(args, 2, "--file=" .. current_options.file)
end
if current_options.project then
table.insert(args, 2, "--project=" .. current_options.project)
end
os.execv(os.programfile(), args)
return true
end
if completing:startswith("-") then
return self:_complete_option_kv(options, current_options, completing)
else
return self:_complete_option_v(options, current_options, completing)
end
end
function completer:complete(items, argv, completing)
local shortnames = table.new(0, 10)
for v, menu in pairs(items) do
if menu.shortname then
shortnames[menu.shortname] = v
end
end
if #argv == 0 then
if self:_complete_item(items, completing) then return end
end
local item_name = self:default_command()
if argv[1] and not argv[1]:startswith("-") then
item_name = table.remove(argv, 1)
end
if shortnames[item_name] then
item_name = shortnames[item_name]
end
local options
if items[item_name] then
options = items[item_name].options
end
if options then
self:_complete_option(options, argv, completing)
end
end
function completer:set_words(raw_words)
self._WORDS = raw_words
end
function completer:words()
return self._WORDS
end
function completer:set_position(pos)
self._POSITION = pos
end
function completer:position()
return self._POSITION
end
function completer:set_default_command(command)
self._DEFAULT_COMMAND = command
end
function completer:default_command()
return self._DEFAULT_COMMAND
end
function completer:set_config(config)
self._CONFIG = (config or ""):trim():split("-")
end
function completer:config(key)
return table.find_first(self._CONFIG, key)
end
function new(...)
return completer.new(...)
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/utils/bin2c.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 bin2c.lua
--
-- imports
import("core.base.bytes")
import("core.base.option")
local options = {
{'w', "linewidth", "kv", nil, "Set the line width"},
{nil, "nozeroend", "k", false, "Disable to patch zero terminating character"},
{'i', "binarypath", "kv", nil, "Set the binary file path."},
{'o', "outputpath", "kv", nil, "Set the output file path."}
}
function _do_dump(binarydata, outputfile, opt)
local i = 0
local n = 147
local p = 0
local e = binarydata:size()
local line = nil
local linewidth = opt.linewidth or 0x20
local first = true
while p < e do
line = ""
if p + linewidth <= e then
for i = 0, linewidth - 1 do
if first then
first = false
line = line .. " "
else
line = line .. ","
end
line = line .. string.format(" 0x%02X", binarydata[p + i + 1])
end
outputfile:print(line)
p = p + linewidth
elseif p < e then
local left = e - p
for i = 0, left - 1 do
if first then
first = false
line = line .. " "
else
line = line .. ","
end
line = line .. string.format(" 0x%02X", binarydata[p + i + 1])
end
outputfile:print(line)
p = p + left
else
break
end
end
end
function _do_bin2c(binarypath, outputpath, opt)
-- init source directory and options
opt = opt or {}
binarypath = path.absolute(binarypath)
outputpath = path.absolute(outputpath)
assert(os.isfile(binarypath), "%s not found!", binarypath)
-- trace
print("generating code data file from %s ..", binarypath)
-- do dump
local binarydata = bytes(io.readfile(binarypath, {encoding = "binary"}))
local outputfile = io.open(outputpath, 'w')
if outputfile then
if not opt.nozeroend then
binarydata = binarydata .. bytes('\0')
end
_do_dump(binarydata, outputfile, opt)
outputfile:close()
end
-- trace
cprint("${bright}%s generated!", outputpath)
end
-- main entry
function main(...)
-- parse arguments
local argv = {...}
local opt = option.parse(argv, options, "Print c/c++ code files from the given binary file."
, ""
, "Usage: xmake l private.utils.bin2c [options]")
-- do bin2c
_do_bin2c(opt.binarypath, opt.outputpath, opt)
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/diagnosis/dump_buildjobs.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 dump_buildjobs.lua
--
-- imports
import("core.project.config")
import("actions.build.build", {rootdir = os.programdir()})
-- dump the build jobs, e.g. xmake l private.diagnosis.dump_buildjobs [targetname]
function main(targetname)
config.load()
print(build.get_batchjobs(targetname))
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/diagnosis/dump_targets.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 dump_targets.lua
--
-- imports
import("core.base.hashset")
import("core.project.config")
import("core.project.project")
-- get targets
function _get_targets(targetname)
-- get targets
local targets = {}
if targetname then
table.insert(targets, project.target(targetname))
else
for _, target in pairs(project.targets()) do
table.insert(targets, target)
end
end
return targets
end
-- dump the build jobs, e.g. xmake l private.diagnosis.dump_buildjobs [targetname]
function main(targetname)
config.load()
for _, target in ipairs(_get_targets(targetname)) do
cprint("${bright}target(%s):${clear} %s", target:name(), target:kind())
local deps = target:get("deps")
if deps then
cprint(" ${color.dump.string}deps:")
cprint(" ${yellow}->${clear} %s", table.concat(table.wrap(deps), ", "))
end
local options = {}
for _, optname in ipairs(target:get("options")) do
if not optname:startswith("__") then
table.insert(options, optname)
end
end
if #options > 0 then
cprint(" ${color.dump.string}options:")
cprint(" ${yellow}->${clear} %s", table.concat(table.wrap(options), ", "))
end
local packages = target:get("packages")
if packages then
cprint(" ${color.dump.string}packages:")
cprint(" ${yellow}->${clear} %s", table.concat(table.wrap(packages), ", "))
end
local rules = target:get("rules")
if rules then
cprint(" ${color.dump.string}rules:")
cprint(" ${yellow}->${clear} %s", table.concat(table.wrap(rules), ", "))
end
print("")
end
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/tools/vstool.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 vstool.lua
--
-- quietly run command with arguments list
function runv(program, argv, opt)
-- init options
opt = opt or {}
-- if has VS_BINARY_OUTPUT dont enable unicode output
local envs = opt.envs or {}
if envs.VS_BINARY_OUTPUT then
return os.runv(program, argv, opt)
end
-- make temporary output and error file
local outpath = os.tmpfile()
local errpath = os.tmpfile()
local outfile = io.open(outpath, 'w')
-- enable unicode output for vs toolchains, e.g. cl.exe, link.exe and etc.
-- @see https://github.com/xmake-io/xmake/issues/528
opt.envs = table.join(envs, {VS_UNICODE_OUTPUT = outfile:rawfd()})
-- execute it
local ok, syserrors = os.execv(program, argv, table.join(opt, {try = true, stdout = outfile, stderr = errpath}))
-- close outfile first
outfile:close()
-- failed?
if ok ~= 0 then
-- read errors
local outdata = os.isfile(outpath) and io.readfile(outpath, {encoding = "utf16le"}) or nil
local errdata = os.isfile(errpath) and io.readfile(errpath) or nil
local errors = errdata or ""
if #errors:trim() == 0 then
errors = outdata or ""
end
-- make the default errors
if not errors or #errors == 0 then
-- get command
local cmd = program
if argv then
cmd = cmd .. " " .. os.args(argv)
end
-- get errors
if ok ~= nil then
errors = string.format("vstool.runv(%s) failed(%d)", cmd, ok)
else
errors = string.format("vstool.runv(%s), %s", cmd, syserrors and syserrors or "unknown reason")
end
end
-- remove the files
os.tryrm(outpath)
os.tryrm(errpath)
-- raise errors
os.raise({errors = errors, stderr = errdata, stdout = outdata})
end
-- remove the files
os.tryrm(outpath)
os.tryrm(errpath)
end
-- run command and return output and error data
function iorunv(program, argv, opt)
-- init options
opt = opt or {}
-- if has VS_BINARY_OUTPUT dont enable unicode output
local envs = opt.envs or {}
if envs.VS_BINARY_OUTPUT then
return os.runv(program, argv, opt)
end
-- make temporary output and error file
local outpath = os.tmpfile()
local errpath = os.tmpfile()
local outfile = io.open(outpath, 'w')
-- enable unicode output for vs toolchains, e.g. cl.exe, link.exe and etc.
-- @see https://github.com/xmake-io/xmake/issues/528
opt.envs = table.join(envs, {VS_UNICODE_OUTPUT = outfile:rawfd()})
-- run command
local ok, syserrors = os.execv(program, argv, table.join(opt, {try = true, stdout = outfile, stderr = errpath}))
-- get output and error data
outfile:close()
local outdata = os.isfile(outpath) and io.readfile(outpath, {encoding = "utf16le"}) or nil
local errdata = os.isfile(errpath) and io.readfile(errpath) or nil
-- remove the temporary output and error file
os.tryrm(outpath)
os.tryrm(errpath)
-- failed?
if ok ~= 0 then
-- get errors
local errors = errdata or ""
if #errors:trim() == 0 then
errors = outdata or ""
end
-- make the default errors
if not errors or #errors == 0 then
-- get command
local cmd = program
if argv then
cmd = cmd .. " " .. os.args(argv)
end
-- get errors
if ok ~= nil then
errors = string.format("vstool.iorunv(%s) failed(%d)", cmd, ok)
else
errors = string.format("vstool.iorunv(%s), %s", cmd, syserrors and syserrors or "unknown reason")
end
end
-- raise errors
os.raise({errors = errors, stderr = errdata, stdout = outdata})
end
return outdata, errdata
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/tools/ccache.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 ccache.lua
--
-- imports
import("core.project.config")
import("lib.detect.find_tool")
-- get ccache tool
function _ccache()
local ccache = _g.ccache
if ccache == nil and config.get("ccache") then
ccache = find_tool("ccache")
_g.ccache = ccache or false
end
return ccache or nil
end
-- exists ccache?
function exists()
return _ccache() ~= nil
end
-- uses ccache to wrap the program and arguments
--
-- e.g. ccache program argv
--
function cmdargv(program, argv)
-- uses ccache?
local ccache = _ccache()
if ccache then
-- parse the filename and arguments, e.g. "xcrun -sdk macosx clang"
if not os.isexec(program) then
argv = table.join(program:split("%s"), argv)
else
table.insert(argv, 1, program)
end
return ccache.program, argv
end
return program, argv
end
|
0 | repos/xmake/xmake/modules/private | repos/xmake/xmake/modules/private/tools/codesign.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 codesign.lua
--
-- imports
import("lib.detect.find_tool")
import("core.cache.global_detectcache")
-- get mobile provision name
function _get_mobile_provision_name(provision)
local p = provision:find("<key>Name</key>", 1, true)
if p then
local e = provision:find("</string>", p, true)
if e then
return provision:sub(p, e + 9):match("<string>(.*)</string>")
end
end
end
-- get mobile provision entitlements
function _get_mobile_provision_entitlements(provision)
local p = provision:find("<key>Entitlements</key>", 1, true)
if p then
local e = provision:find("</dict>", p, true)
if e then
return provision:sub(p, e + 7):match("(<dict>.*</dict>)")
end
end
end
-- get codesign identities
function codesign_identities()
local identities = global_detectcache:get2("codesign", "identities")
local lastime = global_detectcache:get2("codesign", "lastime")
if type(lastime) == "number" and os.time() - lastime > 3 * 24 * 3600 then -- > 3 days
identities = nil
end
if identities == nil then
identities = {}
local results = try { function() return os.iorun("/usr/bin/security find-identity") end }
if results then
local splitinfo = results:split("Valid identities only", {plain = true})
if splitinfo and #splitinfo > 1 then
results = splitinfo[2]
end
end
if not results then
-- it may be slower
results = try { function() return os.iorun("/usr/bin/security find-identity -v -p codesigning") end }
end
if results then
for _, line in ipairs(results:split('\n', {plain = true})) do
local sign, identity = line:match("%) (%w+) \"(.+)\"")
if sign and identity then
identities[identity] = sign
end
end
end
global_detectcache:set2("codesign", "identities", identities or false)
global_detectcache:set2("codesign", "lastime", os.time())
global_detectcache:save()
end
return identities or nil
end
-- get provision profiles only for mobile
function mobile_provisions()
local mobile_provisions = global_detectcache:get2("codesign", "mobile_provisions")
local lastime = global_detectcache:get2("codesign", "lastime")
if type(lastime) == "number" and os.time() - lastime > 3 * 24 * 3600 then -- > 3 days
mobile_provisions = nil
end
if mobile_provisions == nil then
mobile_provisions = {}
local files = os.files("~/Library/MobileDevice/Provisioning Profiles/*.mobileprovision")
for _, file in ipairs(files) do
local results = try { function() return os.iorunv("/usr/bin/security", {"cms", "-D", "-i", file}) end }
if results then
local name = _get_mobile_provision_name(results)
if name then
mobile_provisions[name] = results
end
end
end
global_detectcache:set2("codesign", "mobile_provisions", mobile_provisions or false)
global_detectcache:set2("codesign", "lastime", os.time())
global_detectcache:save()
end
return mobile_provisions or nil
end
-- dump all information of codesign
function dump()
-- only for macosx
assert(is_host("macosx"), "codesign: only support for macOS!")
-- do dump
print("==================================== codesign identities ====================================")
print(codesign_identities())
print("===================================== mobile provisions =====================================")
print(mobile_provisions())
end
-- remove signature
function unsign(programdir)
-- only for macosx
assert(is_host("macosx"), "codesign: only support for macOS!")
-- get codesign
local codesign = find_tool("codesign")
if not codesign then
return
end
-- remove signature
os.vrunv(codesign.program, {"--remove-signature", programdir})
end
-- main entry
function main (programdir, codesign_identity, mobile_provision, opt)
-- only for macosx
opt = opt or {}
assert(is_host("macosx"), "codesign: only support for macOS!")
-- get codesign
local codesign = find_tool("codesign")
if not codesign then
return
end
-- get codesign_allocate
local codesign_allocate
local xcode_sdkdir = get_config("xcode")
if xcode_sdkdir then
codesign_allocate = path.join(xcode_sdkdir, "Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate")
end
-- get codesign
local sign = "-"
if codesign_identity then -- we will uses sign/'-' if be false for `xmake f --xcode_codesign_identity=n`
local identities = codesign_identities()
if identities then
sign = identities[codesign_identity]
assert(sign, "codesign: invalid sign identity(%s)!", codesign_identity)
end
end
-- get entitlements for mobile
local entitlements
if codesign_identity and mobile_provision then
local provisions = mobile_provisions()
if provisions then
mobile_provision = provisions[mobile_provision]
if mobile_provision then
local entitlements_data = _get_mobile_provision_entitlements(mobile_provision)
if entitlements_data then
entitlements = os.tmpfile() .. ".plist"
io.writefile(entitlements, string.format([[<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
%s
</plist>
]], entitlements_data))
end
end
end
end
-- do sign
local argv = {"--force", "--timestamp=none"}
if opt.deep then
table.insert(argv, "--deep")
end
table.insert(argv, "--sign")
table.insert(argv, sign)
if entitlements then
table.insert(argv, "--entitlements")
table.insert(argv, entitlements)
end
table.insert(argv, programdir)
os.vrunv(codesign.program, argv, {envs = {CODESIGN_ALLOCATE = codesign_allocate}})
if entitlements then
os.tryrm(entitlements)
end
end
|
0 | repos/xmake/xmake/modules/private/tools | repos/xmake/xmake/modules/private/tools/armcc/parse_deps.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 smalli
-- @file parse_deps_armcc.lua
--
-- imports
import("core.project.project")
import("core.base.hashset")
-- a placeholder for spaces in path
local space_placeholder = "\001"
-- normailize path of a dependecy
function _normailize_dep(dep, projectdir)
if path.is_absolute(dep) then
dep = path.translate(dep)
else
dep = path.absolute(dep, projectdir)
end
if dep:startswith(projectdir) then
return path.relative(dep, projectdir)
else
return dep
end
end
-- parse depsfiles from string
--
-- parse_deps(io.readfile(depfile, {continuation = "\\"}))
--
-- eg.
-- build\\.objs\\apps\\cross\\cortex-m3\\release\\APPS\\main.c.o: APPS\\main.c\
-- build\\.objs\\apps\\cross\\cortex-m3\\release\\APPS\\main.c.o: D:\\Keil533\\ARM\\ARMCC\\bin\\..\\include\\stdarg.h\
-- build\\.objs\\apps\\cross\\cortex-m3\\release\\APPS\\main.c.o: D:\\Keil533\\ARM\\ARMCC\\bin\\..\\include\\stdio.h\
-- build\\.objs\\apps\\cross\\cortex-m3\\release\\APPS\\main.c.o: D:\\Keil533\\ARM\\ARMCC\\bin\\..\\include\\string.h\
-- build\\.objs\\apps\\cross\\cortex-m3\\release\\APPS\\main.c.o: APPS\\main.h\
--
--
function main(depsdata)
local block = 0
local results = hashset.new()
local projectdir = os.projectdir()
local line = depsdata:rtrim() -- maybe there will be an empty newline at the end. so we trim it first
local plain = {plain = true}
line = line:replace("\\ ", space_placeholder, plain)
for _, includefile in ipairs(line:split('\n', plain)) do
if is_host("windows") and includefile:match("^%w\\:") then
includefile = includefile:replace("\\:", ":", plain)
end
includefile = includefile:replace(space_placeholder, ' ', plain)
local splitinfo = includefile:split(".o:", {plain = true})
if #splitinfo < 2 then
splitinfo = includefile:split(".obj:", {plain = true})
end
includefile = splitinfo[2]
if includefile then
includefile = includefile:replace(' ', '', plain)
if #includefile > 0 then
includefile = _normailize_dep(includefile, projectdir)
if includefile then
results:insert(includefile)
end
end
end
end
return results:to_array()
end
|
0 | repos/xmake/xmake/modules/private/tools | repos/xmake/xmake/modules/private/tools/cl/parse_deps_json.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 parse_deps_json.lua
--
-- imports
import("core.project.project")
import("core.base.hashset")
import("core.base.json")
import("core.tool.toolchain")
-- get $VCInstallDir
function _VCInstallDir()
local VCInstallDir = _g.VCInstallDir
if not VCInstallDir then
local msvc = toolchain.load("msvc")
if msvc then
local vcvars = msvc:config("vcvars")
if vcvars and vcvars.VCInstallDir then
VCInstallDir = vcvars.VCInstallDir:lower() -- @note we need lower case for json/deps
_g.VCInstallDir = VCInstallDir
end
end
end
return VCInstallDir
end
-- get $WindowsSdkDir
function _WindowsSdkDir()
local WindowsSdkDir = _g.WindowsSdkDir
if not WindowsSdkDir then
local msvc = toolchain.load("msvc")
if msvc then
local vcvars = msvc:config("vcvars")
if vcvars and vcvars.WindowsSdkDir then
WindowsSdkDir = vcvars.WindowsSdkDir:lower() -- @note we need lower case for json/deps
_g.WindowsSdkDir = WindowsSdkDir
end
end
end
return WindowsSdkDir
end
-- normailize path of a dependecy
function _normailize_dep(dep, projectdir)
if path.is_absolute(dep) then
dep = path.translate(dep)
else
dep = path.absolute(dep, projectdir)
end
dep = dep:lower()
local VCInstallDir = _VCInstallDir()
local WindowsSdkDir = _WindowsSdkDir()
if (VCInstallDir and dep:startswith(VCInstallDir)) or (WindowsSdkDir and dep:startswith(WindowsSdkDir)) then
-- we ignore headerfiles in vc install directory
return
end
if dep:startswith(projectdir) then
return path.relative(dep, projectdir)
else
-- we also need to check header files outside project
-- https://github.com/xmake-io/xmake/issues/1154
return dep
end
end
-- parse depsfiles from string
--
--[[
{
"Version": "1.2",
"Data": {
"Source": "c:\users\ruki\desktop\user_headerunit\src\main.cpp",
"ProvidedModule": "",
"Includes": [],
"ImportedModules": [
{
"Name": "hello",
"BMI": "c:\users\ruki\desktop\user_headerunit\src\hello.ifc"
}
],
"ImportedHeaderUnits": [
{
"Header": "c:\users\ruki\desktop\user_headerunit\src\header.hpp",
"BMI": "c:\users\ruki\desktop\user_headerunit\src\header.hpp.ifc"
}
]
}
}]]
function main(depsdata)
-- decode json data first
depsdata = json.decode(depsdata)
-- get includes
local data
if depsdata then
data = depsdata.Data
end
if data then
includes = data.Includes
for _, item in ipairs(data.ImportedModules) do
local bmifile = item.BMI
if bmifile then
includes = includes or {}
table.insert(includes, bmifile)
end
end
for _, item in ipairs(data.ImportedHeaderUnits) do
local bmifile = item.BMI
if bmifile then
includes = includes or {}
table.insert(includes, bmifile)
end
end
end
-- translate it
local results = hashset.new()
local projectdir = os.projectdir():lower() -- we need to generate lower string, because json values are all lower
for _, includefile in ipairs(includes) do
includefile = _normailize_dep(includefile, projectdir)
if includefile then
results:insert(includefile)
end
end
return results:to_array()
end
|
0 | repos/xmake/xmake/modules/private/tools | repos/xmake/xmake/modules/private/tools/cl/parse_deps.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 parse_deps.lua
--
-- imports
import("core.project.project")
import("core.base.hashset")
import("parse_include")
import("core.tool.toolchain")
-- get $VCInstallDir
function _VCInstallDir()
local VCInstallDir = _g.VCInstallDir
if not VCInstallDir then
local msvc = toolchain.load("msvc")
if msvc then
local vcvars = msvc:config("vcvars")
if vcvars and vcvars.VCInstallDir then
VCInstallDir = vcvars.VCInstallDir
_g.VCInstallDir = VCInstallDir
end
end
end
return VCInstallDir
end
-- get $WindowsSdkDir
function _WindowsSdkDir()
local WindowsSdkDir = _g.WindowsSdkDir
if not WindowsSdkDir then
local msvc = toolchain.load("msvc")
if msvc then
local vcvars = msvc:config("vcvars")
if vcvars and vcvars.WindowsSdkDir then
WindowsSdkDir = vcvars.WindowsSdkDir
_g.WindowsSdkDir = WindowsSdkDir
end
end
end
return WindowsSdkDir
end
-- normailize path of a dependecy
function _normailize_dep(dep, projectdir)
if path.is_absolute(dep) then
dep = path.translate(dep)
else
dep = path.absolute(dep, projectdir)
end
local VCInstallDir = _VCInstallDir()
local WindowsSdkDir = _WindowsSdkDir()
if (VCInstallDir and dep:startswith(VCInstallDir)) or (WindowsSdkDir and dep:startswith(WindowsSdkDir)) then
-- we ignore headerfiles in vc install directory
return
end
if dep:startswith(projectdir) then
return path.relative(dep, projectdir)
else
-- we also need to check header files outside project
-- https://github.com/xmake-io/xmake/issues/1154
return dep
end
end
-- parse depsfiles from string
function main(depsdata)
local results = hashset.new()
for _, line in ipairs(depsdata:split("\n", {plain = true})) do
local includefile = parse_include(line:trim())
if includefile then
includefile = _normailize_dep(includefile, os.projectdir())
if includefile then
results:insert(includefile)
end
end
end
return results:to_array()
end
|
0 | repos/xmake/xmake/modules/private/tools | repos/xmake/xmake/modules/private/tools/cl/parse_include.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 parse_include.lua
--
-- imports
import("core.project.project")
import("core.base.hashset")
import("core.tool.toolchain")
import("core.cache.detectcache")
import("lib.detect.find_tool")
import("private.tools.vstool")
-- probe include note prefix from cl
function probe_include_note_from_cl()
local key = "cldeps.parse_include.note"
local note = detectcache:get(key)
if not note then
local cl = find_tool("cl")
if cl then
local projectdir = os.tmpfile() .. ".cldeps"
local sourcefile = path.join(projectdir, "main.c")
local headerfile = path.join(projectdir, "foo.h")
local objectfile = sourcefile .. ".obj"
local outdata = try { function()
local runenvs = toolchain.load("msvc"):runenvs()
local argv = {"-nologo", "-showIncludes", "-c", "-Fo" .. objectfile, sourcefile}
io.writefile(headerfile, "\n")
io.writefile(sourcefile, [[
#include "foo.h"
int main (int argc, char** argv) {
return 0;
}
]])
return vstool.iorunv(cl.program, argv, {envs = runenvs, curdir = projectdir})
end}
if outdata then
for _, line in ipairs(outdata:split('\n', {plain = true})) do
note = line:match("^(.-:.-: )")
if note then
break
end
end
end
os.tryrm(projectdir)
end
detectcache:set(key, note)
detectcache:save()
end
return note
end
-- get include notes prefix, e.g. "Note: including file: "
--
-- @note we cannot get better solution to distinguish between `includes` and `error infos`
--
function get_include_notes()
local notes = _g.notes
if not notes then
notes = {}
local note = probe_include_note_from_cl()
if note then
table.insert(notes, note)
end
table.join2(notes, {
"Note: including file: ", -- en
"注意: 包含文件: ", -- zh
"Remarque : inclusion du fichier : ", -- fr
"メモ: インクルード ファイル: " -- jp
})
_g.notes = notes
end
return notes
end
-- main entry
function main(line)
local notes = get_include_notes()
for idx, note in ipairs(notes) do
if line:startswith(note) then
-- optimization: move this note to head
if idx ~= 1 then
table.insert(notes, 1, note)
end
return line:sub(#note):trim()
end
end
end
|
0 | repos/xmake/xmake/modules/private/tools | repos/xmake/xmake/modules/private/tools/gcc/parse_deps.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 parse_deps.lua
--
-- imports
import("core.project.config")
import("core.project.project")
import("core.base.hashset")
-- a placeholder for spaces in path
local space_placeholder = "\001"
-- normailize path of a dependecy
function _normailize_dep(dep, projectdir)
-- escape characters, e.g. \#Qt.Widget_pch.h -> #Qt.Widget_pch.h
-- @see https://github.com/xmake-io/xmake/issues/4134
-- https://github.com/xmake-io/xmake/issues/4273
if not is_host("windows") then
dep = dep:gsub("\\(.)", "%1")
end
if path.is_absolute(dep) then
dep = path.translate(dep)
else
dep = path.absolute(dep, projectdir)
end
if dep:startswith(projectdir) then
return path.relative(dep, projectdir)
else
-- we also need to check header files outside project
-- https://github.com/xmake-io/xmake/issues/1154
return dep
end
end
-- load module mapper
function _load_module_mapper(target)
local mapper = {}
local mapperfile = path.join(config.buildir(), target:name(), "mapper.txt")
for line in io.lines(mapperfile) do
local moduleinfo = line:split(" ", {plain = true})
if #moduleinfo == 2 then
mapper[moduleinfo[1]] = moduleinfo[2]
end
end
return mapper
end
-- parse depsfiles from string
--
-- parse_deps(io.readfile(depfile, {continuation = "\\"}))
--
-- eg.
-- strcpy.o: src/tbox/libc/string/strcpy.c src/tbox/libc/string/string.h \
-- src/tbox/libc/string/prefix.h src/tbox/libc/string/../prefix.h \
-- src/tbox/libc/string/../../prefix.h \
-- src/tbox/libc/string/../../prefix/prefix.h \
-- src/tbox/libc/string/../../prefix/config.h \
-- src/tbox/libc/string/../../prefix/../config.h \
-- build/iphoneos/x86_64/release/tbox.config.h \
--
-- with c++ modules (gcc):
-- build/.objs/dependence/linux/x86_64/release/src/foo.mpp.o: src/foo.mpp\
-- build/.objs/dependence/linux/x86_64/release/src/foo.mpp.o gcm.cache/foo.gcm: bar.c++m cat.c++m\
-- foo.c++m: gcm.cache/foo.gcm\
-- .PHONY: foo.c++m\
-- gcm.cache/foo.gcm:| build/.objs/dependence/linux/x86_64/release/src/foo.mpp.o\
-- CXX_IMPORTS += bar.c++m cat.c++m\
--
function main(depsdata, opt)
-- we assume there is only one valid line
local block = 0
local results = hashset.new()
local projectdir = os.projectdir()
local line = depsdata:rtrim() -- maybe there will be an empty newline at the end. so we trim it first
local plain = {plain = true}
line = line:replace("\\ ", space_placeholder, plain)
for _, includefile in ipairs(line:split(' ', plain)) do -- it will trim all internal spaces without `{strict = true}`
-- some gcc toolchains will some invalid paths (e.g. `d\:\xxx`), we need to fix it
-- https://github.com/xmake-io/xmake/issues/1196
if is_host("windows") and includefile:match("^%w\\:") then
includefile = includefile:replace("\\:", ":", plain)
end
if includefile:endswith(":") then -- ignore "xxx.o:" prefix
block = block + 1
if block > 1 then
-- skip other `xxx.o:` block
break
end
else
includefile = includefile:replace(space_placeholder, ' ', plain)
includefile = includefile:split("\n", plain)[1]
if #includefile > 0 then
includefile = _normailize_dep(includefile, projectdir)
if includefile then
results:insert(includefile)
end
end
end
end
-- translate .c++m module file path
-- with c++ modules (gcc):
-- CXX_IMPORTS += bar.c++m cat.c++m\
--
-- @see https://github.com/xmake-io/xmake/issues/3000
-- https://github.com/xmake-io/xmake/issues/4215
local target = opt and opt.target
if target and line:find("CXX_IMPORTS += ", 1, true) then
local mapper = _load_module_mapper(target)
local modulefiles = line:split("CXX_IMPORTS += ", plain)[2]
if modulefiles then
for _, modulefile in ipairs(modulefiles:split(' ', plain)) do
if modulefile:endswith(".c++m") then
local modulekey = modulefile:sub(1, #modulefile - 5)
local modulepath = mapper[modulekey]
if modulepath then
modulepath = _normailize_dep(modulepath, projectdir)
results:insert(modulepath)
end
end
end
end
end
return results:to_array()
end
|
0 | repos/xmake/xmake/modules/private/tools | repos/xmake/xmake/modules/private/tools/rust/check_target.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 w568w
-- @file check_target.lua
--
-- imports
import("lib.detect.find_tool")
-- get rustc supported targets
--
-- @return the supported target list. If rustc not found, return nil
function _get_rustc_supported_target()
local rustc = find_tool("rustc")
if not rustc then
return nil
end
local output = os.iorunv(rustc.program, {"--print", "target-list"})
return output:split('\n')
end
-- check whether the target is supported by rustc
--
-- @param arch the target name, e.g. x86_64-unknown-linux-gnu
-- @param precise whether to check the target precisely (i.e. check by rustc), otherwise only by syntax
--
-- @return true if arch != nil and the target is supported by rustc, otherwise false
function main(arch, precise)
if not arch then
return false
end
-- 1: check by syntax
local result = false
local archs = arch:split("%-")
if #archs >= 2 then
result = true
else
wprint("the arch \"%s\" is NOT a valid target triple, will be IGNORED and may cause compilation errors, please check it again", arch)
end
-- 2: check by rustc
if not precise then
return result
end
result = false
local rustc_supported_target = _get_rustc_supported_target()
if rustc_supported_target then
for _, v in ipairs(rustc_supported_target) do
if v == arch then
result = true
break
end
end
if not result then
wprint("the arch \"%s\" is NOT supported by rustc, will be IGNORED and may cause compilation errors, please check it again", arch)
end
end
return result
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.