Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/xmake/xmake/core
repos/xmake/xmake/core/project/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 -- -- define module local package = {} local _instance = _instance or {} -- load modules local io = require("base/io") local os = require("base/os") local path = require("base/path") local table = require("base/table") local utils = require("base/utils") local semver = require("base/semver") local rule = require("project/rule") local config = require("project/config") local sandbox = require("sandbox/sandbox") local localcache = require("cache/localcache") local instance_deps = require("base/private/instance_deps") -- save the requires info to the cache function _instance:save() package._cache():set(self:name(), self._INFO) package._cache():save() end -- clear the package function _instance:clear() local info = self._INFO if info then for k, v in pairs(info) do if not k:startswith("__") then info[k] = nil end end end self._COMPONENT_DEPS = nil end -- dump this package function _instance:dump() utils.dump(self._INFO) end -- get the require info function _instance:get(infoname) return self._INFO[infoname] end -- get the package name (with alias name) function _instance:name() return self._NAME end -- get the package version function _instance:version() -- get it from cache first if self._VERSION ~= nil then return self._VERSION end -- get version local version = nil local verstr = self:get("version") if verstr then version = semver.new(verstr) end self._VERSION = version or false return version end -- get the package license function _instance:license() return self:get("license") end -- has static libraries? function _instance:has_static() return self:get("static") end -- has shared libraries? function _instance:has_shared() return self:get("shared") end -- get the require string function _instance:requirestr() return self:get("__requirestr") end -- get the require configuration from the given name -- -- e.g. -- -- add_requires("xxx", {system = true, configs = {shared = true}}) -- -- local configs = pkg:requireconf() -- local system = pkg:requireconf("system") -- local shared = pkg:requireconf("configs", "shared") -- function _instance:requireconf(name, key) local requireconfs = self:get("__requireconfs") local value = requireconfs if name then value = requireconfs and requireconfs[name] or nil if value and key then value = value[key] end end return value end -- get the install directory -- @see https://github.com/xmake-io/xmake/issues/3106 function _instance:installdir() return self:get("installdir") or self:get("__installdir") -- deprecated end -- get library files function _instance:libraryfiles() return self:get("libfiles") end -- get components function _instance:components() return self:get("components") end -- get default components function _instance:components_default() return self:get("__components_default") end -- get components list with link order function _instance:components_orderlist() return self:get("__components_orderlist") end -- get the dependencies of components function _instance:components_deps() return self:get("__components_deps") end -- get user extra configuration from package/on_fetch -- @see https://github.com/xmake-io/xmake/issues/3106#issuecomment-1330143922 -- -- e.g. -- -- @code -- package("xxx") -- on_fetch(function (package) -- return {includedirs = "", links = "", extras = {foo = ""}} -- end) -- -- @endcode -- -- we can also get extra configuration from package/add_xxx -- -- e.g. -- -- @code -- package("xxx") -- add_linkgroups("foo", {group = true}) -- -- target:pkg("xxx"):extraconf("linkgroups", "foo", "group") -- @endcode -- -- extras = { -- linkgroups = { -- z = { -- group = true -- } -- } -- } -- function _instance:extraconf(name, item, key) local extraconfs = self:get("extras") if not extraconfs then return end -- get configuration local extraconf = extraconfs[name] -- get configuration value local value = extraconf if item then value = extraconf and extraconf[item] or nil if value == nil and extraconf and type(item) == "table" then value = extraconf[table.concat(item, "_")] end if value and key then value = value[key] end end return value end -- get order dependencies of the given component function _instance:component_orderdeps(name) local component_orderdeps = self._COMPONENT_ORDERDEPS if not component_orderdeps then component_orderdeps = {} self._COMPONENT_ORDERDEPS = component_orderdeps end -- expand dependencies local orderdeps = component_orderdeps[name] if not orderdeps then orderdeps = table.reverse_unique(self:_sort_componentdeps(name)) component_orderdeps[name] = orderdeps end return orderdeps end -- set the value to the requires info function _instance:set(name_or_info, ...) if type(name_or_info) == "string" then local args = ... if args ~= nil then self._INFO[name_or_info] = table.unwrap(table.unique(table.join(...))) else self._INFO[name_or_info] = nil end elseif table.is_dictionary(name_or_info) then for name, info in pairs(table.join(name_or_info, ...)) do self:set(name, info) end end end -- add the value to the requires info function _instance:add(name_or_info, ...) if type(name_or_info) == "string" then local info = table.wrap(self._INFO[name_or_info]) self._INFO[name_or_info] = table.unwrap(table.unique(table.join(info, ...))) elseif table.is_dictionary(name_or_info) then for name, info in pairs(table.join(name_or_info, ...)) do self:add(name, info) end end end -- this require info is enabled? function _instance:enabled() return self:get("__enabled") end -- enable or disable this require info function _instance:enable(enabled) self:set("__enabled", enabled) end -- get environments function _instance:envs() return self:get("envs") end -- get the given rule function _instance:rule(name) return self:rules()[name] end -- get package rules -- @see https://github.com/xmake-io/xmake/issues/2374 function _instance:rules() local rules = self._RULES if rules == nil then local ruleinfos = {} local installdir = self:installdir() local rulesdir = path.join(installdir, "rules") if os.isdir(rulesdir) then local files = os.filedirs(path.join(rulesdir, "*")) if files then for _, filepath in ipairs(files) do local results, errors if filepath:endswith(".lua") then results, errors = rule._load(filepath) elseif os.isdir(filepath) and os.isfile(path.join(filepath, "xmake.lua")) then results, errors = rule._load(path.join(filepath, "xmake.lua")) else os.raise("unknown rule %s: %s", os.isdir(filepath) and "directory" or "file", filepath) end if results then table.join2(ruleinfos, results) else os.raise(errors) end end end end -- make rule instances rules = {} for rulename, ruleinfo in pairs(ruleinfos) do rulename = "@" .. self:name() .. "/" .. rulename local instance = rule.new(rulename, ruleinfo, {package = self}) if instance:script("load") then utils.warning("we cannot add `on_load()` in package rule(%s), please use `on_config()` instead of it!", rulename) end if instance:script("load_after") then utils.warning("we cannot add `after_load()` in package rule(%s), please use `on_config()` instead of it!", rulename) end rules[rulename] = instance end self._RULES = rules end return rules end -- sort component deps function _instance:_sort_componentdeps(name) local orderdeps = {} local plaindeps = self:components_deps() and self:components_deps()[name] for _, dep in ipairs(table.wrap(plaindeps)) do table.insert(orderdeps, dep) table.join2(orderdeps, self:_sort_componentdeps(dep)) end return orderdeps end -- we need to sort package set keys by this string -- @see https://github.com/xmake-io/xmake/pull/2971#issuecomment-1290052169 function _instance:__tostring() return "<package: " .. self:name() .. ">" end -- get cache function package._cache() return localcache.cache("package") end -- load the package from the cache function package.load(name) local info = package._cache():get(name) if info == nil then return end return package.load_withinfo(name, info) end -- load package from the give package info function package.load_withinfo(name, info) local instance = table.inherit(_instance) instance._INFO = info instance._NAME = name return instance end -- return module return package
0
repos/xmake/xmake/core/project
repos/xmake/xmake/core/project/deprecated/project.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 deprecated_project.lua -- -- define module: deprecated_project local deprecated_project = deprecated_project or {} -- load modules local os = require("base/os") local path = require("base/path") local utils = require("base/utils") local table = require("base/table") local string = require("base/string") local rule = require("project/rule") local config = require("project/config") local platform = require("platform/platform") local deprecated = require("base/deprecated") -- register api function deprecated_project.api_register(interp) end -- return module: deprecated_project return deprecated_project
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/libc.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 libc.lua -- -- define module: libc local libc = libc or {} -- save original interfaces libc._malloc = libc._malloc or libc.malloc libc._free = libc._free or libc.free libc._memcpy = libc._memcpy or libc.memcpy libc._memmov = libc._memmov or libc.memmov libc._memset = libc._memset or libc.memset libc._strndup = libc._strndup or libc.strndup libc._dataptr = libc._dataptr or libc.dataptr libc._byteof = libc._byteof or libc.byteof libc._setbyte = libc._setbyte or libc.setbyte -- load modules local ffi = xmake._LUAJIT and require("ffi") -- define ffi interfaces if ffi then ffi.cdef[[ void* malloc(size_t size); void free(void* data); void* memmove(void* dest, const void* src, size_t n); ]] end function libc.malloc(size, opt) if ffi then if opt and opt.gc then return ffi.gc(ffi.cast("unsigned char*", ffi.C.malloc(size)), ffi.C.free) else return ffi.cast("unsigned char*", ffi.C.malloc(size)) end else local data, errors = libc._malloc(size) if not data then os.raise(errors) end return data end end function libc.free(data) if ffi then return ffi.C.free(data) else return libc._free(data) end end function libc.memcpy(dst, src, size) if ffi then return ffi.copy(dst, src, size) else return libc._memcpy(dst, src, size) end end function libc.memmov(dst, src, size) if ffi then return ffi.C.memmove(dst, src, size) else return libc._memmov(dst, src, size) end end function libc.memset(data, ch, size) if ffi then return ffi.fill(data, size, ch) else libc._memset(data, ch, size) end end function libc.strndup(s, n) if ffi then return ffi.string(s, n) else local s, errors = libc._strndup(s, n) if not s then os.raise(errors) end return s end end function libc.byteof(data, offset) if ffi then return data[offset] else return libc._byteof(data, offset) end end function libc.setbyte(data, offset, value) if ffi then data[offset] = value else return libc._setbyte(data, offset, value) end end function libc.dataptr(data, opt) if ffi then if opt and opt.gc then return ffi.gc(ffi.cast("unsigned char*", data), ffi.C.free) else return ffi.cast("unsigned char*", data) end else return type(data) == "number" and data or libc._dataptr(data) end end function libc.ptraddr(data) if ffi then return tonumber(ffi.cast('unsigned long long', data)) else return data end end -- return module: libc return libc
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/table.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 table.lua -- -- define module: table local table = table or {} -- clear table if not table.clear then if xmake._LUAJIT then table.clear = require("table.clear") else function table.clear(t) for k, v in pairs(t) do t[k] = nil end end end end -- new table if not table.new then if xmake._LUAJIT then table.new = require("table.new") else function table.new(narray, nhash) -- TODO return {} end end end -- get array length if not table.getn then function table.getn(t) return #t end end -- get array max integer key for lua5.4 if not table.maxn then function table.maxn(t) local max = 0 for k, _ in pairs(t) do if type(k) == "number" and k > max then max = k end end return max end end -- move values of table(a1) to table(a2) -- -- disable the builtin implementation for android termux/arm64, it will crash when calling `table.move({1, 1}, 1, 2, 1, {})` -- -- @see https://github.com/xmake-io/xmake/pull/667#issuecomment-575859604 -- if xmake._ARCH:startswith("arm") then function table.move(a1, f, e, t, a2) if a2 == nil then a2 = a1 end assert(a1) assert(a2) if e >= f then local d = t - f if t > e or t <= f or a2 ~= a1 then for i = f, e do a2[i + d] = a1[i] end else for i = e, f, -1 do a2[i + d] = a1[i] end end end return a2 end end -- join all objects and tables function table.join(...) local result = {} for _, t in ipairs({...}) do if type(t) == "table" and not t.__wrap_locked__ then for k, v in pairs(t) do if type(k) == "number" then table.insert(result, v) else result[k] = v end end else table.insert(result, t) end end return result end -- join all objects and tables to self function table.join2(self, ...) for _, t in ipairs({...}) do if type(t) == "table" and not t.__wrap_locked__ then for k, v in pairs(t) do if type(k) == "number" then table.insert(self, v) else self[k] = v end end else table.insert(self, t) end end return self end -- shallow join all objects, it will not expand all table values function table.shallow_join(...) local result = {} for _, t in ipairs({...}) do table.insert(result, t) end return result end -- shallow join all objects, it will not expand all table values function table.shallow_join2(self, ...) for _, t in ipairs({...}) do table.insert(self, t) end return self end -- swap items in array function table.swap(array, i, j) local val = array[i] array[i] = array[j] array[j] = val end -- append all objects to array function table.append(array, ...) for _, value in ipairs({...}) do table.insert(array, value) end return array end -- clone table -- -- @param depth e.g. shallow: 1, deep: -1 -- function table.clone(self, depth) depth = depth or 1 local result = self if type(self) == "table" and depth > 0 then result = {} for k, v in pairs(self) do result[k] = table.clone(v, depth - 1) end end return result end -- copy the table (deprecated, please use table.clone) function table.copy(copied) local result = {} copied = copied or {} for k, v in pairs(table.wrap(copied)) do result[k] = v end return result end -- copy the table to self function table.copy2(self, copied) table.clear(self) copied = copied or {} for k, v in pairs(table.wrap(copied)) do self[k] = v end end -- inherit interfaces and create a new instance function table.inherit(...) local classes = {...} local instance = {} local metainfo = {} for _, clasz in ipairs(classes) do for k, v in pairs(clasz) do if type(v) == "function" then if k:startswith("__") then if metainfo[k] == nil then metainfo[k] = v end else if instance[k] == nil then instance[k] = v else instance["_super_" .. k] = v end end end end end setmetatable(instance, metainfo) return instance end -- inherit interfaces from the given class function table.inherit2(self, ...) local classes = {...} local metainfo = getmetatable(self) or {} for _, clasz in ipairs(classes) do for k, v in pairs(clasz) do if type(v) == "function" then if k:startswith("__") then if metainfo[k] == nil then metainfo[k] = v end else if self[k] == nil then self[k] = v else self["_super_" .. k] = v end end end end end setmetatable(self, metainfo) return self end -- slice table array function table.slice(self, first, last, step) local sliced = {} for i = first or 1, last or #self, step or 1 do sliced[#sliced + 1] = self[i] end return sliced end -- is array? function table.is_array(array) return type(array) == "table" and array[1] ~= nil end -- is dictionary? function table.is_dictionary(dict) return type(dict) == "table" and dict[1] == nil end -- does contain the given values in table? -- contains arg1 or arg2 ... function table.contains(t, arg1, arg2, ...) local found = false if arg2 == nil then -- only one value if table.is_array(t) then for _, v in ipairs(t) do if v == arg1 then found = true break end end else for _, v in pairs(t) do if v == arg1 then found = true break end end end else local values = {} local args = table.pack(arg1, arg2, ...) for _, arg in ipairs(args) do values[arg] = true end if table.is_array(t) then for _, v in ipairs(t) do if values[v] then found = true break end end else for _, v in pairs(t) do if values[v] then found = true break end end end end return found end -- read data from iterator, push them to an array -- usage: table.to_array(ipairs("a", "b")) -> {{1,"a",n=2},{2,"b",n=2}},2 -- usage: table.to_array(io.lines("file")) -> {"line 1","line 2", ... , "line n"},n function table.to_array(iterator, state, var) local result = {} local count = 0 while true do local data = table.pack(iterator(state, var)) if data[1] == nil then break end var = data[1] if data.n == 1 then table.insert(result, var) else table.insert(result, data) end count = count + 1 end return result, count end -- unwrap array if be only one value function table.unwrap(array) if type(array) == "table" and not array.__wrap_locked__ then if #array == 1 then return array[1] end end return array end -- wrap value to array function table.wrap(value) if nil == value then return {} end if type(value) ~= "table" or value.__wrap_locked__ then return {value} end return value end -- lock table value to avoid unwrap -- -- a = {1}, wrap(a): {1}, unwrap(a): 1 -- a = wrap_lock({1}), wrap(a): {a}, unwrap(a): a function table.wrap_lock(value) if type(value) == "table" then value.__wrap_locked__ = true end return value end -- unlock table value to unwrap function table.wrap_unlock(value) if type(value) == "table" then value.__wrap_locked__ = nil end return value end -- remove repeat from the given array function table.unique(array, barrier) if table.is_array(array) then if table.getn(array) ~= 1 then local exists = {} local unique = {} for _, v in ipairs(array) do -- exists barrier? clear the current existed items if barrier and barrier(v) then exists = {} end -- add unique item if not exists[v] then exists[v] = true table.insert(unique, v) end end if array.__wrap_locked__ then table.wrap_lock(unique) end array = unique end end return array end -- reverse to remove repeat from the given array function table.reverse_unique(array, barrier) if table.is_array(array) then if table.getn(array) ~= 1 then local exists = {} local unique = {} local n = #array for i = 1, n do local v = array[n - i + 1] -- exists barrier? clear the current existed items if barrier and barrier(v) then exists = {} end -- add unique item if not exists[v] then exists[v] = true table.insert(unique, 1, v) end end if array.__wrap_locked__ then table.wrap_lock(unique) end array = unique end end return array end -- pack arguments into a table -- polyfill of lua 5.2, @see https://www.lua.org/manual/5.2/manual.html#pdf-table.pack function table.pack(...) return { n = select("#", ...), ... } end -- table.unpack table values -- polyfill of lua 5.2, @see https://www.lua.org/manual/5.2/manual.html#pdf-unpack table.unpack = table.unpack or unpack -- get keys of a table function table.keys(tbl) local keyset = {} local n = 0 for k, _ in pairs(tbl) do n = n + 1 keyset[n] = k end return keyset, n end -- get order keys of a table function table.orderkeys(tbl, callback) local callback = type(callback) == "function" and callback or nil local keys = table.keys(tbl) if callback then table.sort(keys, callback) else local ok = pcall(table.sort, keys) if not ok then -- maybe sort strings and numbers, {1, 2, "a"} table.sort(keys, function (a, b) return tostring(a) < tostring(b) end) end end return keys end -- order key/value iterator -- -- for k, v in table.orderpairs(t) do -- TODO -- end function table.orderpairs(t, callback) if type(t) ~= "table" then t = t ~= nil and {t} or {} end local orderkeys = table.orderkeys(t, callback) local i = 1 return function (t, k) k = orderkeys[i] i = i + 1 return k, t[k] end, t, nil end -- get values of a table function table.values(tbl) local valueset = {} local n = 0 for _, v in pairs(tbl) do n = n + 1 valueset[n] = v end return valueset, n end -- map values to a new table function table.map(tbl, mapper) local newtbl = {} for k, v in pairs(tbl) do newtbl[k] = mapper(k, v) end return newtbl end -- map values to a new array function table.imap(arr, mapper) local newarr = {} for k, v in ipairs(arr) do table.insert(newarr, mapper(k, v)) end return newarr end -- reverse table values function table.reverse(arr) local revarr = {} local l = #arr for i = 1, l do revarr[i] = arr[l - i + 1] end return revarr end -- remove values if predicate is matched function table.remove_if(tbl, pred) if table.is_array(tbl) then for i = #tbl, 1, -1 do if pred(i, tbl[i]) then table.remove(tbl, i) end end else for k, v in pairs(tbl) do if pred(k, v) then tbl[k] = nil end end end return tbl end -- is empty table? function table.empty(tbl) return type(tbl) == "table" and #tbl == 0 and #table.keys(tbl) == 0 end -- return indices or keys for the given value function table.find(tbl, value) local result if table.is_array(tbl) then for i, v in ipairs(tbl) do if v == value then result = result or {} table.insert(result, i) end end else for k, v in pairs(tbl) do if v == value then result = result or {} table.insert(result, k) end end end return result end -- return indices or keys if predicate is matched function table.find_if(tbl, pred) local result if table.is_array(tbl) then for i, v in ipairs(tbl) do if pred(i, v) then result = result or {} table.insert(result, i) end end else for k, v in pairs(tbl) do if pred(k, v) then result = result or {} table.insert(result, k) end end end return result end -- return first index for the given value function table.find_first(tbl, value) for i, v in ipairs(tbl) do if v == value then return i end end end -- return first index if predicate is matched function table.find_first_if(tbl, pred) for i, v in ipairs(tbl) do if pred(i, v) then return i end end end -- return module: table return table
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/linuxos.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 linuxos.lua -- -- define module: linuxos local linuxos = linuxos or {} -- load modules local os = require("base/os") local path = require("base/path") local semver = require("base/semver") -- get lsb_release information -- -- e.g. -- -- Distributor ID: Ubuntu -- Description: Ubuntu 16.04.7 LTS -- Release: 16.04 -- Codename: xenial -- function linuxos._lsb_release() local lsb_release = linuxos._LSB_RELEASE if lsb_release == nil then local ok, result = os.iorun("lsb_release -a") if ok then lsb_release = result end if lsb_release then lsb_release = lsb_release:trim():lower() end linuxos._LSB_RELEASE = lsb_release or false end return lsb_release or nil end -- get uname information function linuxos._uname_r() local uname_r = linuxos._UNAME_R if uname_r == nil then local ok, result = os.iorun("uname -r") if ok then uname_r = result end if uname_r then uname_r = uname_r:trim():lower() end linuxos._UNAME_R = uname_r or false end return uname_r or nil end -- get system name -- -- e.g. -- - ubuntu -- - debian -- - archlinux -- - rhel -- - centos -- - fedora -- - opensuse -- - ... function linuxos.name() local name = linuxos._NAME if name == nil then -- get it from /etc/os-release first if name == nil and os.isfile("/etc/os-release") then local os_release = io.readfile("/etc/os-release") if os_release then os_release = os_release:trim():lower() if os_release:find("arch linux", 1, true) or os_release:find("archlinux", 1, true) then name = "archlinux" elseif os_release:find("centos linux", 1, true) or os_release:find("centos", 1, true) then name = "centos" elseif os_release:find("fedora", 1, true) then name = "fedora" elseif os_release:find("uos", 1, true) then name = "uos" elseif os_release:find("deepin", 1, true) then name = "deepin" elseif os_release:find("linux mint", 1, true) or os_release:find("linuxmint", 1, true) then name = "linuxmint" elseif os_release:find("ubuntu", 1, true) then name = "ubuntu" elseif os_release:find("debian", 1, true) then name = "debian" elseif os_release:find("gentoo linux", 1, true) then name = "gentoo" elseif os_release:find("opensuse", 1, true) then name = "opensuse" elseif os_release:find("manjaro", 1, true) then name = "manjaro" end end end -- get it from lsb release if name == nil then local lsb_release = linuxos._lsb_release() if lsb_release and lsb_release:find("ubuntu", 1, true) then name = "ubuntu" end end -- is archlinux? if name == nil and os.isfile("/etc/arch-release") then name = "archlinux" end -- unknown name = name or "unknown" linuxos._NAME = name end return name end -- get system version function linuxos.version() local version = linuxos._VERSION if version == nil then -- get it from /etc/os-release first if version == nil and os.isfile("/etc/os-release") then local os_release = io.readfile("/etc/os-release") if os_release then os_release = os_release:trim():lower():split("\n") for _, line in ipairs(os_release) do -- ubuntu: VERSION="16.04.7 LTS (Xenial Xerus)" -- fedora: VERSION="32 (Container Image)" -- debian: VERSION="9 (stretch)" if line:find("version=") then line = line:sub(9) version = semver.match(line) if not version then version = line:match("\"(%d+)%s+.*\"") if version then version = semver.new(version .. ".0") end end if version then break end end end end end -- get it from lsb release if version == nil then local lsb_release = linuxos._lsb_release() if lsb_release and lsb_release:find("ubuntu", 1, true) then for _, line in ipairs(lsb_release:split("\n")) do -- release: 16.04 if line:find("release:") then version = semver.match(line, 9) if version then break end end end end end linuxos._VERSION = version end return version end -- get linux kernel version function linuxos.kernelver() local version = linuxos._KERNELVER if version == nil then if version == nil then local uname_r = linuxos._uname_r() if uname_r then version = semver.match(uname_r) end end linuxos._KERNELVER = version end return version end -- return module: linuxos return linuxos
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/process.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 process.lua -- -- define module: process local process = process or {} local _subprocess = _subprocess or {} -- load modules local io = require("base/io") local path = require("base/path") local utils = require("base/utils") local string = require("base/string") local coroutine = require("base/coroutine") local scheduler = require("base/scheduler") -- save original interfaces process._open = process._open or process.open process._openv = process._openv or process.openv process._wait = process._wait or process.wait process._kill = process._kill or process.kill process._close = process._close or process.close process.wait = nil process.kill = nil process.close = nil process._subprocess = _subprocess -- new an subprocess function _subprocess.new(program, proc) local subprocess = table.inherit(_subprocess) subprocess._PROGRAM = program subprocess._PROC = proc setmetatable(subprocess, _subprocess) return subprocess end -- get the process name function _subprocess:name() if not self._NAME then self._NAME = path.filename(self:program()) end return self._NAME end -- get the process program function _subprocess:program() return self._PROGRAM end -- get cdata of process function _subprocess:cdata() return self._PROC end -- get poller object type, poller.OT_PROC function _subprocess:otype() return 3 end -- wait subprocess -- -- @param timeout the timeout -- -- @return ok, status -- function _subprocess:wait(timeout) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- wait events local result = -1 local status_or_errors = nil if scheduler:co_running() then result, status_or_errors = scheduler:poller_waitproc(self, timeout or -1) else result, status_or_errors = process._wait(self:cdata(), timeout or -1) end if result < 0 and status_or_errors then status_or_errors = string.format("%s: %s", self, status_or_errors) end return result, status_or_errors end -- kill subprocess function _subprocess:kill() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- kill process process._kill(self:cdata()) return true end -- close subprocess function _subprocess:close() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- cancel pipe events from the scheduler if scheduler:co_running() then ok, errors = scheduler:poller_cancel(self) if not ok then return false, errors end end -- close process ok = process._close(self:cdata()) if ok then self._PROC = nil end return ok end -- ensure the process is opened function _subprocess:_ensure_opened() if not self:cdata() then return false, string.format("%s: has been closed!", self) end return true end -- tostring(subprocess) function _subprocess:__tostring() return "<subprocess: " .. self:name() .. ">" end -- gc(subprocess) function _subprocess:__gc() if self._PROC and process._close(self._PROC) then self._PROC = nil end end -- open a subprocess -- -- @param command the process command -- @param opt the option arguments, e.g. {stdin = filepath/file/pipe, stdout = filepath/file/pipe, stderr = filepath/file/pipe, envs = {"PATH=xxx", "XXX=yyy"}}) -- -- @return the subprocess -- function process.open(command, opt) -- get stdin and pass to subprocess opt = opt or {} local stdin = opt.stdin if type(stdin) == "string" then opt.inpath = stdin elseif type(stdin) == "table" then if stdin.otype and stdin:otype() == 2 then opt.inpipe = stdin:cdata() else opt.infile = stdin:cdata() end end -- get stdout and pass to subprocess local stdout = opt.stdout if type(stdout) == "string" then opt.outpath = stdout elseif type(stdout) == "table" then if stdout.otype and stdout:otype() == 2 then opt.outpipe = stdout:cdata() else opt.outfile = stdout:cdata() end end -- get stderr and pass to subprocess local stderr = opt.stderr if type(stderr) == "string" then opt.errpath = stderr elseif type(stderr) == "table" then if stderr.otype and stderr:otype() == 2 then opt.errpipe = stderr:cdata() else opt.errfile = stderr:cdata() end end -- open subprocess local proc = process._open(command, opt) if proc then return _subprocess.new(command:split(' ', {plain = true})[1], proc) else return nil, string.format("open process(%s) failed!", command) end end -- open a subprocess with the arguments list -- -- @param program the program -- @param argv the arguments list -- @param opt the option arguments, e.g. {stdin = filepath/file/pipe, stdout = filepath/file/pipe, stderr = filepath/file/pipe, envs = {"PATH=xxx", "XXX=yyy"}}) -- -- @return the subprocess -- function process.openv(program, argv, opt) -- get stdin and pass to subprocess opt = opt or {} local stdin = opt.stdin if type(stdin) == "string" then opt.inpath = stdin elseif type(stdin) == "table" then if stdin.otype and stdin:otype() == 2 then opt.inpipe = stdin:cdata() else opt.infile = stdin:cdata() end end -- get stdout and pass to subprocess local stdout = opt.stdout if type(stdout) == "string" then opt.outpath = stdout elseif type(stdout) == "table" then if stdout.otype and stdout:otype() == 2 then opt.outpipe = stdout:cdata() else opt.outfile = stdout:cdata() end end -- get stderr and pass to subprocess local stderr = opt.stderr if type(stderr) == "string" then opt.errpath = stderr elseif type(stderr) == "table" then if stderr.otype and stderr:otype() == 2 then opt.errpipe = stderr:cdata() else opt.errfile = stderr:cdata() end end -- open subprocess local proc = process._openv(program, argv, opt) if proc then return _subprocess.new(program, proc) else return nil, string.format("openv process(%s, %s) failed!", program, os.args(argv)) end end -- return module: process return process
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/base64.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 base64.lua -- -- define module: base64 local base64 = base64 or {} -- load modules local io = require("base/io") local utils = require("base/utils") local bytes = require("base/bytes") -- save metatable and builtin functions base64._encode = base64._encode or base64.encode base64._decode = base64._decode or base64.decode -- decode base64 string to the data -- -- @param base64str the base64 string -- -- @return the data -- function base64.decode(base64str) local data = base64._decode(base64str) if not data then return nil, string.format("decode base64 failed") end return bytes(data) end -- encode data to the base64 string -- -- @param data the data -- -- @return the base64 string -- function base64.encode(data) if type(data) == "string" then data = bytes(data) end local datasize = data:size() local dataaddr = data:caddr() local base64str, errors = base64._encode(dataaddr, datasize) if not base64str then return nil, errors or string.format("encode base64 failed") end return base64str end -- return module: base64 return base64
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/bytes.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 bytes.lua -- -- define module: bytes local bytes = bytes or {} local _instance = _instance or {} -- load modules local bit = require("base/bit") local os = require("base/os") local utils = require("base/utils") local todisplay = require("base/todisplay") local libc = require("base/libc") local table = require("base/table") -- new a bytes instance -- -- bytes(size[, init]): allocates a buffer of given size, init with given number or char value -- bytes(size, ptr [, manage]): mounts buffer on existing storage (manage memory or not) -- bytes(str): mounts a buffer from the given string -- bytes(bytes, start, last): mounts a buffer from another one, with start/last limits -- bytes(bytes1, bytes2, bytes3, ...): allocates and concat buffer from list of byte buffers -- bytes(bytes): allocates a buffer from another one (strict replica, sharing memory) -- bytes({bytes1, bytes2, ...}): allocates and concat buffer from a list of byte buffers (table) -- bytes({})/bytes(): allocate an empty buffer -- function _instance.new(...) local args = {...} local arg1, arg2, arg3 = table.unpack(args) local instance = table.inherit(_instance) if type(arg1) == "number" then local size = arg1 local arg2_type = type(arg2) if arg2_type == "cdata" or arg2_type == "userdata" then -- bytes(size, ptr [, manage]): mounts buffer on existing storage (manage memory or not) local ptr = arg2 local manage = arg3 if manage then instance._CDATA = libc.dataptr(ptr, {gc = true}) instance._MANAGED = true else instance._CDATA = libc.dataptr(ptr) instance._MANAGED = false end else -- bytes(size[, init]): allocates a buffer of given size local init if arg2 then if arg2_type == "number" then init = arg2 elseif arg2_type == "string" then init = arg2:byte() else os.raise("invalid arguments #2 for bytes(size, ...), cdata, string, number or nil expected!") end end local ptr = libc.malloc(size, {gc = true}) if init then libc.memset(ptr, init, size) end instance._CDATA = ptr instance._MANAGED = true end instance._SIZE = size instance._READONLY = false elseif type(arg1) == "string" then -- bytes(str): mounts a buffer from the given string local str = arg1 instance._SIZE = #str instance._CDATA = libc.dataptr(str) instance._REF = str -- keep ref for GC instance._MANAGED = false instance._READONLY = true elseif type(arg1) == "table" then if type(arg2) == 'number' then -- bytes(bytes, start, last): mounts a buffer from another one, with start/last limits: local b = arg1 local start = arg2 or 1 local last = arg3 or b:size() if start < 1 or last > b:size() then os.raise("incorrect bounds(%d-%d) for bytes(...)!", start, last) end instance._SIZE = last - start + 1 instance._CDATA = b:cdata() - 1 + start instance._REF = b -- keep lua ref for GC instance._MANAGED = false instance._READONLY = b:readonly() elseif type(arg2) == "table" then -- bytes(bytes1, bytes2, bytes3, ...): allocates and concat buffer from list of byte buffers instance._SIZE = 0 for _, b in ipairs(args) do instance._SIZE = instance._SIZE + b:size() end instance._CDATA = libc.malloc(instance._SIZE, {gc = true}) local offset = 0 for _, b in ipairs(args) do libc.memcpy(instance._CDATA + offset, b:cdata(), b:size()) offset = offset + b:size() end instance._MANAGED = true instance._READONLY = false elseif not arg2 and arg1[1] and type(arg1[1]) == 'table' then -- bytes({bytes1, bytes2, ...}): allocates and concat buffer from a list of byte buffers (table) args = arg1 instance._SIZE = 0 for _, b in ipairs(args) do instance._SIZE = instance._SIZE + b:size() end instance._CDATA = libc.malloc(instance._SIZE, {gc = true}) local offset = 0 for _, b in ipairs(args) do libc.memcpy(instance._CDATA + offset, b._CDATA, b:size()) offset = offset + b:size() end instance._MANAGED = true instance._READONLY = false elseif not arg2 and arg1.size and arg1:size() > 0 then -- bytes(bytes): allocates a buffer from another one (strict replica, sharing memory) local b = arg1 local start = 1 local last = arg3 or b:size() if start < 1 or last > b:size() then os.raise("incorrect bounds(%d-%d)!", start, last) end instance._SIZE = last - start + 1 instance._CDATA = b:cdata() -1 + start instance._REF = b -- keep lua ref for GC instance._MANAGED = false instance._READONLY = b:readonly() else -- bytes({}): allocate an empty buffer instance._SIZE = 0 instance._CDATA = nil instance._MANAGED = false instance._READONLY = true end elseif arg1 == nil then -- bytes(): allocate an empty buffer instance._SIZE = 0 instance._CDATA = nil instance._MANAGED = false instance._READONLY = true end if instance:size() == nil then os.raise("invalid arguments for bytes(...)!") end setmetatable(instance, _instance) return instance end -- get bytes size function _instance:size() return self._SIZE end -- get bytes data function _instance:cdata() return self._CDATA end -- get data address function _instance:caddr() return libc.ptraddr(self:cdata()) end -- readonly? function _instance:readonly() return self._READONLY end -- bytes:ipairs() function _instance:ipairs() local index = 0 return function (...) if index < self:size() then index = index + 1 return index, self[index] end end end -- get a slice of bytes function _instance:slice(start, last) return bytes(self, start, last) end -- copy bytes function _instance:copy(src, start, last) if self:readonly() then os.raise("%s: cannot be modified!", self) end if type(src) == "string" then src = bytes(src) end local srcsize = src:size() start = start or 1 last = last or srcsize if start < 1 or start > srcsize then os.raise("%s: invalid start(%d)!", self, start) end if last < start - 1 or last > srcsize + start - 1 then os.raise("%s: invalid last(%d)!", self, last) end local copysize = last + 1 - start if copysize > self:size() then os.raise("%s: cannot copy bytes, src:size(%d) must be smaller than %d!", self, copysize, self:size()) end libc.memcpy(self:cdata(), src:cdata() + start - 1, copysize) return self end -- copy bytes to the given position function _instance:copy2(pos, src, start, last) if self:readonly() then os.raise("%s: cannot be modified!", self) end if type(src) == "string" then src = bytes(src) end local srcsize = src:size() start = start or 1 last = last or srcsize if start < 1 or start > srcsize then os.raise("%s: invalid start(%d)!", self, start) end if last < start - 1 or last > srcsize + start - 1 then os.raise("%s: invalid last(%d)!", self, last) end if pos < 1 or pos > self:size() then os.raise("%s: invalid pos(%d)!", self, pos) end local copysize = last + 1 - start local leftsize = self:size() + 1 - pos if copysize > leftsize then os.raise("%s: cannot copy bytes, src:size(%d) must be smaller than %d!", self, copysize, leftsize) end libc.memcpy(self:cdata() + pos - 1, src:cdata() + start - 1, copysize) return self end -- move bytes to the begin position function _instance:move(start, last) if self:readonly() then os.raise("%s: cannot be modified!", self) end local totalsize = self:size() start = start or 1 last = last or totalsize if start < 1 or start > totalsize then os.raise("%s: invalid start(%d)!", self, start) end if last < start - 1 or last > totalsize + start - 1 then os.raise("%s: invalid last(%d)!", self, last) end local movesize = last + 1 - start if movesize > totalsize then os.raise("%s: cannot move bytes, move size(%d) must be smaller than %d!", self, movesize, totalsize) end libc.memmov(self:cdata(), self:cdata() + start - 1, movesize) return self end -- move bytes to the given position function _instance:move2(pos, start, last) if self:readonly() then os.raise("%s: cannot be modified!", self) end local totalsize = self:size() start = start or 1 last = last or totalsize if start < 1 or start > totalsize then os.raise("%s: invalid start(%d)!", self, start) end if last < start - 1 or last > totalsize + start - 1 then os.raise("%s: invalid last(%d)!", self, last) end if pos < 1 or pos > totalsize then os.raise("%s: invalid pos(%d)!", self, pos) end local movesize = last + 1 - start local leftsize = totalsize + 1 - pos if movesize > leftsize then os.raise("%s: cannot move bytes, move size(%d) must be smaller than %d!", self, movesize, leftsize) end libc.memmov(self:cdata() + pos - 1, self:cdata() + start - 1, movesize) return self end -- clone a new bytes buffer function _instance:clone() local new = bytes(self:size()) new:copy(self) return new end -- dump whole bytes data function _instance:dump(start, last) start = start or 1 last = last or self:size() local i = 0 local n = 147 local p = start - 1 local e = last local line = nil while p < e do line = "" if p + 0x20 <= e then -- dump offset line = line .. string.format("${color.dump.anchor}%08X ${color.dump.number}", p) -- dump data for i = 0, 0x20 - 1 do if (i % 4) == 0 then line = line .. " " end line = line .. string.format(" %02X", self[p + i + 1]) end -- dump spaces line = line .. " " -- dump characters line = line .. "${color.dump.string}" for i = 0, 0x20 - 1 do local v = self[p + i + 1] if v > 0x1f and v < 0x7f then line = line .. string.format("%c", v) else line = line .. '.' end end line = line .. "${clear}" -- dump line utils.cprint(line) -- next line p = p + 0x20 elseif p < e then -- init padding local padding = n - 0x20 -- dump offset line = line .. string.format("${color.dump.anchor}%08X ${color.dump.number}", p) if padding >= 9 then padding = padding - 9 end -- dump data local left = e - p for i = 0, left - 1 do if (i % 4) == 0 then line = line .. " " if padding then padding = padding - 1 end end line = line .. string.format(" %02X", self[p + i + 1]) if padding >= 3 then padding = padding - 3 end end -- dump spaces while padding > 0 do line = line .. " " padding = padding - 1 end -- dump characters line = line .. "${color.dump.string}" for i = 0, left - 1 do local v = self[p + i + 1] if v > 0x1f and v < 0x7f then line = line .. string.format("%c", v) else line = line .. '.' end end line = line .. "${clear}" -- dump line utils.cprint(line) -- next line p = p + left else break end end end -- convert bytes to string function _instance:str(i, j) local offset = i and i - 1 or 0 return libc.strndup(self:cdata() + offset, (j or self:size()) - offset) end -- get uint8 value function _instance:u8(offset) return self[offset] end -- set uint8 value function _instance:u8_set(offset, value) self[offset] = bit.band(value, 0xff) return self end -- get sint8 value function _instance:s8(offset) local value = self[offset] return value < 0x80 and value or -0x100 + value end -- get uint16 little-endian value function _instance:u16le(offset) return bit.lshift(self[offset + 1], 8) + self[offset] end -- set uint16 little-endian value function _instance:u16le_set(offset, value) self[offset + 1] = bit.band(bit.rshift(value, 8), 0xff) self[offset] = bit.band(value, 0xff) return self end -- get uint16 big-endian value function _instance:u16be(offset) return bit.lshift(self[offset], 8) + self[offset + 1] end -- set uint16 big-endian value function _instance:u16be_set(offset, value) self[offset] = bit.band(bit.rshift(value, 8), 0xff) self[offset + 1] = bit.band(value, 0xff) return self end -- get sint16 little-endian value function _instance:s16le(offset) local value = self:u16le(offset) return value < 0x8000 and value or -0x10000 + value end -- get sint16 big-endian value function _instance:s16be(offset) local value = self:u16be(offset) return value < 0x8000 and value or -0x10000 + value end -- get uint32 little-endian value function _instance:u32le(offset) return bit.lshift(self[offset + 3], 24) + bit.lshift(self[offset + 2], 16) + bit.lshift(self[offset + 1], 8) + self[offset] end -- set uint32 little-endian value function _instance:u32le_set(offset, value) self[offset + 3] = bit.band(bit.rshift(value, 24), 0xff) self[offset + 2] = bit.band(bit.rshift(value, 16), 0xff) self[offset + 1] = bit.band(bit.rshift(value, 8), 0xff) self[offset] = bit.band(value, 0xff) return self end -- get uint32 big-endian value function _instance:u32be(offset) return bit.lshift(self[offset], 24) + bit.lshift(self[offset + 1], 16) + bit.lshift(self[offset + 2], 8) + self[offset + 3] end -- set uint32 big-endian value function _instance:u32be_set(offset, value) self[offset] = bit.band(bit.rshift(value, 24), 0xff) self[offset + 1] = bit.band(bit.rshift(value, 16), 0xff) self[offset + 2] = bit.band(bit.rshift(value, 8), 0xff) self[offset + 3] = bit.band(value, 0xff) return self end -- get sint32 little-endian value function _instance:s32le(offset) return bit.tobit(self:u32le(offset)) end -- get sint32 big-endian value function _instance:s32be(offset) return bit.tobit(self:u32be(offset)) end -- get byte or bytes slice at the given index position -- -- bytes[1] -- bytes[{1, 2}] -- function _instance:__index(key) if type(key) == "number" then if key < 1 or key > self:size() then os.raise("%s: index(%d/%d) out of bounds!", self, key, self:size()) end return libc.byteof(self._CDATA, key - 1) elseif type(key) == "table" then local start, last = key[1], key[2] return self:slice(start, last) end return rawget(self, key) end -- set byte or bytes slice at the given index position -- -- bytes[1] = 0x1 -- bytes[{1, 2}] = bytes(2) -- function _instance:__newindex(key, value) if self:readonly() then os.raise("%s: cannot modify value at index[%s]!", self, key) end if type(key) == "number" then if key < 1 or key > self:size() then os.raise("%s: index(%d/%d) out of bounds!", self, key, self:size()) end libc.setbyte(self._CDATA, key - 1, value) return elseif type(key) == "table" then local start, last = key[1], key[2] self:slice(start, last):copy(value) return end rawset(self, key, value) end -- concat two bytes buffer function _instance:__concat(other) local new = bytes(self:size() + other:size()) new:slice(1, self:size()):copy(self) new:slice(self:size() + 1, new:size()):copy(other) return new end -- tostring(bytes) function _instance:__tostring() return "<bytes: " .. self:size() .. ">" end -- todisplay(bytes) function _instance:__todisplay() local parts = {} local size = self:size() if size > 8 then size = 8 end for i = 1, size do parts[i] = "0x" .. bit.tohex(self[i], 2) end return "bytes${reset}(" .. todisplay(self:size()) .. ") <${color.dump.number}" .. table.concat(parts, " ") .. (self:size() > 8 and "${reset} ..>" or "${reset}>") end -- it's only called for lua runtime, because bytes is not userdata function _instance:__gc() if self._MANAGED and self._CDATA then libc.free(self._CDATA) self._CDATA = nil end end -- new an bytes instance function bytes.new(...) return _instance.new(...) end -- is instance of bytes? function bytes.instance_of(data) if type(data) == "table" and data.cdata and data.size then return true end return false end -- register call function setmetatable(bytes, { __call = function (_, ...) return bytes.new(...) end, __todisplay = function() return todisplay(bytes.new) end }) -- return module: bytes return bytes
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/string.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 string.lua -- -- define module: string local string = string or {} -- load modules local deprecated = require("base/deprecated") local serialize = require("base/serialize") local bit = require("base/bit") -- save original interfaces string._dump = string._dump or string.dump string._trim = string._trim or string.trim string._split = string._split or string.split string._lastof = string._lastof or string.lastof -- find the last substring with the given pattern function string:lastof(pattern, plain) -- is plain text? use the native implementation if plain then return string._lastof(self, pattern) end -- find the last substring local curr = 0 repeat local next = self:find(pattern, curr + 1, plain) if next then curr = next end until (not next) -- found? if curr > 0 then return curr end end -- split string with the given substring/characters -- -- pattern match and ignore empty string -- ("1\n\n2\n3"):split('\n') => 1, 2, 3 -- ("abc123123xyz123abc"):split('123') => abc, xyz, abc -- ("abc123123xyz123abc"):split('[123]+') => abc, xyz, abc -- -- plain match and ignore empty string -- ("1\n\n2\n3"):split('\n', {plain = true}) => 1, 2, 3 -- ("abc123123xyz123abc"):split('123', {plain = true}) => abc, xyz, abc -- -- pattern match and contains empty string -- ("1\n\n2\n3"):split('\n', {strict = true}) => 1, , 2, 3 -- ("abc123123xyz123abc"):split('123', {strict = true}) => abc, , xyz, abc -- ("abc123123xyz123abc"):split('[123]+', {strict = true}) => abc, xyz, abc -- -- plain match and contains empty string -- ("1\n\n2\n3"):split('\n', {plain = true, strict = true}) => 1, , 2, 3 -- ("abc123123xyz123abc"):split('123', {plain = true, strict = true}) => abc, , xyz, abc -- -- limit split count -- ("1\n\n2\n3"):split('\n', {limit = 2}) => 1, 2\n3 -- ("1.2.3.4.5"):split('%.', {limit = 3}) => 1, 2, 3.4.5 -- function string:split(delimiter, opt) if #delimiter == 0 then os.raise("string.split(%s, \"\") use empty delimiter", self) end local limit, plain, strict if opt then limit = opt.limit plain = opt.plain strict = opt.strict end if plain then return string._split(self, delimiter, strict, limit) end local start = 1 local result = {} local pos, epos = self:find(delimiter, start, plain) while pos do local substr = self:sub(start, pos - 1) if (#substr > 0) or strict then if limit and limit > 0 and #result + 1 >= limit then break end table.insert(result, substr) end start = epos + 1 pos, epos = self:find(delimiter, start, plain) end if start <= #self then table.insert(result, self:sub(start)) elseif strict and (not limit or #result < limit) then if start == #self + 1 then table.insert(result, "") end end return result end -- trim the spaces function string:trim(trimchars) return string._trim(self, trimchars, 0) end -- trim the left spaces function string:ltrim(trimchars) return string._trim(self, trimchars, -1) end -- trim the right spaces function string:rtrim(trimchars) return string._trim(self, trimchars, 1) end -- encode: ' ', '=', '\"', '<' function string:encode() return (self:gsub("[%s=\"<]", function (w) return string.format("%%%x", w:byte()) end)) end -- decode: ' ', '=', '\"' function string:decode() return (self:gsub("%%(%x%x)", function (w) return string.char(tonumber(w, 16)) end)) end -- replace text function string:replace(old, new, opt) if opt and opt.plain then local b, e = self:find(old, 1, true) if b == nil then return self, 0 else local str, count = self:sub(e + 1):replace(old, new, opt) return (self:sub(1, b - 1) .. new .. str), count + 1 end else return self:gsub(old, new) end end -- try to format function string.tryformat(format, ...) local ok, str = pcall(string.format, format, ...) if ok then return str else return tostring(format) end end -- case-insensitive pattern-matching -- -- print(("src/dadasd.C"):match(string.ipattern("sR[cd]/.*%.c", true))) -- print(("src/dadasd.C"):match(string.ipattern("src/.*%.c", true))) -- -- print(string.ipattern("sR[cd]/.*%.c")) -- [sS][rR][cd]/.*%.[cC] -- -- print(string.ipattern("sR[cd]/.*%.c", true)) -- [sS][rR][cCdD]/.*%.[cC] -- function string.ipattern(pattern, brackets) local tmp = {} local i = 1 while i <= #pattern do -- get current charactor local char = pattern:sub(i, i) -- escape? if char == '%' then tmp[#tmp + 1] = char i = i + 1 char = pattern:sub(i,i) tmp[#tmp + 1] = char -- '%bxy'? add next 2 chars if char == 'b' then tmp[#tmp + 1] = pattern:sub(i + 1, i + 2) i = i + 2 end -- brackets? elseif char == '[' then tmp[#tmp + 1] = char i = i + 1 while i <= #pattern do char = pattern:sub(i, i) if char == '%' then tmp[#tmp + 1] = char tmp[#tmp + 1] = pattern:sub(i + 1, i + 1) i = i + 1 elseif char:match("%a") then tmp[#tmp + 1] = not brackets and char or char:lower() .. char:upper() else tmp[#tmp + 1] = char end if char == ']' then break end i = i + 1 end -- letter, [aA] elseif char:match("%a") then tmp[#tmp + 1] = '[' .. char:lower() .. char:upper() .. ']' else tmp[#tmp + 1] = char end i = i + 1 end return table.concat(tmp) end -- @deprecated -- dump to string from the given object (more readable) -- -- @param deflate deflate empty characters -- -- @return string, errors -- function string.dump(object, deflate) deprecated.add("utils.dump() or string.serialize()", "string.dump()") return string.serialize(object, deflate) end -- serialize to string from the given object -- -- @param opt serialize options -- e.g. { strip = true, binary = false, indent = true } -- -- @return string, errors -- function string.serialize(object, opt) return serialize.save(object, opt) end -- deserialize string to object -- -- @param str the serialized string -- -- @return object, errors -- function string:deserialize() return serialize.load(self) end -- unicode character width in the given index function string:wcwidth(idx) -- based on Markus Kuhn's implementation of wcswidth() -- https://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c local non_spacing = { {0x0300, 0x036F}, {0x0483, 0x0486}, {0x0488, 0x0489}, {0x0591, 0x05BD}, {0x05BF, 0x05BF}, {0x05C1, 0x05C2}, {0x05C4, 0x05C5}, {0x05C7, 0x05C7}, {0x0600, 0x0603}, {0x0610, 0x0615}, {0x064B, 0x065E}, {0x0670, 0x0670}, {0x06D6, 0x06E4}, {0x06E7, 0x06E8}, {0x06EA, 0x06ED}, {0x070F, 0x070F}, {0x0711, 0x0711}, {0x0730, 0x074A}, {0x07A6, 0x07B0}, {0x07EB, 0x07F3}, {0x0901, 0x0902}, {0x093C, 0x093C}, {0x0941, 0x0948}, {0x094D, 0x094D}, {0x0951, 0x0954}, {0x0962, 0x0963}, {0x0981, 0x0981}, {0x09BC, 0x09BC}, {0x09C1, 0x09C4}, {0x09CD, 0x09CD}, {0x09E2, 0x09E3}, {0x0A01, 0x0A02}, {0x0A3C, 0x0A3C}, {0x0A41, 0x0A42}, {0x0A47, 0x0A48}, {0x0A4B, 0x0A4D}, {0x0A70, 0x0A71}, {0x0A81, 0x0A82}, {0x0ABC, 0x0ABC}, {0x0AC1, 0x0AC5}, {0x0AC7, 0x0AC8}, {0x0ACD, 0x0ACD}, {0x0AE2, 0x0AE3}, {0x0B01, 0x0B01}, {0x0B3C, 0x0B3C}, {0x0B3F, 0x0B3F}, {0x0B41, 0x0B43}, {0x0B4D, 0x0B4D}, {0x0B56, 0x0B56}, {0x0B82, 0x0B82}, {0x0BC0, 0x0BC0}, {0x0BCD, 0x0BCD}, {0x0C3E, 0x0C40}, {0x0C46, 0x0C48}, {0x0C4A, 0x0C4D}, {0x0C55, 0x0C56}, {0x0CBC, 0x0CBC}, {0x0CBF, 0x0CBF}, {0x0CC6, 0x0CC6}, {0x0CCC, 0x0CCD}, {0x0CE2, 0x0CE3}, {0x0D41, 0x0D43}, {0x0D4D, 0x0D4D}, {0x0DCA, 0x0DCA}, {0x0DD2, 0x0DD4}, {0x0DD6, 0x0DD6}, {0x0E31, 0x0E31}, {0x0E34, 0x0E3A}, {0x0E47, 0x0E4E}, {0x0EB1, 0x0EB1}, {0x0EB4, 0x0EB9}, {0x0EBB, 0x0EBC}, {0x0EC8, 0x0ECD}, {0x0F18, 0x0F19}, {0x0F35, 0x0F35}, {0x0F37, 0x0F37}, {0x0F39, 0x0F39}, {0x0F71, 0x0F7E}, {0x0F80, 0x0F84}, {0x0F86, 0x0F87}, {0x0F90, 0x0F97}, {0x0F99, 0x0FBC}, {0x0FC6, 0x0FC6}, {0x102D, 0x1030}, {0x1032, 0x1032}, {0x1036, 0x1037}, {0x1039, 0x1039}, {0x1058, 0x1059}, {0x1160, 0x11FF}, {0x135F, 0x135F}, {0x1712, 0x1714}, {0x1732, 0x1734}, {0x1752, 0x1753}, {0x1772, 0x1773}, {0x17B4, 0x17B5}, {0x17B7, 0x17BD}, {0x17C6, 0x17C6}, {0x17C9, 0x17D3}, {0x17DD, 0x17DD}, {0x180B, 0x180D}, {0x18A9, 0x18A9}, {0x1920, 0x1922}, {0x1927, 0x1928}, {0x1932, 0x1932}, {0x1939, 0x193B}, {0x1A17, 0x1A18}, {0x1B00, 0x1B03}, {0x1B34, 0x1B34}, {0x1B36, 0x1B3A}, {0x1B3C, 0x1B3C}, {0x1B42, 0x1B42}, {0x1B6B, 0x1B73}, {0x1DC0, 0x1DCA}, {0x1DFE, 0x1DFF}, {0x200B, 0x200F}, {0x202A, 0x202E}, {0x2060, 0x2063}, {0x206A, 0x206F}, {0x20D0, 0x20EF}, {0x302A, 0x302F}, {0x3099, 0x309A}, {0xA806, 0xA806}, {0xA80B, 0xA80B}, {0xA825, 0xA826}, {0xFB1E, 0xFB1E}, {0xFE00, 0xFE0F}, {0xFE20, 0xFE23}, {0xFEFF, 0xFEFF}, {0xFFF9, 0xFFFB}, {0x10A01, 0x10A03}, {0x10A05, 0x10A06}, {0x10A0C, 0x10A0F}, {0x10A38, 0x10A3A}, {0x10A3F, 0x10A3F}, {0x1D167, 0x1D169}, {0x1D173, 0x1D182}, {0x1D185, 0x1D18B}, {0x1D1AA, 0x1D1AD}, {0x1D242, 0x1D244}, {0xE0001, 0xE0001}, {0xE0020, 0xE007F}, {0xE0100, 0xE01EF}, } idx = idx or 1 -- turn codepoint into unicode local c = self:byte(idx) local seq = c < 0x80 and 1 or c < 0xE0 and 2 or c < 0xF0 and 3 or c < 0xF8 and 4 or error("invalid UTF-8 sequence") local val = seq == 1 and c or bit.band(c, (2^(8 - seq) - 1)) for aux = 2, seq do c = self:byte(idx + aux - 1) val = val * 2 ^ 6 + bit.band(c, 0x3F) end -- test for 8-bit control characters if val == 0 then return 0 end if val < 32 or (val >= 0x7f and val < 0xa0) then return -1 end -- binary search in table of non-spacing characters local min, max = 1, #non_spacing if val >= non_spacing[1][1] and val <= non_spacing[max][2] then while max >= min do local mid = math.floor((min + max) / 2) if val > non_spacing[mid][2] then min = mid + 1 elseif val < non_spacing[mid][1] then max = mid - 1 else return 0 end end end if val >= 0x1100 and (val <= 0x115f or -- Hangul Jamo init. consonants val == 0x2329 or val == 0x232a or (val >= 0x2e80 and val <= 0xa4cf and val ~= 0x303f) or -- CJK ... Yi (val >= 0xac00 and val <= 0xd7a3) or -- Hangul Syllables (val >= 0xf900 and val <= 0xfaff) or -- CJK Compatibility Ideographs (val >= 0xfe10 and val <= 0xfe19) or -- Vertical forms (val >= 0xfe30 and val <= 0xfe6f) or -- CJK Compatibility Forms (val >= 0xff00 and val <= 0xff60) or -- Fullwidth Forms (val >= 0xffe0 and val <= 0xffe6) or (val >= 0x20000 and val <= 0x2fffd) or (val >= 0x30000 and val <= 0x3fffd)) then return 2 end return 1 end -- unicode string width in given start index function string:wcswidth(idx) local width = 0 idx = idx or 1 while idx <= #self do if bit.band(self:byte(idx), 0xc0) ~= 0x80 then width = width + self:wcwidth(idx) end idx = idx + 1 end return width end -- compute the Levenshtein distance between two strings function string:levenshtein(str2) local str1 = self local len1 = #str1 local len2 = #str2 local matrix = {} local cost = 0 if len1 == 0 then return len2 elseif len2 == 0 then return len1 elseif str1 == str2 then return 0 end for i = 0, len1, 1 do matrix[i] = {} matrix[i][0] = i end for j = 0, len2, 1 do matrix[0][j] = j end for i = 1, len1, 1 do for j = 1, len2, 1 do if (str1:byte(i) == str2:byte(j)) then cost = 0 else cost = 1 end matrix[i][j] = math.min(matrix[i-1][j] + 1, matrix[i][j-1] + 1, matrix[i-1][j-1] + cost) end end return matrix[len1][len2] end -- return module: string return string
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/memory.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 memory.lua -- -- define module local memory = memory or {} -- load modules local os = require("base/os") -- get memory info function memory.info(name) local meminfo = memory._MEMINFO local memtime = memory._MEMTIME if meminfo == nil or memtime == nil or os.time() - memtime > 10 then -- cache 10s meminfo = os._meminfo() if meminfo.totalsize and meminfo.availsize then meminfo.usagerate = (meminfo.totalsize - meminfo.availsize) / meminfo.totalsize else meminfo.usagerate = 0 end memory._MEMINFO = meminfo memory._MEMTIME = os.time() end if name then return meminfo[name] else return meminfo end end -- return module return memory
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/bit.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 bit.lua -- return (xmake._LUAJIT and require("bit") or require("base/compat/bit"))
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/singleton.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 singleton.lua -- -- define module local singleton = singleton or {} -- get a singleton instance and create it if not exists -- -- e.g. -- -- function get_xxx() -- return {xxx = 1} -- end -- local instance = singleton.get("key", get_xxx) -- -- Or -- -- function get_xxx() -- -- -- get instance -- local instance, inited = singleton.get(get_xxx) -- if inited then -- return instance -- end -- -- -- init instance -- instance.xxx = 1 -- return instance -- end -- function singleton.get(key, init) -- get key key = tostring(key) -- get all instances local instances = singleton.instances() -- get singleton instance local inited = true local instance = instances[key] if instance == nil then -- init instance if init then instance = init() else -- mark as not inited inited = false -- init instance instance = {} end -- save this instance instances[key] = instance end return instance, inited end -- get all singleton instances function singleton.instances() local instances = singleton._INSTANCES if not instances then instances = {} singleton._INSTANCES = instances end return instances end -- return module: singleton return singleton
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/scheduler.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 scheduler.lua -- -- define module: scheduler local scheduler = scheduler or {} local _coroutine = _coroutine or {} -- load modules local table = require("base/table") local utils = require("base/utils") local option = require("base/option") local string = require("base/string") local poller = require("base/poller") local timer = require("base/timer") local hashset = require("base/hashset") local coroutine = require("base/coroutine") local bit = require("base/bit") -- new a coroutine instance function _coroutine.new(name, thread) local instance = table.inherit(_coroutine) instance._NAME = name instance._THREAD = thread setmetatable(instance, _coroutine) return instance end -- get the coroutine name function _coroutine:name() return self._NAME or "none" end -- set the coroutine name function _coroutine:name_set(name) self._NAME = name end -- get the waiting poller object function _coroutine:waitobj() return self._WAITOBJ end -- set the waiting poller object function _coroutine:waitobj_set(obj) self._WAITOBJ = obj end -- get user private data function _coroutine:data(name) return self._DATA and self._DATA[name] end -- set user private data function _coroutine:data_set(name, data) self._DATA = self._DATA or {} self._DATA[name] = data end -- add user private data function _coroutine:data_add(name, data) self._DATA = self._DATA or {} self._DATA[name] = table.unwrap(table.join(self._DATA[name] or {}, data)) end -- get the raw coroutine thread function _coroutine:thread() return self._THREAD end -- get the coroutine status function _coroutine:status() return coroutine.status(self:thread()) end -- is dead? function _coroutine:is_dead() return self:status() == "dead" end -- is running? function _coroutine:is_running() return self:status() == "running" end -- is suspended? function _coroutine:is_suspended() return self:status() == "suspended" end -- is isolated? function _coroutine:is_isolated() return self._ISOLATED end -- isolate coroutine environments function _coroutine:isolate(isolate) self._ISOLATED = isolate end -- get the current timer task function _coroutine:_timer_task() return self._TIMER_TASK end -- set the timer task function _coroutine:_timer_task_set(task) self._TIMER_TASK = task end -- tostring(coroutine) function _coroutine:__tostring() return string.format("<co: %s/%s>", self:name(), self:status()) end -- gc(coroutine) function _coroutine:__gc() self._THREAD = nil end -- get the timer of scheduler function scheduler:_timer() local t = self._TIMER if t == nil then t = timer:new() self._TIMER = t end return t end -- get poller object data for socket, pipe, process, fwatcher object function scheduler:_poller_data(obj) return self._POLLERDATA and self._POLLERDATA[obj] or nil end -- set poller object data -- -- data.co_recv: the suspended coroutine for waiting poller/recv -- data.co_send: the suspended coroutine for waiting poller/send -- data.poller_events_wait: the waited events for poller -- data.poller_events_save: the saved events for poller (triggered) -- function scheduler:_poller_data_set(obj, data) local pollerdata = self._POLLERDATA if not pollerdata then pollerdata = {} self._POLLERDATA = pollerdata end pollerdata[obj] = data end -- resume the suspended coroutine after poller callback function scheduler:_poller_resume_co(co, events) -- cancel timer task if exists local timer_task = co:_timer_task() if timer_task then timer_task.cancel = true end -- the scheduler has been stopped? mark events as error to stop the coroutine if not self._STARTED then events = poller.EV_POLLER_ERROR end -- this coroutine must be suspended, (maybe also dead) if not co:is_suspended() then return false, string.format("%s cannot be resumed, status: %s", co, co:status()) end -- resume this coroutine task co:waitobj_set(nil) return self:co_resume(co, (bit.band(events, poller.EV_POLLER_ERROR) ~= 0) and -1 or events) end -- the poller events callback function scheduler:_poller_events_cb(obj, events) -- get poller object data local pollerdata = self:_poller_data(obj) if not pollerdata then return false, string.format("%s: cannot get poller data!", obj) end -- is process/fwatcher object? if obj:otype() == poller.OT_PROC or obj:otype() == poller.OT_FWATCHER then -- resume coroutine and return the process exit status/fwatcher event pollerdata.object_event = events -- waiting process/fwatcher? resume this coroutine if pollerdata.co_waiting then local co_waiting = pollerdata.co_waiting pollerdata.co_waiting = nil return self:_poller_resume_co(co_waiting, 1) else pollerdata.object_pending = 1 end return true end -- get poller object events local events_prev_wait = pollerdata.poller_events_wait local events_prev_save = pollerdata.poller_events_save -- eof for edge trigger? if bit.band(events, poller.EV_POLLER_EOF) ~= 0 then -- cache this eof as next recv/send event events = bit.band(events, bit.bnot(poller.EV_POLLER_EOF)) events_prev_save = bit.bor(events_prev_save, events_prev_wait) pollerdata.poller_events_save = events_prev_save end -- get the waiting coroutines local co_recv = bit.band(events, poller.EV_POLLER_RECV) ~= 0 and pollerdata.co_recv or nil local co_send = bit.band(events, poller.EV_POLLER_SEND) ~= 0 and pollerdata.co_send or nil -- return the events result for the waiting coroutines if co_recv and co_recv == co_send then pollerdata.co_recv = nil pollerdata.co_send = nil return self:_poller_resume_co(co_recv, events) else if co_recv then pollerdata.co_recv = nil local ok, errors = self:_poller_resume_co(co_recv, bit.band(events, bit.bnot(poller.EV_POLLER_SEND))) if not ok then return false, errors end events = bit.band(events, bit.bnot(poller.EV_POLLER_RECV)) end if co_send then pollerdata.co_send = nil local ok, errors = self:_poller_resume_co(co_send, bit.band(events, bit.bnot(poller.EV_POLLER_RECV))) if not ok then return false, errors end events = bit.band(events, bit.bnot(poller.EV_POLLER_SEND)) end -- no coroutines are waiting? cache this events if bit.band(events, poller.EV_POLLER_RECV) ~= 0 or bit.band(events, poller.EV_POLLER_SEND) ~= 0 then events_prev_save = bit.bor(events_prev_save, events) pollerdata.poller_events_save = events_prev_save end end return true end -- update the current directory hash of current coroutine function scheduler:_co_curdir_update(curdir) -- get running coroutine local running = self:co_running() if not running then return end -- save the current directory hash curdir = curdir or os.curdir() local curdir_hash = hash.uuid4(path.absolute(curdir)):sub(1, 8) self._CO_CURDIR_HASH = curdir_hash -- save the current directory for each coroutine local co_curdirs = self._CO_CURDIRS if not co_curdirs then co_curdirs = {} self._CO_CURDIRS = co_curdirs end co_curdirs[running] = {curdir_hash, curdir} end -- update the current environments hash of current coroutine function scheduler:_co_curenvs_update(envs) -- get running coroutine local running = self:co_running() if not running then return end -- save the current directory hash local envs_hash = "" envs = envs or os.getenvs() for _, key in ipairs(table.orderkeys(envs)) do envs_hash = envs_hash .. key:upper() .. envs[key] end envs_hash = hash.uuid4(envs_hash):sub(1, 8) self._CO_CURENVS_HASH = envs_hash -- save the current directory for each coroutine local co_curenvs = self._CO_CURENVS if not co_curenvs then co_curenvs = {} self._CO_CURENVS = co_curenvs end co_curenvs[running] = {envs_hash, envs} end -- resume it's waiting coroutine if all coroutines are dead in group function scheduler:_co_groups_resume() local resumed_count = 0 local co_groups = self._CO_GROUPS if co_groups then local co_groups_waiting = self._CO_GROUPS_WAITING local co_resumed_list = {} for name, co_group in pairs(co_groups) do -- get coroutine and limit in waiting group local item = co_groups_waiting and co_groups_waiting[name] or nil if item then local co_waiting = item[1] local limit = item[2] -- get dead coroutines count in this group local count = 0 for _, co in ipairs(co_group) do if count < limit then if co:is_dead() then count = count + 1 end else break end end -- resume the waiting coroutine of this group if some coroutines are dead in this group if count >= limit and co_waiting and co_waiting:is_suspended() then resumed_count = resumed_count + 1 self._CO_GROUPS_WAITING[name] = nil table.insert(co_resumed_list, co_waiting) end end end if #co_resumed_list > 0 then for _, co_waiting in ipairs(co_resumed_list) do local ok, errors = self:co_resume(co_waiting) if not ok then return -1, errors end end end end return resumed_count end -- get profiler function scheduler:_profiler() local profiler = self._PROFILE if profiler == nil then profiler = require("base/profiler") if not profiler:enabled() then profiler = false end end return profiler or nil end -- start a new coroutine task function scheduler:co_start(cotask, ...) return self:co_start_named(nil, cotask, ...) end -- start a new named coroutine task function scheduler:co_start_named(coname, cotask, ...) return self:co_start_withopt({name = coname}, cotask, ...) end -- start a new coroutine task with options function scheduler:co_start_withopt(opt, cotask, ...) -- check coroutine task opt = opt or {} local coname = opt.name if not cotask then return nil, string.format("cannot start coroutine, invalid cotask(%s/%s)", coname and coname or "anonymous", cotask) end -- start coroutine local co co = _coroutine.new(coname, coroutine.create(function(...) local profiler = self:_profiler() if profiler and profiler:enabled() then profiler:start() end self:_co_curdir_update() self:_co_curenvs_update() cotask(...) self:co_tasks()[co:thread()] = nil if self:co_count() > 0 then self._CO_COUNT = self:co_count() - 1 end end)) if opt.isolate then co:isolate(true) end self:co_tasks()[co:thread()] = co self._CO_COUNT = self:co_count() + 1 if self._STARTED then local ok, errors = self:co_resume(co, ...) if not ok then return nil, errors end else self._CO_READY_TASKS = self._CO_READY_TASKS or {} table.insert(self._CO_READY_TASKS, {co, table.pack(...)}) end -- add this coroutine to the pending groups local co_groups_pending = self._CO_GROUPS_PENDING if co_groups_pending then for _, co_group_pending in pairs(co_groups_pending) do table.insert(co_group_pending, co) end end return co end -- resume the given coroutine function scheduler:co_resume(co, ...) -- do resume local ok, errors = coroutine.resume(co:thread(), ...) local running = self:co_running() if running then -- has the current directory been changed? restore it local curdir = self._CO_CURDIR_HASH local olddir = self._CO_CURDIRS and self._CO_CURDIRS[running] or nil if olddir and curdir ~= olddir[1] then -- hash changed? os.cd(olddir[2]) end -- has the current environments been changed? restore it local curenvs = self._CO_CURENVS_HASH local oldenvs = self._CO_CURENVS and self._CO_CURENVS[running] or nil if oldenvs and curenvs ~= oldenvs[1] and running:is_isolated() then -- hash changed? os.setenvs(oldenvs[2]) end end return ok, errors end -- suspend the current coroutine function scheduler:co_suspend(...) -- suspend it local results = table.pack(coroutine.yield(...)) -- has the current directory been changed? restore it local running = assert(self:co_running()) local curdir = self._CO_CURDIR_HASH local olddir = self._CO_CURDIRS and self._CO_CURDIRS[running] or nil if olddir and curdir ~= olddir[1] then -- hash changed? os.cd(olddir[2]) end -- has the current environments been changed? restore it local curenvs = self._CO_CURENVS_HASH local oldenvs = self._CO_CURENVS and self._CO_CURENVS[running] or nil if oldenvs and curenvs ~= oldenvs[1] and running:is_isolated() then -- hash changed? os.setenvs(oldenvs[2]) end -- return results return table.unpack(results) end -- yield the current coroutine function scheduler:co_yield() return scheduler.co_sleep(self, 1) end -- sleep some times (ms) function scheduler:co_sleep(ms) -- we don't need to sleep if ms == 0 then return true end -- get the running coroutine local running = self:co_running() if not running then return false, "we must call sleep() in coroutine with scheduler!" end -- is stopped? if not self._STARTED then return false, "the scheduler is stopped!" end -- register timeout task to timer self:_timer():post(function (cancel) if running:is_suspended() then return self:co_resume(running) end return true end, ms) -- wait self:co_suspend() return true end -- lock the current coroutine function scheduler:co_lock(lockname) -- get the running coroutine local running = self:co_running() if not running then return false, "we must call co_lock() in coroutine with scheduler!" end -- is stopped? if not self._STARTED then return false, "the scheduler is stopped!" end -- do lock local co_locked_tasks = self._CO_LOCKED_TASKS if co_locked_tasks == nil then co_locked_tasks = {} self._CO_LOCKED_TASKS = co_locked_tasks end while true do -- try to lock it if co_locked_tasks[lockname] == nil then co_locked_tasks[lockname] = running return true -- has been locked by the current coroutine elseif co_locked_tasks[lockname] == running then return true end -- register timeout task to timer local function timer_callback (cancel) if co_locked_tasks[lockname] == nil then if running:is_suspended() then return self:co_resume(running) end else self:_timer():post(timer_callback, 500) end return true end self:_timer():post(timer_callback, 500) -- wait self:co_suspend() end return true end -- unlock the current coroutine function scheduler:co_unlock(lockname) -- get the running coroutine local running = self:co_running() if not running then return false, "we must call co_unlock() in coroutine with scheduler!" end -- is stopped? if not self._STARTED then return false, "the scheduler is stopped!" end -- do unlock local co_locked_tasks = self._CO_LOCKED_TASKS if co_locked_tasks == nil then co_locked_tasks = {} self._CO_LOCKED_TASKS = co_locked_tasks end if co_locked_tasks[lockname] == nil then return false, string.format("we need to call lock(%s) first before calling unlock(%s)", lockname, lockname) end if co_locked_tasks[lockname] == running then co_locked_tasks[lockname] = nil else return false, string.format("unlock(%s) is called in other %s", lockname, running) end return true end -- get the given coroutine group function scheduler:co_group(name) return self._CO_GROUPS and self._CO_GROUPS[name] end -- begin coroutine group function scheduler:co_group_begin(name, scopefunc) -- enter groups self._CO_GROUPS = self._CO_GROUPS or {} self._CO_GROUPS_PENDING = self._CO_GROUPS_PENDING or {} if self._CO_GROUPS_PENDING[name] then return false, string.format("co_group(%s): already exists!", name) end self._CO_GROUPS_PENDING[name] = self._CO_GROUPS_PENDING[name] or {} -- call the scope function local co_group = self._CO_GROUPS[name] or {} local ok, errors = utils.trycall(scopefunc, nil, co_group) if not ok then return false, errors end -- leave groups self._CO_GROUPS[name] = co_group table.join2(self._CO_GROUPS[name], self._CO_GROUPS_PENDING[name]) self._CO_GROUPS_PENDING[name] = nil return true end -- wait for finishing the given coroutine group function scheduler:co_group_wait(name, opt) -- get coroutine group local co_group = self:co_group(name) if not co_group or #co_group == 0 then -- no coroutines in this group return true end -- get the running coroutine local running = self:co_running() if not running then return false, "we must call co_group_wait() in coroutine with scheduler!" end -- is stopped? if not self._STARTED then return false, "the scheduler is stopped!" end -- get limit count local limit = opt and opt.limit or #co_group -- wait it local count repeat count = 0 for _, co in ipairs(co_group) do if count < limit then if co:is_dead() then count = count + 1 end else break end end if count < limit then self._CO_GROUPS_WAITING = self._CO_GROUPS_WAITING or {} self._CO_GROUPS_WAITING[name] = {running, limit} self:co_suspend() end until count >= limit -- remove all dead coroutines in group if limit == #co_group and count == limit then self._CO_GROUPS[name] = nil else for i = #co_group, 1, -1 do local co = co_group[i] if co:is_dead() then table.remove(co_group, i) end end end return true end -- get waiting objects for the given group name function scheduler:co_group_waitobjs(name) local objs = hashset.new() for _, co in ipairs(table.wrap(self:co_group(name))) do if not co:is_dead() then local obj = co:waitobj() if obj then objs:insert(obj) end end end return objs end -- get the current running coroutine function scheduler:co_running() if self._ENABLED then local running = coroutine.running() return running and self:co_tasks()[running] or nil end end -- get all coroutine tasks function scheduler:co_tasks() local cotasks = self._CO_TASKS if not cotasks then cotasks = {} self._CO_TASKS = cotasks end return cotasks end -- get all coroutine count function scheduler:co_count() return self._CO_COUNT or 0 end -- wait poller object io events, only for socket and pipe object function scheduler:poller_wait(obj, events, timeout) -- get the running coroutine local running = self:co_running() if not running then return -1, "we must call poller_wait() in coroutine with scheduler!" end -- is stopped? if not self._STARTED then return -1, "the scheduler is stopped!" end -- check the object type local otype = obj:otype() if otype ~= poller.OT_SOCK and otype ~= poller.OT_PIPE then return -1, string.format("%s: invalid object type(%d)!", obj, otype) end -- get and allocate poller object data local pollerdata = self:_poller_data(obj) if not pollerdata then pollerdata = {poller_events_wait = 0, poller_events_save = 0} self:_poller_data_set(obj, pollerdata) end -- enable edge-trigger mode if be supported if self._SUPPORT_EV_POLLER_CLEAR and (otype == poller.OT_SOCK or otype == poller.OT_PIPE) then events = bit.bor(events, poller.EV_POLLER_CLEAR) end -- get the previous poller object events local events_wait = events if pollerdata.poller_events_wait ~= 0 then -- return the cached events directly if the waiting events exists cache local events_prev_wait = pollerdata.poller_events_wait local events_prev_save = pollerdata.poller_events_save if events_prev_save ~= 0 and bit.band(events_prev_wait, events) ~= 0 then -- check error? if bit.band(events_prev_save, poller.EV_POLLER_ERROR) ~= 0 then pollerdata.poller_events_save = 0 return -1, string.format("%s: events error!", obj) end -- clear cache events pollerdata.poller_events_save = bit.band(events_prev_save, bit.bnot(events)) -- return the cached events return bit.band(events_prev_save, events) end -- modify the wait events and reserve the pending events in other coroutine events_wait = events_prev_wait if bit.band(events_wait, poller.EV_POLLER_RECV) ~= 0 and not pollerdata.co_recv then events_wait = bit.band(events_wait, bit.bnot(poller.EV_POLLER_RECV)) end if bit.band(events_wait, poller.EV_POLLER_SEND) ~= 0 and not pollerdata.co_send then events_wait = bit.band(events_wait, bit.bnot(poller.EV_POLLER_SEND)) end events_wait = bit.bor(events_wait, events) -- modify poller object from poller for waiting events if the waiting events has been changed if bit.band(events_prev_wait, events_wait) ~= events_wait then -- maybe wait recv/send at same time local ok, errors = poller:modify(obj, events_wait, self._poller_events_cb) if not ok then return -1, errors end end else -- insert poller object events local ok, errors = poller:insert(obj, events_wait, self._poller_events_cb) if not ok then return -1, errors end end -- register timeout task to timer local timer_task = nil if timeout > 0 then timer_task = self:_timer():post(function (cancel) if not cancel and running:is_suspended() then running:waitobj_set(nil) return self:co_resume(running, 0) end return true end, timeout) end running:_timer_task_set(timer_task) -- save waiting events pollerdata.poller_events_wait = events_wait pollerdata.poller_events_save = 0 -- save the current coroutine if bit.band(events, poller.EV_POLLER_RECV) ~= 0 then pollerdata.co_recv = running end if bit.band(events, poller.EV_POLLER_SEND) ~= 0 then pollerdata.co_send = running end -- save the waiting poller object running:waitobj_set(obj) -- wait return self:co_suspend() end -- wait poller object/process status function scheduler:poller_waitproc(obj, timeout) -- get the running coroutine local running = self:co_running() if not running then return -1, "we must call poller_wait() in coroutine with scheduler!" end -- is stopped? if not self._STARTED then return -1, "the scheduler is stopped!" end -- check the object type local otype = obj:otype() if otype ~= poller.OT_PROC then return -1, string.format("%s: invalid object type(%d)!", obj, otype) end -- get and allocate poller object data local pollerdata = self:_poller_data(obj) if not pollerdata then pollerdata = {object_pending = 0, object_event = 0} self:_poller_data_set(obj, pollerdata) end -- has pending process status? if pollerdata.object_pending ~= 0 then pollerdata.object_pending = 0 return 1, pollerdata.object_event end -- insert poller object to poller for waiting process local ok, errors = poller:insert(obj, 0, self._poller_events_cb) if not ok then return -1, errors end -- register timeout task to timer local timer_task = nil if timeout > 0 then timer_task = self:_timer():post(function (cancel) if not cancel and running:is_suspended() then pollerdata.co_waiting = nil running:waitobj_set(nil) return self:co_resume(running, 0) end return true end, timeout) end running:_timer_task_set(timer_task) -- set process status pollerdata.object_event = 0 pollerdata.object_pending = 0 pollerdata.co_waiting = running -- save the waiting poller object running:waitobj_set(obj) -- wait local ok = self:co_suspend() return ok, pollerdata.object_event end -- wait poller object/fwatcher status function scheduler:poller_waitfs(obj, timeout) -- get the running coroutine local running = self:co_running() if not running then return -1, "we must call poller_wait() in coroutine with scheduler!" end -- is stopped? if not self._STARTED then return -1, "the scheduler is stopped!" end -- check the object type local otype = obj:otype() if otype ~= poller.OT_FWATCHER then return -1, string.format("%s: invalid object type(%d)!", obj, otype) end -- get and allocate poller object data local pollerdata = self:_poller_data(obj) if not pollerdata then pollerdata = {object_pending = 0, object_event = 0} self:_poller_data_set(obj, pollerdata) end -- has pending process status? if pollerdata.object_pending ~= 0 then pollerdata.object_pending = 0 return 1, pollerdata.object_event end -- insert poller object to poller for waiting fwatcher local ok, errors = poller:insert(obj, 0, self._poller_events_cb) if not ok then return -1, errors end -- register timeout task to timer local timer_task = nil if timeout > 0 then timer_task = self:_timer():post(function (cancel) if not cancel and running:is_suspended() then pollerdata.co_waiting = nil running:waitobj_set(nil) return self:co_resume(running, 0) end return true end, timeout) end running:_timer_task_set(timer_task) -- set fwatcher status pollerdata.object_event = 0 pollerdata.object_pending = 0 pollerdata.co_waiting = running -- save the waiting poller object running:waitobj_set(obj) -- wait local ok = self:co_suspend() return ok, pollerdata.object_event end -- cancel poller object events function scheduler:poller_cancel(obj) -- reset the pollerdata data local pollerdata = self:_poller_data(obj) if pollerdata then if pollerdata.poller_events_wait ~= 0 or obj:otype() == poller.OT_PROC or obj:otype() == poller.OT_FWATCHER then local ok, errors = poller:remove(obj) if not ok then return false, errors end end self:_poller_data_set(obj, nil) end return true end -- enable or disable to scheduler function scheduler:enable(enabled) self._ENABLED = enabled end -- stop the scheduler loop function scheduler:stop() -- mark scheduler status as stopped and spank the poller:wait() self._STARTED = false poller:spank() return true end -- run loop, schedule coroutine with socket/io, sub-processes, fwatcher function scheduler:runloop() -- start loop self._STARTED = true self._ENABLED = true -- ensure poller has been initialized first (for windows/iocp) and check edge-trigger mode (for epoll/kqueue) if poller:support(poller.EV_POLLER_CLEAR) then self._SUPPORT_EV_POLLER_CLEAR = true end -- set on change directory callback for scheduler os._sched_chdir_set(function (curdir) self:_co_curdir_update(curdir) end) -- set on change environments callback for scheduler os._sched_chenvs_set(function (envs) self:_co_curenvs_update(envs) end) -- start all ready coroutine tasks local co_ready_tasks = self._CO_READY_TASKS if co_ready_tasks then for _, task in pairs(co_ready_tasks) do local co = task[1] local argv = task[2] local ok, errors = self:co_resume(co, table.unpack(argv)) if not ok then return false, errors end end end self._CO_READY_TASKS = nil -- run loop opt = opt or {} local ok = true local errors = nil local timeout = -1 while self._STARTED and self:co_count() > 0 do -- resume it's waiting coroutine if some coroutines are dead in group local resumed_count, resumed_errors = self:_co_groups_resume() if resumed_count < 0 then ok = false errors = resumed_errors break elseif resumed_count == 0 then -- get the next timeout timeout = self:_timer():delay() or 1000 -- wait events local count, events = poller:wait(timeout) if count < 0 then ok = false errors = events break end -- resume all suspended tasks with events for _, e in ipairs(events) do local obj = e[1] local objevents = e[2] local eventfunc = e[3] if eventfunc then ok, errors = eventfunc(self, obj, objevents) if not ok then -- This causes a direct exit from the entire runloop and -- a quick escape from nested try-catch blocks and coroutines groups. -- -- So some try-catch cannot catch these errors, such as when a build fails (in build group). -- @see https://github.com/xmake-io/xmake/issues/3401 -- -- We should catch it in coroutines and re-throw it outside scheduler, -- it will avoid co_resume to get and return this error. -- -- e.g. we can see runjobs.lua implementation break end end end if not ok then break end end -- spank the timer and trigger all timeout tasks ok, errors = self:_timer():next() if not ok then break end end -- mark the loop as stopped first self._STARTED = false -- cancel all timeout tasks and trigger them self:_timer():kill() -- finished and we need not resume other pending coroutines, because xmake will be aborted directly if fails return ok, errors end -- return module: scheduler return scheduler
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/colors.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 colors.lua -- -- define module local colors = colors or {} -- load modules local tty -- lazy loading it local emoji = require("base/emoji") -- the color8 keys -- -- from https://github.com/hoelzro/ansicolors -- colors._keys8 = { -- attributes reset = 0 , clear = 0 , default = 0 , bright = 1 , dim = 2 , underline = 4 , blink = 5 , reverse = 7 , hidden = 8 -- foreground , black = 30 , red = 31 , green = 32 , yellow = 33 , blue = 34 , magenta = 35 , cyan = 36 , white = 37 -- background , onblack = 40 , onred = 41 , ongreen = 42 , onyellow = 43 , onblue = 44 , onmagenta = 45 , oncyan = 46 , onwhite = 47 } -- the color256 keys -- -- from https://github.com/hoelzro/ansicolors -- colors._keys256 = { -- attributes reset = 0 , clear = 0 , default = 0 , bright = 1 , dim = 2 , underline = 4 , blink = 5 , reverse = 7 , hidden = 8 -- foreground , black = "38;5;0" , red = "38;5;1" , green = "38;5;2" , yellow = "38;5;3" , blue = "38;5;4" , magenta = "38;5;5" , cyan = "38;5;6" , white = "38;5;7" -- background , onblack = "48;5;0" , onred = "48;5;1" , ongreen = "48;5;2" , onyellow = "48;5;3" , onblue = "48;5;4" , onmagenta = "48;5;5" , oncyan = "48;5;6" , onwhite = "48;5;7" } -- the 24bits color keys -- -- from https://github.com/hoelzro/ansicolors -- colors._keys24 = { -- attributes reset = 0 , clear = 0 , default = 0 , bright = 1 , dim = 2 , underline = 4 , blink = 5 , reverse = 7 , hidden = 8 -- foreground , black = "38;2;0;0;0" , red = "38;2;255;0;0" , green = "38;2;0;255;0" , yellow = "38;2;255;255;0" , blue = "38;2;0;0;255" , magenta = "38;2;255;0;255" , cyan = "38;2;0;255;255" , white = "38;2;255;255;255" -- background , onblack = "48;2;0;0;0" , onred = "48;2;255;0;0" , ongreen = "48;2;0;255;0" , onyellow = "48;2;255;255;0" , onblue = "48;2;0;0;255" , onmagenta = "48;2;255;0;255" , oncyan = "48;2;0;255;255" , onwhite = "48;2;255;255;255" } -- the escape string colors._ESC = '\x1b[%sm' -- make rainbow truecolor code by the index of characters -- -- @param index the index of characters -- @param seed the seed, 0-255, default: random -- @param freq the frequency, default: 0.1 -- @param spread the spread, default: 3.0 -- -- function colors.rainbow24(index, seed, freq, spread) -- init values seed = seed freq = freq or 0.1 spread = spread or 3.0 index = seed + index / spread -- make colors local red = math.sin(freq * index + 0) * 127 + 128 local green = math.sin(freq * index + 2 * math.pi / 3) * 127 + 128 local blue = math.sin(freq * index + 4 * math.pi / 3) * 127 + 128 -- make code return string.format("%d;%d;%d", math.floor(red), math.floor(green), math.floor(blue)) end -- make rainbow color256 code by the index of characters (16-256) -- -- @param index the index of characters -- @param seed the seed, 0-255, default: random -- @param freq the frequency, default: 0.1 -- @param spread the spread, default: 3.0 -- -- function colors.rainbow256(index, seed, freq, spread) -- init values seed = seed freq = freq or 0.1 spread = spread or 3.0 index = seed + index / spread -- make color code local code = math.floor((freq * index) % 240 + 18) -- make code return string.format("#%d", code) end -- translate colors from the string -- -- @param str the string with colors -- @param opt options -- patch_reset: wrap str with `"${reset}"`? -- ignore_unknown: ignore unknown codes like `"${unknown_code}"`? -- plain: false -- -- 8 colors: -- -- "${red}hello" -- "${onred}hello${clear} xmake" -- "${bright red underline}hello" -- "${dim red}hello" -- "${blink red}hello" -- "${reverse red}hello xmake" -- -- 256 colors: -- -- "${#255}hello" -- "${on#255}hello${clear} xmake" -- "${bright #255; underline}hello" -- "${bright on#255 #10}hello${clear} xmake" -- -- true colors: -- -- "${255;0;0}hello" -- "${on;255;0;0}hello${clear} xmake" -- "${bright 255;0;0 underline}hello" -- "${bright on;255;0;0 0;255;0}hello${clear} xmake" -- -- emoji: -- -- "${beer}hello${beer}world" -- -- theme: -- "${color.error}" -- "${bright color.warning}" -- -- text: -- "${hello xmake}" -- "${hello xmake $beer}" -- function colors.translate(str, opt) -- check string if not str then return nil end opt = opt or {} -- get theme local theme = colors.theme() -- patch reset if opt.patch_reset ~= false then str = "${reset}" .. str .. "${reset}" end -- translate color blocks, e.g. ${red}, ${color.xxx}, ${emoji} tty = tty or require("base/tty") local has_color8 = tty.has_color8() local has_color256 = tty.has_color256() local has_color24 = tty.has_color24() local has_emoji = tty.has_emoji() str = str:gsub("(%${(.-)})", function(_, word) -- not supported? ignore it local nocolors = false if not has_color8 and not has_color256 and not has_color24 then nocolors = true end -- is plain theme? no colors and no emoji local noemoji = not has_emoji if opt.plain or (theme and theme:name() == "plain") then nocolors = true noemoji = true end -- get keys local keys = has_color256 and colors._keys256 or colors._keys8 if has_color24 then keys = colors._keys24 end -- split words local blocks_raw = word:split(' ', {plain = true}) -- translate theme color first, e.g ${color.error} local blocks = {} for _, block in ipairs(blocks_raw) do if theme then local theme_block = theme:get(block) if theme_block then for _, theme_block_sub in ipairs(theme_block:split(' ', {plain = true})) do table.insert(blocks, theme_block_sub) end else table.insert(blocks, block) end elseif block:startswith("color.") or block:startswith("text.") then local default_theme = {["color.error"] = "red", ["color.warning"] = "yellow", ["text.error"] = "error", ["text.warning"] = "warning"} local theme_block = default_theme[block] if theme_block then table.insert(blocks, theme_block) else table.insert(blocks, block) end else table.insert(blocks, block) end end -- make color buffer local text_buffer = {} local color_buffer = {} for _, block in ipairs(blocks) do -- get the color code local code = keys[block] if not code then if has_color24 and block:find(";", 1, true) then if block:startswith("on;") then code = block:gsub("on;", "48;2;") else code = "38;2;" .. block end elseif has_color256 and block:find("#", 1, true) then if block:startswith("on#") then code = block:gsub("on#", "48;5;") else code = block:gsub("#", "38;5;") end elseif block:startswith("$") then -- plain text, do not translate emoji table.insert(text_buffer, block:sub(2)) elseif not noemoji then -- get emoji code local emoji_code = emoji.translate(block) if emoji_code then table.insert(text_buffer, emoji_code) elseif not opt.ignore_unknown then -- unknown code, regard as plain text table.insert(text_buffer, block) end elseif not opt.ignore_unknown then table.insert(text_buffer, block) end end -- save this code table.insert(color_buffer, code) end -- make result local result = "" if #color_buffer > 0 and not nocolors then result = result .. colors._ESC:format(table.concat(color_buffer, ";")) end if #text_buffer > 0 then result = result .. table.concat(text_buffer, " ") end return result end) return str end -- ignore all colors function colors.ignore(str) if str then -- strip "${red}" and "${theme color}" str = colors.translate(str, {plain = true}) -- strip color code, e.g. for clang/gcc color diagnostics output return (str:gsub("\x1b%[.-m", "")) end end -- get theme function colors.theme() return colors._THEME end -- set theme function colors.theme_set(theme) colors._THEME = theme end -- return module return colors
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/signal.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 signal.lua -- -- define module: signal local signal = signal or {} -- load modules local os = require("base/os") -- signal code signal.SIGINT = 2 -- register signal handler function signal.register(signo, handler) os.signal(signo, handler) end -- reset signal, SIGDFL function signal.reset(signo) os.signal(signo, 1) end -- ignore signal, SIGIGN function signal.ignore(signo) os.signal(signo, 2) end -- return module: signal return signal
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/utils.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 utils.lua -- -- define module local utils = utils or {} -- load modules local option = require("base/option") local colors = require("base/colors") local string = require("base/string") local log = require("base/log") local io = require("base/io") local dump = require("base/dump") local text = require("base/text") -- dump values function utils.dump(...) if option.get("quiet") then return ... end local diagnosis = option.get("diagnosis") -- show caller info if diagnosis then local info = debug.getinfo(2) local line = info.currentline if not line or line < 0 then line = info.linedefined end io.write(string.format("dump from %s %s:%s\n", info.name or "<anonymous>", info.source, line)) end local values = table.pack(...) if values.n == 0 then return end if values.n == 1 then dump(values[1], "", diagnosis) else for i = 1, values.n do dump(values[i], string.format("%2d: ", i), diagnosis) end end return table.unpack(values, 1, values.n) end -- print string with newline function utils._print(...) -- print it if not quiet if not option.get("quiet") then local values = {...} for i, v in ipairs(values) do -- dump basic type if type(v) == "string" or type(v) == "boolean" or type(v) == "number" then io.write(tostring(v)) -- dump table elseif type(v) == "table" then dump(v) else io.write("<" .. tostring(v) .. ">") end if i ~= #values then io.write(" ") end end io.write('\n') end end -- print string without newline function utils._iowrite(...) -- print it if not quiet if not option.get("quiet") then io.write(...) end end -- decode errors if errors is encoded table string function utils._decode_errors(errors) if not errors then return end local _, pos = errors:find("[@encode(error)]: ", 1, true) if pos then -- strip traceback (maybe from coroutine.resume) local errs = errors:sub(pos + 1) local stack = nil local stackpos = errs:find("}\nstack traceback:", 1, true) if stackpos and stackpos > 1 then stack = errs:sub(stackpos + 2) errs = errs:sub(1, stackpos) end errors, errs = errs:deserialize() if not errors then errors = errs end if type(errors) == "table" then if stack then errors._stack = stack end setmetatable(errors, { __tostring = function (self) local result = self.errors if not result then result = string.serialize(self, {strip = true, indent = false}) end result = result or "" if self._stack then result = result .. "\n" .. self._stack end return result end, __concat = function (self, other) return tostring(self) .. tostring(other) end }) end return errors end end -- print format string with newline function utils.print(format, ...) assert(format) local message = string.tryformat(format, ...) utils._print(message) log:printv(message) end -- print format string without newline function utils.printf(format, ...) assert(format) local message = string.tryformat(format, ...) utils._iowrite(message) log:write(message) end -- print format string and colors with newline function utils.cprint(format, ...) assert(format) local message = string.tryformat(format, ...) utils._print(colors.translate(message)) if log:file() then log:printv(colors.ignore(message)) end end -- print format string and colors without newline function utils.cprintf(format, ...) assert(format) local message = string.tryformat(format, ...) utils._iowrite(colors.translate(message)) if log:file() then log:write(colors.ignore(message)) end end -- print the verbose information function utils.vprint(format, ...) if (option.get("verbose") or option.get("diagnosis")) and format ~= nil then utils.print(format, ...) end end -- print the verbose information without newline function utils.vprintf(format, ...) if (option.get("verbose") or option.get("diagnosis")) and format ~= nil then utils.printf(format, ...) end end -- print the error information function utils.error(format, ...) if format ~= nil then local errors = string.tryformat(format, ...) local decoded_errors = utils._decode_errors(errors) if decoded_errors then errors = tostring(decoded_errors) end utils.cprint("${bright color.error}${text.error}: ${clear}" .. errors) log:flush() end end -- add warning message function utils.warning(format, ...) assert(format) -- format message local args = table.pack(...) local msg = (args.n > 0 and string.tryformat(format, ...) or format) -- init warnings local warnings = utils._WARNINGS if not warnings then warnings = {} utils._WARNINGS = warnings end -- add warning msg table.insert(warnings, msg) end -- show warnings function utils.show_warnings() local warnings = utils._WARNINGS if warnings then for idx, msg in ipairs(table.unique(warnings)) do if not option.get("verbose") and idx > 1 then utils.cprint("${bright color.warning}${text.warning}: ${color.warning}add -v for getting more warnings ..") break end utils.cprint("${bright color.warning}${text.warning}: ${color.warning}%s", msg) end end end -- try to call script function utils.trycall(script, traceback, ...) return xpcall(script, function (errors) -- get traceback traceback = traceback or debug.traceback -- decode it if errors is encoded table string local decoded_errors = utils._decode_errors(errors) if decoded_errors then return decoded_errors end return traceback(errors) end, ...) end -- get confirm result -- -- @code -- if utils.confirm({description = "xmake.lua not found, try generating it", default = true}) then -- TODO -- end -- @endcode -- function utils.confirm(opt) -- init options opt = opt or {} -- get default local default = opt.default if default == nil then default = false end -- get description local description = opt.description or "" -- get confirm result local result = option.get("yes") or option.get("confirm") if type(result) == "string" then result = result:lower() if result == "d" or result == "def" then result = default else result = nil end end -- get user confirm if result == nil then -- show tips if type(description) == "function" then description() else utils.cprint("${bright color.warning}note: ${clear}%s (pass -y or --confirm=y/n/d to skip confirm)?", description) end -- get answer if opt.answer then result = opt.answer() else utils.cprint("please input: ${bright}%s${clear} (y/n)", default and "y" or "n") io.flush() result = option.boolean((io.read() or "false"):trim()) if type(result) ~= "boolean" then result = default end end end return result end function utils.table(data, opt) utils.printf(text.table(data, opt)) end function utils.vtable(data, opt) utils.vprintf(text.table(data, opt)) end -- return module return utils
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/scopeinfo.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 scopeinfo.lua -- -- define module local scopeinfo = scopeinfo or {} local _instance = _instance or {} -- load modules local io = require("base/io") local os = require("base/os") local path = require("base/path") local table = require("base/table") local utils = require("base/utils") local deprecated = require("base/deprecated") -- new an instance function _instance.new(kind, info, opt) opt = opt or {} local instance = table.inherit(_instance) instance._KIND = kind or "root" instance._INFO = info instance._INTERPRETER = opt.interpreter instance._DEDUPLICATE = opt.deduplicate instance._ENABLE_FILTER = opt.enable_filter return instance end -- get apis function _instance:_apis() local interp = self:interpreter() if interp then return interp:api_definitions() end end -- get the given api type function _instance:_api_type(name) local apis = self:_apis() if apis then return apis[self:kind() .. '.' .. name] end end -- handle the api values function _instance:_api_handle(name, values) local interp = self:interpreter() if interp then -- remove repeat first for each slice with deleted item (__remove_xxx) if self._DEDUPLICATE and not table.is_dictionary(values) then local policy = interp:deduplication_policy(name) if policy ~= false then local unique_func = policy == "toleft" and table.reverse_unique or table.unique values = unique_func(values, function (v) return type(v) == "string" and v:startswith("__remove_") end) end end -- filter values if self._ENABLE_FILTER then values = interp:_filter(values) end end -- unwrap it if be only one return table.unwrap(values) end -- save api source info, e.g. call api() in sourcefile:linenumber function _instance:_api_save_sourceinfo_to_scope(scope, apiname, values) -- save api source info, e.g. call api() in sourcefile:linenumber local sourceinfo = debug.getinfo(5, "Sl") if sourceinfo then scope["__sourceinfo_" .. apiname] = scope["__sourceinfo_" .. apiname] or {} local sourcescope = scope["__sourceinfo_" .. apiname] for _, value in ipairs(values) do if type(value) == "string" then sourcescope[value] = {file = sourceinfo.short_src or sourceinfo.source, line = sourceinfo.currentline} end end end end -- set the api values to the scope info function _instance:_api_set_values(name, ...) -- get the scope info local scope = self._INFO -- get extra config local values = {...} local extra_config = values[#values] if table.is_dictionary(extra_config) then table.remove(values) else extra_config = nil end -- @note we need to mark table value as meta object to avoid wrap/unwrap -- if these values cannot be expanded, especially when there is only one value -- -- e.g. target:set("shflags", {"-Wl,-exported_symbols_list", exportfile}, {force = true, expand = false}) if extra_config and extra_config.expand == false then for _, value in ipairs(values) do table.wrap_lock(value) end else -- expand values values = table.join(table.unpack(values)) end -- handle values local handled_values = self:_api_handle(name, values) -- save values if type(handled_values) == "table" and table.empty(handled_values) then -- set("xx", nil)? remove it scope[name] = nil else scope[name] = handled_values end -- save extra config if extra_config then scope["__extra_" .. name] = scope["__extra_" .. name] or {} local extrascope = scope["__extra_" .. name] for _, value in ipairs(values) do extrascope[value] = extra_config end end end -- add the api values to the scope info function _instance:_api_add_values(name, ...) -- get the scope info local scope = self._INFO -- get extra config local values = {...} local extra_config = values[#values] if table.is_dictionary(extra_config) then table.remove(values) else extra_config = nil end -- @note we need to mark table value as meta object to avoid wrap/unwrap -- if these values cannot be expanded, especially when there is only one value -- -- e.g. target:add("shflags", {"-Wl,-exported_symbols_list", exportfile}, {force = true, expand = false}) if extra_config and extra_config.expand == false then for _, value in ipairs(values) do table.wrap_lock(value) end else -- expand values values = table.join(table.unpack(values)) end -- save values scope[name] = self:_api_handle(name, table.join2(table.wrap(scope[name]), values)) -- save extra config if extra_config then scope["__extra_" .. name] = scope["__extra_" .. name] or {} local extrascope = scope["__extra_" .. name] for _, value in ipairs(values) do extrascope[value] = extra_config end end end -- set the api groups to the scope info function _instance:_api_set_groups(name, ...) -- get the scope info local scope = self._INFO -- get extra config local values = {...} local extra_config = values[#values] if table.is_dictionary(extra_config) then table.remove(values) else extra_config = nil end -- expand values values = table.join(table.unpack(values)) -- save values table.wrap_lock(values) scope[name] = values scope[name] = self:_api_handle(name, scope[name]) -- save extra config if extra_config then scope["__extra_" .. name] = scope["__extra_" .. name] or {} local extrascope = scope["__extra_" .. name] local key = table.concat(values, "_") extrascope[key] = extra_config end end -- add the api groups to the scope info function _instance:_api_add_groups(name, ...) -- get the scope info local scope = self._INFO -- get extra config local values = {...} local extra_config = values[#values] if table.is_dictionary(extra_config) then table.remove(values) else extra_config = nil end -- expand values values = table.join(table.unpack(values)) -- save values -- -- @note maybe scope[name] has been unwrapped, we need wrap it first -- https://github.com/xmake-io/xmake/issues/4428 scope[name] = table.wrap(scope[name]) table.wrap_lock(values) table.insert(scope[name], values) scope[name] = self:_api_handle(name, scope[name]) -- save extra config if extra_config then scope["__extra_" .. name] = scope["__extra_" .. name] or {} local extrascope = scope["__extra_" .. name] local key = table.concat(values, "_") extrascope[key] = extra_config end end -- set the api key-values to the scope info function _instance:_api_set_keyvalues(name, key, ...) -- get the scope info local scope = self._INFO -- get extra config local values = {...} local extra_config = values[#values] if table.is_dictionary(extra_config) then table.remove(values) else extra_config = nil end -- save values to "name" scope[name] = scope[name] or {} scope[name][key] = self:_api_handle(name, values) -- save values to "name.key" local name_key = name .. "." .. key scope[name_key] = scope[name][key] -- fix override attributes scope["__override_" .. name] = false scope["__override_" .. name_key] = true -- save extra config if extra_config then scope["__extra_" .. name_key] = scope["__extra_" .. name_key] or {} local extrascope = scope["__extra_" .. name_key] for _, value in ipairs(values) do extrascope[value] = extra_config end end end -- add the api key-values to the scope info function _instance:_api_add_keyvalues(name, key, ...) -- get the scope info local scope = self._INFO -- get extra config local values = {...} local extra_config = values[#values] if table.is_dictionary(extra_config) then table.remove(values) else extra_config = nil end -- save values to "name" scope[name] = scope[name] or {} if scope[name][key] == nil then scope[name][key] = self:_api_handle(name, values) else scope[name][key] = self:_api_handle(name, table.join2(table.wrap(scope[name][key]), values)) end -- save values to "name.key" local name_key = name .. "." .. key scope[name_key] = scope[name][key] -- save extra config if extra_config then scope["__extra_" .. name_key] = scope["__extra_" .. name_key] or {} local extrascope = scope["__extra_" .. name_key] for _, value in ipairs(values) do extrascope[value] = extra_config end end end -- set the api dictionary to the scope info function _instance:_api_set_dictionary(name, dict_or_key, value, extra_config) -- get the scope info local scope = self._INFO -- check if type(dict_or_key) == "table" then local dict = {} for k, v in pairs(dict_or_key) do dict[k] = self:_api_handle(name, v) end scope[name] = dict elseif type(dict_or_key) == "string" and value ~= nil then scope[name] = {[dict_or_key] = self:_api_handle(name, value)} -- save extra config if extra_config and table.is_dictionary(extra_config) then scope["__extra_" .. name] = scope["__extra_" .. name] or {} local extrascope = scope["__extra_" .. name] extrascope[dict_or_key] = extra_config end else -- error os.raise("%s:set(%s, ...): invalid value type!", self:kind(), name, type(dict)) end end -- add the api dictionary to the scope info function _instance:_api_add_dictionary(name, dict_or_key, value, extra_config) -- get the scope info local scope = self._INFO -- check scope[name] = scope[name] or {} if type(dict_or_key) == "table" then local dict = {} for k, v in pairs(dict_or_key) do dict[k] = self:_api_handle(name, v) end table.join2(scope[name], dict) elseif type(dict_or_key) == "string" and value ~= nil then scope[name][dict_or_key] = self:_api_handle(name, value) -- save extra config if extra_config and table.is_dictionary(extra_config) then scope["__extra_" .. name] = scope["__extra_" .. name] or {} local extrascope = scope["__extra_" .. name] extrascope[dict_or_key] = extra_config end else -- error os.raise("%s:add(%s, ...): invalid value type!", self:kind(), name, type(dict)) end end -- set the api paths to the scope info function _instance:_api_set_paths(name, ...) -- get the scope info local scope = self._INFO -- get interpreter local interp = self:interpreter() -- get extra config local values = {...} local extra_config = values[#values] if table.is_dictionary(extra_config) then table.remove(values) else extra_config = nil end -- expand values values = table.join(table.unpack(values)) -- translate paths local paths = interp:_api_translate_paths(values, "set_" .. name, 5) -- save values scope[name] = self:_api_handle(name, paths) -- save extra config if extra_config then scope["__extra_" .. name] = scope["__extra_" .. name] or {} local extrascope = scope["__extra_" .. name] for _, value in ipairs(paths) do extrascope[value] = extra_config end end -- save api source info, e.g. call api() in sourcefile:linenumber self:_api_save_sourceinfo_to_scope(scope, name, paths) end -- add the api paths to the scope info function _instance:_api_add_paths(name, ...) -- get the scope info local scope = self._INFO -- get interpreter local interp = self:interpreter() -- get extra config local values = {...} local extra_config = values[#values] if table.is_dictionary(extra_config) then table.remove(values) else extra_config = nil end -- expand values values = table.join(table.unpack(values)) -- translate paths local paths = interp:_api_translate_paths(values, "add_" .. name, 5) -- save values scope[name] = self:_api_handle(name, table.join2(table.wrap(scope[name]), paths)) -- save extra config if extra_config then scope["__extra_" .. name] = scope["__extra_" .. name] or {} local extrascope = scope["__extra_" .. name] for _, value in ipairs(paths) do extrascope[value] = extra_config end end -- save api source info, e.g. call api() in sourcefile:linenumber self:_api_save_sourceinfo_to_scope(scope, name, paths) end -- remove the api paths to the scope info (deprecated) function _instance:_api_del_paths(name, ...) -- get the scope info local scope = self._INFO -- get interpreter local interp = self:interpreter() -- expand values values = table.join(...) -- it has been marked as deprecated deprecated.add("remove_" .. name .. "(%s)", "del_" .. name .. "(%s)", table.concat(values, ", "), table.concat(values, ", ")) -- translate paths local paths = interp:_api_translate_paths(values, "del_" .. name, 5) -- mark these paths as deleted local paths_deleted = {} for _, pathname in ipairs(paths) do table.insert(paths_deleted, "__remove_" .. pathname) end -- save values scope[name] = self:_api_handle(name, table.join2(table.wrap(scope[name]), paths_deleted)) -- save api source info, e.g. call api() in sourcefile:linenumber self:_api_save_sourceinfo_to_scope(scope, name, paths) end -- remove the api paths to the scope info function _instance:_api_remove_paths(name, ...) -- get the scope info local scope = self._INFO -- get interpreter local interp = self:interpreter() -- expand values values = table.join(...) -- translate paths local paths = interp:_api_translate_paths(values, "remove_" .. name, 5) -- mark these paths as removed local paths_removed = {} for _, pathname in ipairs(paths) do table.insert(paths_removed, "__remove_" .. pathname) end -- save values scope[name] = self:_api_handle(name, table.join2(table.wrap(scope[name]), paths_removed)) -- save api source info, e.g. call api() in sourcefile:linenumber self:_api_save_sourceinfo_to_scope(scope, name, paths) end -- get the scope kind function _instance:kind() return self._KIND end -- is root scope? function _instance:is_root() return self:kind() == "root" end -- get all scope info function _instance:info() return self._INFO end -- get interpreter function _instance:interpreter() return self._INTERPRETER end -- get the scope info from the given name function _instance:get(name) return self._INFO[name] end -- set the value to the scope info function _instance:set(name, value) self._INFO[name] = value end -- set the api values to the scope info function _instance:apival_set(name, ...) if type(name) == "string" then local api_type = self:_api_type("set_" .. name) if api_type then local set_xxx = self["_api_set_" .. api_type] if set_xxx then set_xxx(self, name, ...) else os.raise("unknown apitype(%s) for %s:set(%s, ...)", api_type, self:kind(), name) end else -- unknown api values? only set values self:_api_set_values(name, ...) end -- set array, e.g. set({{links = ..}, {links = ..}}) elseif table.is_array(name) then local array = name for _, dict in ipairs(array) do for k, v in pairs(dict) do self:apival_set(k, table.unpack(table.wrap(v))) end end -- set dictionary, e.g. set({links = ..}) elseif table.is_dictionary(name) then local dict = name for k, v in pairs(dict) do self:apival_set(k, table.unpack(table.wrap(v))) end elseif name ~= nil then os.raise("unknown type(%s) for %s:set(%s, ...)", type(name), self:kind(), name) end end -- add the api values to the scope info function _instance:apival_add(name, ...) if type(name) == "string" then local api_type = self:_api_type("add_" .. name) if api_type then local add_xxx = self["_api_add_" .. api_type] if add_xxx then add_xxx(self, name, ...) else os.raise("unknown apitype(%s) for %s:add(%s, ...)", api_type, self:kind(), name) end else -- unknown api values? only add values self:_api_add_values(name, ...) end -- add array, e.g. add({{links = ..}, {links = ..}}) elseif table.is_array(name) then local array = name for _, dict in ipairs(array) do for k, v in pairs(dict) do self:apival_add(k, table.unpack(table.wrap(v))) end end -- add dictionary, e.g. add({links = ..}) elseif table.is_dictionary(name) then local dict = name for k, v in pairs(dict) do self:apival_add(k, table.unpack(table.wrap(v))) end elseif name ~= nil then os.raise("unknown type(%s) for %s:add(%s, ...)", type(name), self:kind(), name) end end -- remove the api values to the scope info (deprecated) function _instance:apival_del(name, ...) if type(name) == "string" then local api_type = self:_api_type("del_" .. name) if api_type then local del_xxx = self["_api_remove_" .. api_type] if del_xxx then del_xxx(self, name, ...) else os.raise("unknown apitype(%s) for %s:del(%s, ...)", api_type, self:kind(), name) end else os.raise("unknown api(%s) for %s:del(%s, ...)", name, self:kind(), name) end elseif name ~= nil then -- TODO os.raise("cannot support to remove a dictionary!") end end -- remove the api values to the scope info function _instance:apival_remove(name, ...) if type(name) == "string" then local api_type = self:_api_type("remove_" .. name) if api_type then local remove_xxx = self["_api_remove_" .. api_type] if remove_xxx then remove_xxx(self, name, ...) else os.raise("unknown apitype(%s) for %s:remove(%s, ...)", api_type, self:kind(), name) end else os.raise("unknown api(%s) for %s:remove(%s, ...)", name, self:kind(), name) end elseif name ~= nil then -- TODO os.raise("cannot support to remove a dictionary!") end end -- get the extra configuration -- -- e.g. -- -- add_includedirs("inc", {public = true}) -- -- function (target) -- _instance:extraconf("includedirs", "inc", "public") -> true -- _instance:extraconf("includedirs", "inc") -> {public = true} -- _instance:extraconf("includedirs") -> {inc = {public = true}} -- end -- function _instance:extraconf(name, item, key) -- get extra configurations local extraconfs = self._EXTRACONFS if not extraconfs then extraconfs = {} self._EXTRACONFS = extraconfs end -- get configuration local extraconf = extraconfs[name] if not extraconf then extraconf = self:get("__extra_" .. name) extraconfs[name] = extraconf end -- get configuration value local value = extraconf if item then value = extraconf and extraconf[item] or nil if value == nil and extraconf and type(item) == "table" then value = extraconf[table.concat(item, "_")] end if value and key then value = value[key] end end return value end -- set the extra configuration -- -- e.g. -- -- add_includedirs("inc", {public = true}) -- -- function (target) -- _instance:extraconf_set("includedirs", "inc", "public", true) -- _instance:extraconf_set("includedirs", "inc", {public = true}) -- _instance:extraconf_set("includedirs", {inc = {public = true}}) -- end -- function _instance:extraconf_set(name, item, key, value) if key ~= nil then local extraconf = self:get("__extra_" .. name) or {} if value ~= nil then extraconf[item] = extraconf[item] or {} extraconf[item][key] = value else extraconf[item] = key end self:set("__extra_" .. name, extraconf) else self:set("__extra_" .. name, item) end end -- get configuration source information of the given api item -- -- e.g. -- self:get("defines", "TEST") -- - add_defines("TEST") -- - src/xmake.lua:10 -- function _instance:sourceinfo(name, item) return (self:get("__sourceinfo_" .. name) or {})[item] end -- clone a new instance from the current function _instance:clone() return _instance.new(self:kind(), table.clone(self:info(), 3), { -- @note we need do deep clone interpreter = self:interpreter(), deduplicate = self._DEDUPLICATE, enable_filter = self._ENABLE_FILTER}) end -- new a scope instance function scopeinfo.new(...) return _instance.new(...) end -- return module return scopeinfo
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/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 -- -- define module: object local object = object or {} -- taken from 'std' library: http://luaforge.net/projects/stdlib/ -- and http://lua-cui.sourceforge.net/ -- -- local point = object { _init = {"x", "y"} } -- -- local p1 = point {1, 2} -- > p1 {x = 1, y = 2} -- -- permute some indices of a table local function permute (p, t) local u = {} for i, v in pairs (t) do if p[i] ~= nil then u[p[i]] = v else u[i] = v end end return u end -- make a shallow copy of a table, including any local function clone (t) local u = setmetatable ({}, getmetatable (t)) for i, v in pairs (t) do u[i] = v end return u end -- merge two tables -- -- If there are duplicate fields, u's will be used. The metatable of -- the returned table is that of t -- local function merge (t, u) local r = clone (t) for i, v in pairs (u) do r[i] = v end return r end -- root object -- -- List of fields to be initialised by the -- constructor: assuming the default _clone, the -- numbered values in an object constructor are -- assigned to the fields given in _init -- local object = { _init = {} } setmetatable (object, object) -- object constructor -- -- @param initial values for fields in -- -- @return new object -- function object:_clone (values) local object = merge(self, permute(self._init, values or {})) return setmetatable (object, object) end -- local x = object {} function object.__call (...) return (...)._clone (...) end -- return module: object return object
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/log.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. --o -- @author ruki -- @file log.lua -- -- define module: log local log = log or {} -- get the log file function log:file() -- disable? if self._ENABLE ~= nil and not self._ENABLE then return end -- get the output file if self._FILE == nil then local outputfile = self:outputfile() if outputfile then -- get directory local i = outputfile:lastof("[/\\]") if i then if i > 1 then i = i - 1 end dir = outputfile:sub(1, i) else dir = "." end -- ensure the directory if not os.isdir(dir) then os.mkdir(dir) end -- open the log file self._FILE = io.open(outputfile, 'w+') end self._FILE = self._FILE or false end return self._FILE end -- get the output file function log:outputfile() if self._LOGFILE == nil then self._LOGFILE = os.getenv("XMAKE_LOGFILE") or false end return self._LOGFILE end -- clear log function log:clear(state) if os.isfile(self:outputfile()) then io.writefile(self:outputfile(), "") end end -- enable log function log:enable(state) self._ENABLE = state end -- flush log to file function log:flush() local file = self:file() if file then file:flush() end end -- close the log file function log:close() local file = self:file() if file then file:close() end end -- print log to the log file function log:print(...) local file = self:file() if file then file:write(string.format(...) .. "\n") end end -- print variables to the log file function log:printv(...) local file = self:file() if file then local values = {...} for i, v in ipairs(values) do -- dump basic type if type(v) == "string" or type(v) == "boolean" or type(v) == "number" then file:write(tostring(v)) else file:write("<" .. tostring(v) .. ">") end if i ~= #values then file:write(" ") end end file:write('\n') end end -- printf log to the log file function log:printf(...) local file = self:file() if file then file:write(string.format(...)) end end -- write log the log file function log:write(...) local file = self:file() if file then file:write(...) end end -- return module: log return log
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/macos.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 macos.lua -- -- define module: macos local macos = macos or {} -- load modules local os = require("base/os") local semver = require("base/semver") -- get system version function macos.version() -- get it from cache first if macos._VERSION ~= nil then return macos._VERSION end -- get mac version local macver = nil local ok, verstr = os.iorun("sw_vers -productVersion") if ok and verstr then macver = semver.new(verstr:trim()) end macos._VERSION = macver or false return macver end -- return module: macos return macos
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/cpu.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 cpu.lua -- -- define module local cpu = cpu or {} -- load modules local os = require("base/os") local winos = require("base/winos") local io = require("base/io") local hashset = require("base/hashset") -- get cpu micro architecture for Intel -- -- @see https://en.wikichip.org/wiki/intel/cpuid -- https://github.com/xmake-io/xmake/issues/1120 -- function cpu._march_intel() local cpu_family = cpu.family() local cpu_model = cpu.model() if cpu_family == 3 then return "80386" elseif cpu_family == 4 then if cpu_model >= 1 and cpu_model <= 9 then return "80486" end elseif cpu_family == 5 then if cpu_model == 9 or cpu_model == 10 then return "Lakemont" elseif cpu_model == 1 or cpu_model == 2 or cpu_model == 4 or cpu_model == 7 or cpu_model == 8 then return "P5" end elseif cpu_family == 6 then -- mic architecture if cpu_model == 133 then return "Knights Mill" elseif cpu_model == 87 then return "Knights Landing" end -- small cores if cpu_model == 134 then return "Tremont" elseif cpu_model == 122 then return "Goldmont Plus" elseif cpu_model == 95 or cpu_model == 92 then return "Goldmont" elseif cpu_model == 76 then return "Airmont" elseif cpu_model == 93 or cpu_model == 90 or cpu_model == 77 or cpu_model == 74 or cpu_model == 55 then return "Silvermont" elseif cpu_model == 54 or cpu_model == 53 or cpu_model == 39 then return "Saltwell" elseif cpu_model == 38 or cpu_model == 28 then return "Bonnell" end -- big cores if cpu_model == 183 then return "Raptor Lake" elseif cpu_model == 151 or cpu_model == 154 then return "Alder Lake" elseif cpu_model == 167 then return "Rocket Lake" elseif cpu_model == 140 then return "Tiger Lake" elseif cpu_model == 126 or cpu_model == 125 then return "Ice Lake" elseif cpu_model == 165 then return "Comet Lake" elseif cpu_model == 102 then return "Cannon Lake" elseif cpu_model == 142 or cpu_model == 158 then return "Kaby Lake" elseif cpu_model == 94 or cpu_model == 78 or cpu_model == 85 then return "Skylake" elseif cpu_model == 71 or cpu_model == 61 or cpu_model == 79 or cpu_model == 86 then return "Broadwell" elseif cpu_model == 70 or cpu_model == 69 or cpu_model == 60 or cpu_model == 63 then return "Haswell" elseif cpu_model == 58 or cpu_model == 62 then return "Ivy Bridge" elseif cpu_model == 42 or cpu_model == 45 then return "Sandy Bridge" elseif cpu_model == 37 or cpu_model == 44 or cpu_model == 47 then return "Westmere" elseif cpu_model == 31 or cpu_model == 30 or cpu_model == 46 or cpu_model == 26 then return "Nehalem" elseif cpu_model == 23 or cpu_model == 29 then return "Penryn" elseif cpu_model == 22 or cpu_model == 15 then return "Core" elseif cpu_model == 14 then return "Modified Pentium M" elseif cpu_model == 21 or cpu_model == 13 or cpu_model == 9 then return "Pentium M" elseif cpu_model == 11 or cpu_model == 10 or cpu_model == 8 or cpu_model == 7 or cpu_model == 6 or cpu_model == 5 or cpu_model == 1 then return "P6" end elseif cpu_family == 7 then -- TODO Itanium elseif cpu_family == 11 then if cpu_model == 0 then return "knights-ferry" elseif cpu_model == 1 then return "knights-corner" end elseif cpu_family == 15 then if cpu_model <= 6 then return "netburst" end end end -- get cpu micro architecture for AMD -- -- @see https://en.wikichip.org/wiki/amd/cpuid -- function cpu._march_amd() local cpu_family = cpu.family() local cpu_model = cpu.model() if cpu_family == 25 then return "Zen 3" elseif cpu_family == 24 then return "Zen" elseif cpu_family == 23 then if cpu_model == 144 or cpu_model == 113 or cpu_model == 96 or cpu_model == 49 then return "Zen 2" elseif cpu_model == 24 or cpu_model == 8 then return "Zen+" else return "Zen" end elseif cpu_family == 22 then return "AMD 16h" elseif cpu_family == 21 then if cpu_model < 2 then return "Bulldozer" else -- TODO and Steamroller, Excavator .. return "Piledriver" end elseif cpu_family == 20 then return "Bobcat" elseif cpu_family == 16 then return "K10" elseif cpu_family == 15 then if cpu_model > 64 then return "K8-sse3" else return "K8" end end end -- get cpu info function cpu._info() local cpuinfo = cpu._CPUINFO if cpuinfo == nil then cpuinfo = {} if os.host() == "macosx" then local ok, sysctl_result = os.iorun("/usr/sbin/sysctl -n machdep.cpu.vendor machdep.cpu.model machdep.cpu.family machdep.cpu.features machdep.cpu.brand_string") if ok and sysctl_result then sysctl_result = sysctl_result:trim():split('\n', {plain = true}) cpuinfo.vendor_id = sysctl_result[1] cpuinfo.cpu_model = sysctl_result[2] cpuinfo.cpu_family = sysctl_result[3] cpuinfo.cpu_features = sysctl_result[4] if cpuinfo.cpu_features then cpuinfo.cpu_features = cpuinfo.cpu_features:lower():gsub("%.", "_") end cpuinfo.cpu_model_name = sysctl_result[5] end elseif os.host() == "linux" then -- FIXME -- local proc_cpuinfo = io.readfile("/proc/cpuinfo") local ok, proc_cpuinfo = os.iorun("cat /proc/cpuinfo") if ok and proc_cpuinfo then for _, line in ipairs(proc_cpuinfo:split('\n', {plain = true})) do if not cpuinfo.vendor_id and line:startswith("vendor_id") then cpuinfo.vendor_id = line:match("vendor_id%s+:%s+(.*)") end if not cpuinfo.cpu_model and line:startswith("model") then cpuinfo.cpu_model = line:match("model%s+:%s+(.*)") end if not cpuinfo.cpu_model_name and line:startswith("model name") then cpuinfo.cpu_model_name = line:match("model name%s+:%s+(.*)") end if not cpuinfo.cpu_family and line:startswith("cpu family") then cpuinfo.cpu_family = line:match("cpu family%s+:%s+(.*)") end if not cpuinfo.cpu_features and line:startswith("flags") then cpuinfo.cpu_features = line:match("flags%s+:%s+(.*)") end -- termux on android if not cpuinfo.cpu_features and line:startswith("Features") then cpuinfo.cpu_features = line:match("Features%s+:%s+(.*)") end end end elseif os.host() == "windows" then cpuinfo.vendor_id = winos.registry_query("HKEY_LOCAL_MACHINE\\Hardware\\Description\\System\\CentralProcessor\\0;VendorIdentifier") cpuinfo.cpu_model_name = winos.registry_query("HKEY_LOCAL_MACHINE\\Hardware\\Description\\System\\CentralProcessor\\0;ProcessorNameString") local cpu_id = winos.registry_query("HKEY_LOCAL_MACHINE\\Hardware\\Description\\System\\CentralProcessor\\0;Identifier") if cpu_id then local cpu_family, cpu_model = cpu_id:match("Family (%d+) Model (%d+)") cpuinfo.cpu_family = cpu_family cpuinfo.cpu_model = cpu_model end elseif os.host() == "bsd" then local ok, dmesginfo = os.iorun("dmesg") if ok and dmesginfo then for _, line in ipairs(dmesginfo:split('\n', {plain = true})) do if not cpuinfo.vendor_id and line:find("Origin=", 1, true) then cpuinfo.vendor_id = line:match("Origin=\"(.-)\"") end if not cpuinfo.cpu_model and line:find("Model=", 1, true) then cpuinfo.cpu_model = line:match("Model=([%d%w]+)") end if not cpuinfo.cpu_family and line:find("Family=", 1, true) then cpuinfo.cpu_family = line:match("Family=([%d%w]+)") end if line:find("Features=", 1, true) then local cpu_features = line:match("Features=.*<(.-)>") if cpu_features then if cpuinfo.cpu_features then cpuinfo.cpu_features = cpuinfo.cpu_features .. "," .. cpu_features else cpuinfo.cpu_features = cpu_features end end end end if cpuinfo.cpu_features then cpuinfo.cpu_features = cpuinfo.cpu_features:lower():gsub(",", " ") end local ok, cpu_model_name = os.iorun("sysctl -n hw.model") if ok and cpu_model_name then cpuinfo.cpu_model_name = cpu_model_name:trim() end end end cpu._CPUINFO = cpuinfo end return cpuinfo end -- get cpu stats info function cpu._statinfo(name) local stats = cpu._STATS local stime = cpu._STIME if stats == nil or stime == nil or os.time() - stime > 1 then -- cache 1s stats = os._cpuinfo() cpu._STATS = stats cpu._STIME = os.time() end if name then return stats[name] else return stats end end -- get vendor id function cpu.vendor() return cpu._info().vendor_id end -- get cpu model function cpu.model() local cpu_model = cpu._info().cpu_model return cpu_model and tonumber(cpu_model) end -- get cpu model name function cpu.model_name() return cpu._info().cpu_model_name end -- get cpu family function cpu.family() local cpu_family = cpu._info().cpu_family return cpu_family and tonumber(cpu_family) end -- get cpu features function cpu.features() return cpu._info().cpu_features end -- has the given feature? function cpu.has_feature(name) local features = cpu._FEATURES if not features then features = cpu.features() if features then features = hashset.from(features:split('%s')) end cpu._FEATURES = features end return features:has(name) end -- get cpu micro architecture function cpu.march() local march = cpu._MARCH if march == nil then local cpu_vendor = cpu.vendor() if cpu_vendor == "GenuineIntel" then march = cpu._march_intel() elseif cpu_vendor == "AuthenticAMD" then march = cpu._march_amd() end cpu._MARCH = march end return march end -- get cpu number function cpu.number() return cpu._statinfo("ncpu") end -- get cpu usage rate function cpu.usagerate() return cpu._statinfo("usagerate") end -- get cpu info function cpu.info(name) local cpuinfo = {} cpuinfo.vendor = cpu.vendor() cpuinfo.model = cpu.model() cpuinfo.family = cpu.family() cpuinfo.march = cpu.march() cpuinfo.ncpu = cpu.number() cpuinfo.features = cpu.features() cpuinfo.usagerate = cpu.usagerate() cpuinfo.model_name = cpu.model_name() if name then return cpuinfo[name] else return cpuinfo end end -- return module return cpu
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/emoji.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 emoji.lua -- -- define module local emoji = emoji or {} -- the emoji keys -- -- from http://www.emoji-cheat-sheet.com/ -- and https://weechat.org/files/scripts/pending/emoji.lua -- emoji.keys = { four="4⃣",kiss_ww="👩❤💋👩",maple_leaf="🍁",waxing_gibbous_moon="🌔",bike="🚲",recycle="♻",family_mwgb="👨👩👧👦",flag_dk="🇩🇰",thought_balloon="💭",oncoming_automobile="🚘",guardsman_tone5="💂🏿",tickets="🎟",school="🏫",house_abandoned="🏚",blue_book="📘",video_game="🎮",triumph="😤",suspension_railway="🚟",umbrella="☔",levitate="🕴",cactus="🌵",monorail="🚝",stars="🌠",new="🆕",herb="🌿",pouting_cat="😾",blue_heart="💙",["100"]="💯",leaves="🍃",family_mwbb="👨👩👦👦",information_desk_person_tone2="💁🏼",dragon_face="🐲",track_next="⏭",cloud_snow="🌨",flag_jp="🇯🇵",children_crossing="🚸",information_desk_person_tone1="💁🏻",arrow_up_down="↕",mount_fuji="🗻",massage_tone1="💆🏻",flag_mq="🇲🇶",massage_tone3="💆🏽",massage_tone2="💆🏼",massage_tone5="💆🏿",flag_je="🇯🇪",flag_jm="🇯🇲",flag_jo="🇯🇴",red_car="🚗",hospital="🏥",red_circle="🔴",princess="👸",tm="™",curly_loop="➰",boy_tone5="👦🏿",pouch="👝",boy_tone3="👦🏽",boy_tone1="👦🏻",izakaya_lantern="🏮",fist_tone5="✊🏿",fist_tone4="✊🏾",fist_tone1="✊🏻",fist_tone3="✊🏽",fist_tone2="✊🏼",arrow_lower_left="↙",game_die="🎲",pushpin="📌",dividers="🗂",dolphin="🐬",night_with_stars="🌃",cruise_ship="🛳",white_medium_small_square="◽",kissing_closed_eyes="😚",earth_americas="🌎",["end"]="🔚",mouse="🐭",rewind="⏪",beach="🏖",pizza="🍕",briefcase="💼",customs="🛃",heartpulse="💗",sparkler="🎇",sparkles="✨",hand_splayed_tone1="🖐🏻",snowman2="☃",tulip="🌷",speaking_head="🗣",ambulance="🚑",office="🏢",clapper="🎬",keyboard="⌨",japan="🗾",post_office="🏣",dizzy_face="😵",imp="👿",flag_ve="🇻🇪",coffee="☕",flag_vg="🇻🇬",flag_va="🇻🇦",flag_vc="🇻🇨",flag_vn="🇻🇳",flag_vi="🇻🇮",open_mouth="😮",flag_vu="🇻🇺",page_with_curl="📃",bank="🏦",bread="🍞",oncoming_police_car="🚔",capricorn="♑",point_left="👈",tokyo_tower="🗼",fishing_pole_and_fish="🎣",thumbsdown="👎",telescope="🔭",spider="🕷",u7121="🈚",camera_with_flash="📸",lifter="🏋",sweet_potato="🍠",lock_with_ink_pen="🔏",ok_woman_tone2="🙆🏼",ok_woman_tone3="🙆🏽",smirk="😏",baggage_claim="🛄",cherry_blossom="🌸",sparkle="❇",zap="⚡",construction_site="🏗",dancers="👯",flower_playing_cards="🎴",hatching_chick="🐣",free="🆓",bullettrain_side="🚄",poultry_leg="🍗",grapes="🍇",smirk_cat="😼",lollipop="🍭",water_buffalo="🐃",black_medium_small_square="◾",atm="🏧",gift_heart="💝",older_woman_tone5="👵🏿",older_woman_tone4="👵🏾",older_woman_tone1="👵🏻",older_woman_tone3="👵🏽",older_woman_tone2="👵🏼",scissors="✂",woman_tone2="👩🏼",basketball="🏀",hammer_pick="⚒",top="🔝",clock630="🕡",raising_hand_tone5="🙋🏿",railway_track="🛤",nail_care="💅",crossed_flags="🎌",minibus="🚐",white_sun_cloud="🌥",shower="🚿",smile_cat="😸",dog2="🐕",loud_sound="🔊",kaaba="🕋",runner="🏃",ram="🐏",writing_hand="✍",rat="🐀",rice_scene="🎑",milky_way="🌌",vulcan_tone5="🖖🏿",necktie="👔",kissing_cat="😽",snowflake="❄",paintbrush="🖌",crystal_ball="🔮",mountain_bicyclist_tone4="🚵🏾",mountain_bicyclist_tone3="🚵🏽",mountain_bicyclist_tone2="🚵🏼",mountain_bicyclist_tone1="🚵🏻",koko="🈁",flag_it="🇮🇹",flag_iq="🇮🇶",flag_is="🇮🇸",flag_ir="🇮🇷",flag_im="🇮🇲",flag_il="🇮🇱",flag_io="🇮🇴",flag_in="🇮🇳",flag_ie="🇮🇪",flag_id="🇮🇩",flag_ic="🇮🇨",ballot_box_with_check="☑",mountain_bicyclist_tone5="🚵🏿",metal="🤘",dog="🐶",pineapple="🍍",no_good_tone3="🙅🏽",no_good_tone2="🙅🏼",no_good_tone1="🙅🏻",scream="😱",no_good_tone5="🙅🏿",no_good_tone4="🙅🏾",flag_ua="🇺🇦",bomb="💣",flag_ug="🇺🇬",flag_um="🇺🇲",flag_us="🇺🇸",construction_worker_tone1="👷🏻",radio="📻",flag_uy="🇺🇾",flag_uz="🇺🇿",person_with_blond_hair_tone1="👱🏻",cupid="💘",mens="🚹",rice="🍚",point_right_tone1="👉🏻",point_right_tone3="👉🏽",point_right_tone2="👉🏼",sunglasses="😎",point_right_tone4="👉🏾",watch="⌚",frowning="😦",watermelon="🍉",wedding="💒",person_frowning_tone4="🙍🏾",person_frowning_tone5="🙍🏿",person_frowning_tone2="🙍🏼",person_frowning_tone3="🙍🏽",person_frowning_tone1="🙍🏻",flag_gw="🇬🇼",flag_gu="🇬🇺",flag_gt="🇬🇹",flag_gs="🇬🇸",flag_gr="🇬🇷",flag_gq="🇬🇶",flag_gp="🇬🇵",flag_gy="🇬🇾",flag_gg="🇬🇬",flag_gf="🇬🇫",microscope="🔬",flag_gd="🇬🇩",flag_gb="🇬🇧",flag_ga="🇬🇦",flag_gn="🇬🇳",flag_gm="🇬🇲",flag_gl="🇬🇱",japanese_ogre="👹",flag_gi="🇬🇮",flag_gh="🇬🇭",man_with_turban="👳",star_and_crescent="☪",writing_hand_tone3="✍🏽",dromedary_camel="🐪",hash="#⃣",hammer="🔨",hourglass="⌛",postbox="📮",writing_hand_tone5="✍🏿",writing_hand_tone4="✍🏾",wc="🚾",aquarius="♒",couple_with_heart="💑",ok_woman="🙆",raised_hands_tone4="🙌🏾",cop="👮",raised_hands_tone1="🙌🏻",cow="🐮",raised_hands_tone3="🙌🏽",white_large_square="⬜",pig_nose="🐽",ice_skate="⛸",hotsprings="♨",tone5="🏿",three="3⃣",beer="🍺",stadium="🏟",airplane_departure="🛫",heavy_division_sign="➗",flag_black="🏴",mushroom="🍄",record_button="⏺",vulcan="🖖",dash="💨",wind_chime="🎐",anchor="⚓",seven="7⃣",flag_hr="🇭🇷",roller_coaster="🎢",pen_ballpoint="🖊",sushi="🍣",flag_ht="🇭🇹",flag_hu="🇭🇺",flag_hk="🇭🇰",dizzy="💫",flag_hn="🇭🇳",flag_hm="🇭🇲",arrow_forward="▶",violin="🎻",orthodox_cross="☦",id="🆔",heart_decoration="💟",first_quarter_moon="🌓",satellite="📡",tone3="🏽",christmas_tree="🎄",unicorn="🦄",broken_heart="💔",ocean="🌊",hearts="♥",snowman="⛄",person_with_blond_hair_tone4="👱🏾",person_with_blond_hair_tone5="👱🏿",person_with_blond_hair_tone2="👱🏼",person_with_blond_hair_tone3="👱🏽",yen="💴",straight_ruler="📏",sleepy="😪",green_apple="🍏",white_medium_square="◻",flag_fr="🇫🇷",grey_exclamation="❕",innocent="😇",flag_fm="🇫🇲",flag_fo="🇫🇴",flag_fi="🇫🇮",flag_fj="🇫🇯",flag_fk="🇫🇰",menorah="🕎",yin_yang="☯",clock130="🕜",gift="🎁",prayer_beads="📿",stuck_out_tongue="😛",om_symbol="🕉",city_dusk="🌆",massage_tone4="💆🏾",couple_ww="👩❤👩",crown="👑",sparkling_heart="💖",clubs="♣",person_with_pouting_face="🙎",newspaper2="🗞",fog="🌫",dango="🍡",large_orange_diamond="🔶",flag_tn="🇹🇳",flag_to="🇹🇴",point_up="☝",flag_tm="🇹🇲",flag_tj="🇹🇯",flag_tk="🇹🇰",flag_th="🇹🇭",flag_tf="🇹🇫",flag_tg="🇹🇬",corn="🌽",flag_tc="🇹🇨",flag_ta="🇹🇦",flag_tz="🇹🇿",flag_tv="🇹🇻",flag_tw="🇹🇼",flag_tt="🇹🇹",flag_tr="🇹🇷",eight_spoked_asterisk="✳",trophy="🏆",black_small_square="▪",o="⭕",no_bell="🔕",curry="🍛",alembic="⚗",sob="😭",waxing_crescent_moon="🌒",tiger2="🐅",two="2⃣",sos="🆘",compression="🗜",heavy_multiplication_x="✖",tennis="🎾",fireworks="🎆",skull_crossbones="☠",astonished="😲",congratulations="㊗",grey_question="❔",arrow_upper_left="↖",arrow_double_up="⏫",triangular_flag_on_post="🚩",gemini="♊",door="🚪",ship="🚢",point_down_tone3="👇🏽",point_down_tone4="👇🏾",point_down_tone5="👇🏿",movie_camera="🎥",ng="🆖",couple_mm="👨❤👨",football="🏈",asterisk="*⃣",taurus="♉",articulated_lorry="🚛",police_car="🚓",flushed="😳",spades="♠",cloud_lightning="🌩",wine_glass="🍷",clock830="🕣",punch_tone2="👊🏼",punch_tone3="👊🏽",punch_tone1="👊🏻",department_store="🏬",punch_tone4="👊🏾",punch_tone5="👊🏿",crocodile="🐊",white_square_button="🔳",hole="🕳",boy_tone2="👦🏼",mountain_cableway="🚠",melon="🍈",persevere="😣",trident="🔱",head_bandage="🤕",u7a7a="🈳",cool="🆒",high_brightness="🔆",deciduous_tree="🌳",white_flower="💮",gun="🔫",flag_sk="🇸🇰",flag_sj="🇸🇯",flag_si="🇸🇮",flag_sh="🇸🇭",flag_so="🇸🇴",flag_sn="🇸🇳",flag_sm="🇸🇲",flag_sl="🇸🇱",flag_sc="🇸🇨",flag_sb="🇸🇧",flag_sa="🇸🇦",flag_sg="🇸🇬",flag_tl="🇹🇱",flag_se="🇸🇪",arrow_left="⬅",flag_sz="🇸🇿",flag_sy="🇸🇾",small_orange_diamond="🔸",flag_ss="🇸🇸",flag_sr="🇸🇷",flag_sv="🇸🇻",flag_st="🇸🇹",file_folder="📁",flag_td="🇹🇩",["1234"]="🔢",smiling_imp="😈",surfer_tone2="🏄🏼",surfer_tone3="🏄🏽",surfer_tone4="🏄🏾",surfer_tone5="🏄🏿",amphora="🏺",baseball="⚾",boy="👦",flag_es="🇪🇸",raised_hands="🙌",flag_eu="🇪🇺",flag_et="🇪🇹",heavy_plus_sign="➕",bow="🙇",flag_ea="🇪🇦",flag_ec="🇪🇨",flag_ee="🇪🇪",light_rail="🚈",flag_eg="🇪🇬",flag_eh="🇪🇭",massage="💆",man_with_gua_pi_mao_tone4="👲🏾",man_with_gua_pi_mao_tone3="👲🏽",outbox_tray="📤",clock330="🕞",projector="📽",sake="🍶",confounded="😖",angry="😠",iphone="📱",sweat_smile="😅",aries="♈",ear_of_rice="🌾",mouse2="🐁",bicyclist_tone4="🚴🏾",bicyclist_tone5="🚴🏿",guardsman="💂",bicyclist_tone1="🚴🏻",bicyclist_tone2="🚴🏼",bicyclist_tone3="🚴🏽",envelope="✉",money_with_wings="💸",beers="🍻",heart_exclamation="❣",notepad_spiral="🗒",cat="🐱",running_shirt_with_sash="🎽",ferry="⛴",spy="🕵",chart_with_upwards_trend="📈",green_heart="💚",confused="😕",angel_tone4="👼🏾",scorpius="♏",sailboat="⛵",elephant="🐘",map="🗺",disappointed_relieved="😥",flag_xk="🇽🇰",motorway="🛣",sun_with_face="🌞",birthday="🎂",mag="🔍",date="📅",dove="🕊",man="👨",octopus="🐙",wheelchair="♿",truck="🚚",sa="🈂",shield="🛡",haircut="💇",last_quarter_moon_with_face="🌜",rosette="🏵",currency_exchange="💱",mailbox_with_no_mail="📭",bath="🛀",clock930="🕤",bowling="🎳",turtle="🐢",pause_button="⏸",construction_worker="👷",unlock="🔓",anger_right="🗯",beetle="🐞",girl="👧",sunrise="🌅",exclamation="❗",flag_dz="🇩🇿",family_mmgg="👨👨👧👧",factory="🏭",flag_do="🇩🇴",flag_dm="🇩🇲",flag_dj="🇩🇯",mouse_three_button="🖱",flag_dg="🇩🇬",flag_de="🇩🇪",star_of_david="✡",reminder_ribbon="🎗",grimacing="😬",thumbsup_tone3="👍🏽",thumbsup_tone2="👍🏼",thumbsup_tone1="👍🏻",musical_note="🎵",thumbsup_tone5="👍🏿",thumbsup_tone4="👍🏾",high_heel="👠",green_book="📗",headphones="🎧",flag_aw="🇦🇼",stop_button="⏹",yum="😋",flag_aq="🇦🇶",warning="⚠",cheese="🧀",ophiuchus="⛎",revolving_hearts="💞",one="1⃣",ring="💍",point_right="👉",sheep="🐑",bookmark="🔖",spider_web="🕸",eyes="👀",flag_ro="🇷🇴",flag_re="🇷🇪",flag_rs="🇷🇸",sweat_drops="💦",flag_ru="🇷🇺",flag_rw="🇷🇼",middle_finger="🖕",race_car="🏎",evergreen_tree="🌲",biohazard="☣",girl_tone3="👧🏽",scream_cat="🙀",computer="💻",hourglass_flowing_sand="⏳",flag_lb="🇱🇧",tophat="🎩",clock1230="🕧",tractor="🚜",u6709="🈶",u6708="🈷",crying_cat_face="😿",angel="👼",ant="🐜",information_desk_person="💁",anger="💢",mailbox_with_mail="📬",pencil2="✏",wink="😉",thermometer="🌡",relaxed="☺",printer="🖨",credit_card="💳",checkered_flag="🏁",family_mmg="👨👨👧",pager="📟",family_mmb="👨👨👦",radioactive="☢",fried_shrimp="🍤",link="🔗",walking="🚶",city_sunset="🌇",shopping_bags="🛍",hockey="🏒",arrow_up="⬆",gem="💎",negative_squared_cross_mark="❎",worried="😟",walking_tone5="🚶🏿",walking_tone1="🚶🏻",hear_no_evil="🙉",convenience_store="🏪",seat="💺",girl_tone1="👧🏻",cloud_rain="🌧",girl_tone2="👧🏼",girl_tone5="👧🏿",girl_tone4="👧🏾",parking="🅿",pisces="♓",calendar="📆",loudspeaker="📢",camping="🏕",bicyclist="🚴",label="🏷",diamonds="♦",older_man_tone1="👴🏻",older_man_tone3="👴🏽",older_man_tone2="👴🏼",older_man_tone5="👴🏿",older_man_tone4="👴🏾",microphone2="🎙",raising_hand="🙋",hot_pepper="🌶",guitar="🎸",tropical_drink="🍹",upside_down="🙃",restroom="🚻",pen_fountain="🖋",comet="☄",cancer="♋",jeans="👖",flag_qa="🇶🇦",boar="🐗",turkey="🦃",person_with_blond_hair="👱",oden="🍢",stuck_out_tongue_closed_eyes="😝",helicopter="🚁",control_knobs="🎛",performing_arts="🎭",tiger="🐯",foggy="🌁",sound="🔉",flag_cz="🇨🇿",flag_cy="🇨🇾",flag_cx="🇨🇽",speech_balloon="💬",seedling="🌱",flag_cr="🇨🇷",envelope_with_arrow="📩",flag_cp="🇨🇵",flag_cw="🇨🇼",flag_cv="🇨🇻",flag_cu="🇨🇺",flag_ck="🇨🇰",flag_ci="🇨🇮",flag_ch="🇨🇭",flag_co="🇨🇴",flag_cn="🇨🇳",flag_cm="🇨🇲",u5408="🈴",flag_cc="🇨🇨",flag_ca="🇨🇦",flag_cg="🇨🇬",flag_cf="🇨🇫",flag_cd="🇨🇩",purse="👛",telephone="☎",sleeping="😴",point_down_tone1="👇🏻",frowning2="☹",point_down_tone2="👇🏼",muscle_tone4="💪🏾",muscle_tone5="💪🏿",synagogue="🕍",muscle_tone1="💪🏻",muscle_tone2="💪🏼",muscle_tone3="💪🏽",clap_tone5="👏🏿",clap_tone4="👏🏾",clap_tone1="👏🏻",train2="🚆",clap_tone2="👏🏼",oil="🛢",diamond_shape_with_a_dot_inside="💠",barber="💈",metal_tone3="🤘🏽",ice_cream="🍨",rowboat_tone4="🚣🏾",burrito="🌯",metal_tone1="🤘🏻",joystick="🕹",rowboat_tone1="🚣🏻",taxi="🚕",u7533="🈸",racehorse="🐎",snowboarder="🏂",thinking="🤔",wave_tone1="👋🏻",wave_tone2="👋🏼",wave_tone3="👋🏽",wave_tone4="👋🏾",wave_tone5="👋🏿",desktop="🖥",stopwatch="⏱",pill="💊",skier="⛷",orange_book="📙",dart="🎯",disappointed="😞",grin="😁",place_of_worship="🛐",japanese_goblin="👺",arrows_counterclockwise="🔄",laughing="😆",clap="👏",left_right_arrow="↔",japanese_castle="🏯",nail_care_tone4="💅🏾",nail_care_tone5="💅🏿",nail_care_tone2="💅🏼",nail_care_tone3="💅🏽",nail_care_tone1="💅🏻",raised_hand_tone4="✋🏾",raised_hand_tone5="✋🏿",raised_hand_tone1="✋🏻",raised_hand_tone2="✋🏼",raised_hand_tone3="✋🏽",point_left_tone3="👈🏽",point_left_tone2="👈🏼",tanabata_tree="🎋",point_left_tone5="👈🏿",point_left_tone4="👈🏾",o2="🅾",knife="🔪",volcano="🌋",kissing_heart="😘",on="🔛",ok="🆗",package="📦",island="🏝",arrow_right="➡",chart_with_downwards_trend="📉",haircut_tone3="💇🏽",wolf="🐺",ox="🐂",dagger="🗡",full_moon_with_face="🌝",syringe="💉",flag_by="🇧🇾",flag_bz="🇧🇿",flag_bq="🇧🇶",flag_br="🇧🇷",flag_bs="🇧🇸",flag_bt="🇧🇹",flag_bv="🇧🇻",flag_bw="🇧🇼",flag_bh="🇧🇭",flag_bi="🇧🇮",flag_bj="🇧🇯",flag_bl="🇧🇱",flag_bm="🇧🇲",flag_bn="🇧🇳",flag_bo="🇧🇴",flag_ba="🇧🇦",flag_bb="🇧🇧",flag_bd="🇧🇩",flag_be="🇧🇪",flag_bf="🇧🇫",flag_bg="🇧🇬",satellite_orbital="🛰",radio_button="🔘",arrow_heading_down="⤵",rage="😡",whale2="🐋",vhs="📼",hand_splayed_tone3="🖐🏽",strawberry="🍓",["non-potable_water"]="🚱",hand_splayed_tone5="🖐🏿",star2="🌟",toilet="🚽",ab="🆎",cinema="🎦",floppy_disk="💾",princess_tone4="👸🏾",princess_tone5="👸🏿",princess_tone2="👸🏼",nerd="🤓",telephone_receiver="📞",princess_tone1="👸🏻",arrow_double_down="⏬",clock1030="🕥",flag_pr="🇵🇷",flag_ps="🇵🇸",poop="💩",flag_pw="🇵🇼",flag_pt="🇵🇹",flag_py="🇵🇾",pear="🍐",m="Ⓜ",flag_pa="🇵🇦",flag_pf="🇵🇫",flag_pg="🇵🇬",flag_pe="🇵🇪",flag_pk="🇵🇰",flag_ph="🇵🇭",flag_pn="🇵🇳",flag_pl="🇵🇱",flag_pm="🇵🇲",mask="😷",hushed="😯",sunrise_over_mountains="🌄",partly_sunny="⛅",dollar="💵",helmet_with_cross="⛑",smoking="🚬",no_bicycles="🚳",man_with_gua_pi_mao="👲",tv="📺",open_hands="👐",rotating_light="🚨",information_desk_person_tone4="💁🏾",information_desk_person_tone5="💁🏿",part_alternation_mark="〽",pray_tone5="🙏🏿",pray_tone4="🙏🏾",pray_tone3="🙏🏽",pray_tone2="🙏🏼",pray_tone1="🙏🏻",smile="😄",large_blue_circle="🔵",man_tone4="👨🏾",man_tone5="👨🏿",fax="📠",woman="👩",man_tone1="👨🏻",man_tone2="👨🏼",man_tone3="👨🏽",eye_in_speech_bubble="👁🗨",blowfish="🐡",card_box="🗃",ticket="🎫",ramen="🍜",twisted_rightwards_arrows="🔀",swimmer_tone4="🏊🏾",swimmer_tone5="🏊🏿",swimmer_tone1="🏊🏻",swimmer_tone2="🏊🏼",swimmer_tone3="🏊🏽",saxophone="🎷",bath_tone1="🛀🏻",notebook_with_decorative_cover="📔",bath_tone3="🛀🏽",ten="🔟",raising_hand_tone4="🙋🏾",tea="🍵",raising_hand_tone1="🙋🏻",raising_hand_tone2="🙋🏼",raising_hand_tone3="🙋🏽",zero="0⃣",ribbon="🎀",santa_tone1="🎅🏻",abc="🔤",clock="🕰",purple_heart="💜",bow_tone1="🙇🏻",no_smoking="🚭",flag_cl="🇨🇱",surfer="🏄",newspaper="📰",busstop="🚏",new_moon="🌑",traffic_light="🚥",thumbsup="👍",no_entry="⛔",name_badge="📛",classical_building="🏛",hamster="🐹",pick="⛏",two_women_holding_hands="👭",family_mmbb="👨👨👦👦",family="👪",rice_cracker="🍘",wind_blowing_face="🌬",inbox_tray="📥",tired_face="😫",carousel_horse="🎠",eye="👁",poodle="🐩",chestnut="🌰",slight_smile="🙂",mailbox_closed="📪",cloud_tornado="🌪",jack_o_lantern="🎃",lifter_tone3="🏋🏽",lifter_tone2="🏋🏼",lifter_tone1="🏋🏻",lifter_tone5="🏋🏿",lifter_tone4="🏋🏾",nine="9⃣",chocolate_bar="🍫",v="✌",man_with_turban_tone4="👳🏾",man_with_turban_tone5="👳🏿",man_with_turban_tone2="👳🏼",man_with_turban_tone3="👳🏽",man_with_turban_tone1="👳🏻",family_wwbb="👩👩👦👦",hamburger="🍔",accept="🉑",airplane="✈",dress="👗",speedboat="🚤",ledger="📒",goat="🐐",flag_ae="🇦🇪",flag_ad="🇦🇩",flag_ag="🇦🇬",flag_af="🇦🇫",flag_ac="🇦🇨",flag_am="🇦🇲",flag_al="🇦🇱",flag_ao="🇦🇴",flag_ai="🇦🇮",flag_au="🇦🇺",flag_at="🇦🇹",fork_and_knife="🍴",fast_forward="⏩",flag_as="🇦🇸",flag_ar="🇦🇷",cow2="🐄",flag_ax="🇦🇽",flag_az="🇦🇿",a="🅰",volleyball="🏐",dragon="🐉",wrench="🔧",point_up_2="👆",egg="🍳",small_red_triangle="🔺",soon="🔜",bow_tone4="🙇🏾",joy_cat="😹",pray="🙏",dark_sunglasses="🕶",rugby_football="🏉",soccer="⚽",dolls="🎎",monkey_face="🐵",clap_tone3="👏🏽",bar_chart="📊",european_castle="🏰",military_medal="🎖",frame_photo="🖼",rice_ball="🍙",trolleybus="🚎",older_woman="👵",information_source="ℹ",postal_horn="📯",house="🏠",fish="🐟",bride_with_veil="👰",fist="✊",lipstick="💄",fountain="⛲",cyclone="🌀",thumbsdown_tone2="👎🏼",thumbsdown_tone3="👎🏽",thumbsdown_tone1="👎🏻",thumbsdown_tone4="👎🏾",thumbsdown_tone5="👎🏿",cookie="🍪",heartbeat="💓",blush="😊",fire_engine="🚒",feet="🐾",horse="🐴",blossom="🌼",crossed_swords="⚔",station="🚉",clock730="🕢",banana="🍌",relieved="😌",hotel="🏨",park="🏞",aerial_tramway="🚡",flag_sd="🇸🇩",panda_face="🐼",b="🅱",flag_sx="🇸🇽",six_pointed_star="🔯",shaved_ice="🍧",chipmunk="🐿",mountain="⛰",koala="🐨",white_small_square="▫",open_hands_tone2="👐🏼",open_hands_tone3="👐🏽",u55b6="🈺",open_hands_tone1="👐🏻",open_hands_tone4="👐🏾",open_hands_tone5="👐🏿",baby_tone5="👶🏿",baby_tone4="👶🏾",baby_tone3="👶🏽",baby_tone2="👶🏼",baby_tone1="👶🏻",chart="💹",beach_umbrella="⛱",basketball_player_tone5="⛹🏿",basketball_player_tone4="⛹🏾",basketball_player_tone1="⛹🏻",basketball_player_tone3="⛹🏽",basketball_player_tone2="⛹🏼",mans_shoe="👞",shinto_shrine="⛩",ideograph_advantage="🉐",airplane_arriving="🛬",golf="⛳",minidisc="💽",hugging="🤗",crayon="🖍",point_down="👇",copyright="©",person_with_pouting_face_tone2="🙎🏼",person_with_pouting_face_tone3="🙎🏽",person_with_pouting_face_tone1="🙎🏻",person_with_pouting_face_tone4="🙎🏾",person_with_pouting_face_tone5="🙎🏿",busts_in_silhouette="👥",alarm_clock="⏰",couplekiss="💏",circus_tent="🎪",sunny="☀",incoming_envelope="📨",yellow_heart="💛",cry="😢",x="❌",arrow_up_small="🔼",art="🎨",surfer_tone1="🏄🏻",bride_with_veil_tone4="👰🏾",bride_with_veil_tone5="👰🏿",bride_with_veil_tone2="👰🏼",bride_with_veil_tone3="👰🏽",bride_with_veil_tone1="👰🏻",hibiscus="🌺",black_joker="🃏",raised_hand="✋",no_mouth="😶",basketball_player="⛹",champagne="🍾",no_entry_sign="🚫",older_man="👴",moyai="🗿",mailbox="📫",slight_frown="🙁",statue_of_liberty="🗽",mega="📣",eggplant="🍆",rose="🌹",bell="🔔",battery="🔋",wastebasket="🗑",dancer="💃",page_facing_up="📄",church="⛪",underage="🔞",secret="㊙",clock430="🕟",fork_knife_plate="🍽",u7981="🈲",fire="🔥",cold_sweat="😰",flag_er="🇪🇷",family_mwgg="👨👩👧👧",heart_eyes="😍",guardsman_tone1="💂🏻",guardsman_tone2="💂🏼",guardsman_tone3="💂🏽",guardsman_tone4="💂🏾",earth_africa="🌍",arrow_right_hook="↪",spy_tone2="🕵🏼",closed_umbrella="🌂",bikini="👙",vertical_traffic_light="🚦",kissing="😗",loop="➿",potable_water="🚰",pound="💷",["fleur-de-lis"]="⚜",key2="🗝",heavy_dollar_sign="💲",shamrock="☘",boy_tone4="👦🏾",shirt="👕",kimono="👘",left_luggage="🛅",meat_on_bone="🍖",ok_woman_tone4="🙆🏾",ok_woman_tone5="🙆🏿",arrow_heading_up="⤴",calendar_spiral="🗓",snail="🐌",ok_woman_tone1="🙆🏻",arrow_down_small="🔽",leopard="🐆",paperclips="🖇",cityscape="🏙",woman_tone1="👩🏻",slot_machine="🎰",woman_tone3="👩🏽",woman_tone4="👩🏾",woman_tone5="👩🏿",euro="💶",musical_score="🎼",triangular_ruler="📐",flags="🎏",five="5⃣",love_hotel="🏩",hotdog="🌭",speak_no_evil="🙊",eyeglasses="👓",dancer_tone4="💃🏾",dancer_tone5="💃🏿",vulcan_tone4="🖖🏾",bridge_at_night="🌉",writing_hand_tone1="✍🏻",couch="🛋",vulcan_tone1="🖖🏻",vulcan_tone2="🖖🏼",vulcan_tone3="🖖🏽",womans_hat="👒",sandal="👡",cherries="🍒",full_moon="🌕",flag_om="🇴🇲",play_pause="⏯",couple="👫",money_mouth="🤑",womans_clothes="👚",globe_with_meridians="🌐",bath_tone5="🛀🏿",bangbang="‼",stuck_out_tongue_winking_eye="😜",heart="❤",bamboo="🎍",mahjong="🀄",waning_gibbous_moon="🌖",back="🔙",point_up_2_tone4="👆🏾",point_up_2_tone5="👆🏿",lips="👄",point_up_2_tone1="👆🏻",point_up_2_tone2="👆🏼",point_up_2_tone3="👆🏽",candle="🕯",middle_finger_tone3="🖕🏽",middle_finger_tone2="🖕🏼",middle_finger_tone1="🖕🏻",middle_finger_tone5="🖕🏿",middle_finger_tone4="🖕🏾",heavy_minus_sign="➖",nose="👃",zzz="💤",stew="🍲",santa="🎅",tropical_fish="🐠",point_up_tone1="☝🏻",point_up_tone3="☝🏽",point_up_tone2="☝🏼",point_up_tone5="☝🏿",point_up_tone4="☝🏾",field_hockey="🏑",school_satchel="🎒",womens="🚺",baby_symbol="🚼",baby_chick="🐤",ok_hand_tone2="👌🏼",ok_hand_tone3="👌🏽",ok_hand_tone1="👌🏻",ok_hand_tone4="👌🏾",ok_hand_tone5="👌🏿",family_mmgb="👨👨👧👦",last_quarter_moon="🌗",tada="🎉",clock530="🕠",question="❓",registered="®",level_slider="🎚",black_circle="⚫",atom="⚛",penguin="🐧",electric_plug="🔌",skull="💀",kiss_mm="👨❤💋👨",walking_tone4="🚶🏾",fries="🍟",up="🆙",walking_tone3="🚶🏽",walking_tone2="🚶🏼",athletic_shoe="👟",hatched_chick="🐥",black_nib="✒",black_large_square="⬛",bow_and_arrow="🏹",rainbow="🌈",metal_tone5="🤘🏿",metal_tone4="🤘🏾",lemon="🍋",metal_tone2="🤘🏼",peach="🍑",peace="☮",steam_locomotive="🚂",oncoming_bus="🚍",heart_eyes_cat="😻",smiley="😃",haircut_tone1="💇🏻",haircut_tone2="💇🏼",u6e80="🈵",haircut_tone4="💇🏾",haircut_tone5="💇🏿",black_medium_square="◼",closed_book="📕",desert="🏜",expressionless="😑",dvd="📀",construction_worker_tone2="👷🏼",construction_worker_tone3="👷🏽",construction_worker_tone4="👷🏾",construction_worker_tone5="👷🏿",mag_right="🔎",bento="🍱",scroll="📜",flag_nl="🇳🇱",flag_no="🇳🇴",flag_ni="🇳🇮",european_post_office="🏤",flag_ne="🇳🇪",flag_nf="🇳🇫",flag_ng="🇳🇬",flag_na="🇳🇦",flag_nc="🇳🇨",alien="👽",first_quarter_moon_with_face="🌛",flag_nz="🇳🇿",flag_nu="🇳🇺",golfer="🏌",flag_np="🇳🇵",flag_nr="🇳🇷",anguished="😧",mosque="🕌",point_left_tone1="👈🏻",ear_tone1="👂🏻",ear_tone2="👂🏼",ear_tone3="👂🏽",ear_tone4="👂🏾",ear_tone5="👂🏿",eight_pointed_black_star="✴",wave="👋",runner_tone5="🏃🏿",runner_tone4="🏃🏾",runner_tone3="🏃🏽",runner_tone2="🏃🏼",runner_tone1="🏃🏻",railway_car="🚃",notes="🎶",no_good="🙅",trackball="🖲",spaghetti="🍝",love_letter="💌",clipboard="📋",baby_bottle="🍼",bird="🐦",card_index="📇",punch="👊",leo="♌",house_with_garden="🏡",family_wwgg="👩👩👧👧",family_wwgb="👩👩👧👦",see_no_evil="🙈",metro="🚇",popcorn="🍿",apple="🍎",scales="⚖",sleeping_accommodation="🛌",clock230="🕝",tools="🛠",cloud="☁",honey_pot="🍯",ballot_box="🗳",frog="🐸",camera="📷",crab="🦀",video_camera="📹",pencil="📝",thunder_cloud_rain="⛈",mountain_bicyclist="🚵",tangerine="🍊",train="🚋",rabbit="🐰",baby="👶",palm_tree="🌴",capital_abcd="🔠",put_litter_in_its_place="🚮",coffin="⚰",abcd="🔡",lock="🔒",pig2="🐖",family_mwg="👨👩👧",point_right_tone5="👉🏿",trumpet="🎺",film_frames="🎞",six="6⃣",leftwards_arrow_with_hook="↩",earth_asia="🌏",heavy_check_mark="✔",notebook="📓",taco="🌮",tomato="🍅",robot="🤖",mute="🔇",symbols="🔣",motorcycle="🏍",thermometer_face="🤒",paperclip="📎",moneybag="💰",neutral_face="😐",white_sun_rain_cloud="🌦",snake="🐍",kiss="💋",blue_car="🚙",confetti_ball="🎊",tram="🚊",repeat_one="🔂",smiley_cat="😺",beginner="🔰",mobile_phone_off="📴",books="📚",["8ball"]="🎱",cocktail="🍸",flag_ge="🇬🇪",horse_racing_tone2="🏇🏼",flag_mh="🇲🇭",flag_mk="🇲🇰",flag_mm="🇲🇲",flag_ml="🇲🇱",flag_mo="🇲🇴",flag_mn="🇲🇳",flag_ma="🇲🇦",flag_mc="🇲🇨",flag_me="🇲🇪",flag_md="🇲🇩",flag_mg="🇲🇬",flag_mf="🇲🇫",flag_my="🇲🇾",flag_mx="🇲🇽",flag_mz="🇲🇿",mountain_snow="🏔",flag_mp="🇲🇵",flag_ms="🇲🇸",flag_mr="🇲🇷",flag_mu="🇲🇺",flag_mt="🇲🇹",flag_mw="🇲🇼",flag_mv="🇲🇻",timer="⏲",passport_control="🛂",small_blue_diamond="🔹",lion_face="🦁",white_check_mark="✅",bouquet="💐",track_previous="⏮",monkey="🐒",tone4="🏾",closed_lock_with_key="🔐",family_wwb="👩👩👦",family_wwg="👩👩👧",tone1="🏻",crescent_moon="🌙",shell="🐚",gear="⚙",tone2="🏼",small_red_triangle_down="🔻",nut_and_bolt="🔩",umbrella2="☂",unamused="😒",fuelpump="⛽",bed="🛏",bee="🐝",round_pushpin="📍",flag_white="🏳",microphone="🎤",bus="🚌",eight="8⃣",handbag="👜",medal="🏅",arrows_clockwise="🔃",urn="⚱",bookmark_tabs="📑",new_moon_with_face="🌚",fallen_leaf="🍂",horse_racing="🏇",chicken="🐔",ear="👂",wheel_of_dharma="☸",arrow_lower_right="↘",man_with_gua_pi_mao_tone5="👲🏿",scorpion="🦂",waning_crescent_moon="🌘",man_with_gua_pi_mao_tone2="👲🏼",man_with_gua_pi_mao_tone1="👲🏻",bug="🐛",virgo="♍",libra="♎",angel_tone1="👼🏻",angel_tone3="👼🏽",angel_tone2="👼🏼",angel_tone5="👼🏿",sagittarius="♐",bear="🐻",information_desk_person_tone3="💁🏽",no_mobile_phones="📵",hand_splayed="🖐",motorboat="🛥",calling="📲",interrobang="⁉",oncoming_taxi="🚖",flag_lt="🇱🇹",flag_lu="🇱🇺",flag_lr="🇱🇷",flag_ls="🇱🇸",flag_ly="🇱🇾",bellhop="🛎",arrow_down="⬇",flag_lc="🇱🇨",flag_la="🇱🇦",flag_lk="🇱🇰",flag_li="🇱🇮",ferris_wheel="🎡",hand_splayed_tone2="🖐🏼",large_blue_diamond="🔷",cat2="🐈",icecream="🍦",tent="⛺",joy="😂",hand_splayed_tone4="🖐🏾",file_cabinet="🗄",key="🔑",weary="😩",bath_tone2="🛀🏼",flag_lv="🇱🇻",low_brightness="🔅",rowboat_tone5="🚣🏿",rowboat_tone2="🚣🏼",rowboat_tone3="🚣🏽",four_leaf_clover="🍀",space_invader="👾",cl="🆑",cd="💿",bath_tone4="🛀🏾",flag_za="🇿🇦",swimmer="🏊",wavy_dash="〰",flag_zm="🇿🇲",flag_zw="🇿🇼",raised_hands_tone5="🙌🏿",two_hearts="💕",bulb="💡",cop_tone4="👮🏾",cop_tone5="👮🏿",cop_tone2="👮🏼",cop_tone3="👮🏽",cop_tone1="👮🏻",open_file_folder="📂",homes="🏘",raised_hands_tone2="🙌🏼",fearful="😨",grinning="😀",bow_tone5="🙇🏿",santa_tone3="🎅🏽",santa_tone2="🎅🏼",santa_tone5="🎅🏿",santa_tone4="🎅🏾",bow_tone2="🙇🏼",bow_tone3="🙇🏽",bathtub="🛁",ping_pong="🏓",u5272="🈹",rooster="🐓",vs="🆚",bullettrain_front="🚅",airplane_small="🛩",white_circle="⚪",balloon="🎈",cross="✝",princess_tone3="👸🏽",speaker="🔈",zipper_mouth="🤐",u6307="🈯",whale="🐳",pensive="😔",signal_strength="📶",muscle="💪",rocket="🚀",camel="🐫",boot="👢",flashlight="🔦",spy_tone4="🕵🏾",spy_tone5="🕵🏿",ski="🎿",spy_tone3="🕵🏽",musical_keyboard="🎹",spy_tone1="🕵🏻",rolling_eyes="🙄",clock1="🕐",clock2="🕑",clock3="🕒",clock4="🕓",clock5="🕔",clock6="🕕",clock7="🕖",clock8="🕗",clock9="🕘",doughnut="🍩",dancer_tone1="💃🏻",dancer_tone2="💃🏼",dancer_tone3="💃🏽",candy="🍬",two_men_holding_hands="👬",badminton="🏸",bust_in_silhouette="👤",writing_hand_tone2="✍🏼",sunflower="🌻",["e-mail"]="📧",chains="⛓",kissing_smiling_eyes="😙",fish_cake="🍥",no_pedestrians="🚷",v_tone4="✌🏾",v_tone5="✌🏿",v_tone1="✌🏻",v_tone2="✌🏼",v_tone3="✌🏽",arrow_backward="◀",clock12="🕛",clock10="🕙",clock11="🕚",sweat="😓",mountain_railway="🚞",tongue="👅",black_square_button="🔲",do_not_litter="🚯",nose_tone4="👃🏾",nose_tone5="👃🏿",nose_tone2="👃🏼",nose_tone3="👃🏽",nose_tone1="👃🏻",horse_racing_tone5="🏇🏿",horse_racing_tone4="🏇🏾",horse_racing_tone3="🏇🏽",ok_hand="👌",horse_racing_tone1="🏇🏻",custard="🍮",rowboat="🚣",white_sun_small_cloud="🌤",flag_kr="🇰🇷",cricket="🏏",flag_kp="🇰🇵",flag_kw="🇰🇼",flag_kz="🇰🇿",flag_ky="🇰🇾",construction="🚧",flag_kg="🇰🇬",flag_ke="🇰🇪",flag_ki="🇰🇮",flag_kh="🇰🇭",flag_kn="🇰🇳",flag_km="🇰🇲",cake="🍰",flag_wf="🇼🇫",mortar_board="🎓",pig="🐷",flag_ws="🇼🇸",person_frowning="🙍",arrow_upper_right="↗",book="📖",clock1130="🕦",boom="💥",["repeat"]="🔁",star="⭐",rabbit2="🐇",footprints="👣",ghost="👻",droplet="💧",vibration_mode="📳",flag_ye="🇾🇪",flag_yt="🇾🇹", } -- translate the string to emoji function emoji.translate(str) -- translate it local chars = emoji.keys[str] -- ok? return chars end -- return module return emoji
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/hash.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 hash.lua -- -- define module: hash local hash = hash or {} -- load modules local io = require("base/io") local utils = require("base/utils") local bytes = require("base/bytes") -- save metatable and builtin functions hash._md5 = hash._md5 or hash.md5 hash._sha = hash._sha or hash.sha hash._xxhash = hash._xxhash or hash.xxhash -- make md5 from the given file or data function hash.md5(file_or_data) local hashstr, errors if bytes.instance_of(file_or_data) then local datasize = file_or_data:size() local dataaddr = file_or_data:caddr() hashstr, errors = hash._md5(dataaddr, datasize) else hashstr, errors = hash._md5(file_or_data) end return hashstr, errors end -- make sha1 from the given file or data function hash.sha1(file_or_data) local hashstr, errors if bytes.instance_of(file_or_data) then local datasize = file_or_data:size() local dataaddr = file_or_data:caddr() hashstr, errors = hash._sha(160, dataaddr, datasize) else hashstr, errors = hash._sha(160, file_or_data) end return hashstr, errors end -- make sha256 from the given file or data function hash.sha256(file_or_data) local hashstr, errors if bytes.instance_of(file_or_data) then local datasize = file_or_data:size() local dataaddr = file_or_data:caddr() hashstr, errors = hash._sha(256, dataaddr, datasize) else hashstr, errors = hash._sha(256, file_or_data) end return hashstr, errors end -- make xxhash64 from the given file or data function hash.xxhash64(file_or_data) local hashstr, errors if bytes.instance_of(file_or_data) then local datasize = file_or_data:size() local dataaddr = file_or_data:caddr() hashstr, errors = hash._xxhash(64, dataaddr, datasize) else hashstr, errors = hash._xxhash(64, file_or_data) end return hashstr, errors end -- make xxhash128 from the given file or data function hash.xxhash128(file_or_data) local hashstr, errors if bytes.instance_of(file_or_data) then local datasize = file_or_data:size() local dataaddr = file_or_data:caddr() hashstr, errors = hash._xxhash(128, dataaddr, datasize) else hashstr, errors = hash._xxhash(128, file_or_data) end return hashstr, errors end -- return module: hash return hash
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/winos.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 winos.lua -- -- define module: winos local winos = winos or {} -- load modules local os = require("base/os") local path = require("base/path") local semver = require("base/semver") winos._ansi_cp = winos._ansi_cp or winos.ansi_cp winos._oem_cp = winos._oem_cp or winos.oem_cp winos._registry_query = winos._registry_query or winos.registry_query winos._registry_keys = winos._registry_keys or winos.registry_keys winos._registry_values = winos._registry_values or winos.registry_values function winos.ansi_cp() if not winos._ANSI_CP then winos._ANSI_CP = winos._ansi_cp() end return winos._ANSI_CP end function winos.oem_cp() if not winos._OEM_CP then winos._OEM_CP = winos._oem_cp() end return winos._OEM_CP end -- get windows version from name function winos._version_from_name(name) -- make defined values winos._VERSIONS = winos._VERSIONS or { nt4 = "4.0" , win2k = "5.0" , winxp = "5.1" , ws03 = "5.2" , win6 = "6.0" , vista = "6.0" , ws08 = "6.0" , longhorn = "6.0" , win7 = "6.1" , win8 = "6.2" , winblue = "6.3" , win81 = "6.3" , win10 = "10.0" } return winos._VERSIONS[name] end -- v1 == v2 with name (winxp, win10, ..)? function winos._version_eq(self, version) if type(version) == "string" then local namever = winos._version_from_name(version) if namever then return semver.compare(self:major() .. '.' .. self:minor(), namever) == 0 else return semver.compare(self:rawstr(), version) == 0 end elseif type(version) == "table" then return semver.compare(self:rawstr(), version:rawstr()) == 0 end end -- v1 < v2 with name (winxp, win10, ..)? function winos._version_lt(self, version) if type(version) == "string" then local namever = winos._version_from_name(version) if namever then return semver.compare(self:major() .. '.' .. self:minor(), namever) < 0 else return semver.compare(self:rawstr(), version) < 0 end elseif type(version) == "table" then return semver.compare(self:rawstr(), version:rawstr()) < 0 end end -- v1 <= v2 with name (winxp, win10, ..)? function winos._version_le(self, version) if type(version) == "string" then local namever = winos._version_from_name(version) if namever then return semver.compare(self:major() .. '.' .. self:minor(), namever) <= 0 else return semver.compare(self:rawstr(), version) <= 0 end elseif type(version) == "table" then return semver.compare(self:rawstr(), version:rawstr()) <= 0 end end -- get system version function winos.version() local winver = winos._VERSION if winver == nil then -- get winver local ok, verstr = os.iorun("cmd /c ver") if ok and verstr then winver = verstr:match("%[.-([%d%.]+)]") if winver then winver = winver:trim() local sem_winver local seg = 0 for num in winver:gmatch("%d+") do if seg == 0 then sem_winver = num elseif seg == 3 then sem_winver = sem_winver .. "+" .. num else sem_winver = sem_winver .. "." .. num end seg = seg + 1 end if sem_winver then winver = semver.new(sem_winver) end end end if not winver then winver = semver.new("0.0") end -- rewrite comparator winver.eq = winos._version_eq winver.lt = winos._version_lt winver.le = winos._version_le winos._VERSION = winver end return winver end -- get command arguments on windows to solve 8192 character command line length limit function winos.cmdargv(argv, opt) -- too long arguments? local limit = 4096 local argn = 0 for _, arg in ipairs(argv) do arg = tostring(arg) argn = argn + #arg if argn > limit then break end end if argn > limit then opt = opt or {} local argsfile = os.tmpfile(opt.tmpkey or os.args(argv)) .. ".args.txt" local f = io.open(argsfile, 'w', {encoding = "ansi"}) if f then -- we need to split args file to solve `fatal error LNK1170: line in command file contains 131071 or more characters` -- @see https://github.com/xmake-io/xmake/issues/812 local idx = 1 while idx <= #argv do arg = tostring(argv[idx]) arg1 = argv[idx + 1] if arg1 then arg1 = tostring(arg1) end -- we need to ensure `/name value` in same line, -- otherwise cl.exe will prompt that the corresponding parameter value cannot be found -- -- e.g. -- -- /sourceDependencies xxxx.json -- -Dxxx -- foo.obj -- if idx + 1 <= #argv and arg:find("^[-/]") and not arg1:find("^[-/]") then f:write(os.args(arg, {escape = opt.escape}) .. " ") f:write(os.args(arg1, {escape = opt.escape}) .. "\n") idx = idx + 2 else f:write(os.args(arg, {escape = opt.escape}) .. "\n") idx = idx + 1 end end f:close() end argv = {"@" .. argsfile} end return argv end -- query registry value -- -- @param keypath the key path -- @return the value and errors -- -- @code -- local value, errors = winos.registry_query("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug") -- local value, errors = winos.registry_query("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug;Debugger") -- @endcode -- function winos.registry_query(keypath) -- get value name local splitinfo = keypath:split(';', {plain = true}) local valuename = splitinfo[2] or "" keypath = splitinfo[1] -- get rootkey, e.g. HKEY_LOCAL_MACHINE local rootkey local p = keypath:find("\\", 1, true) if p then rootkey = keypath:sub(1, p - 1) end if not rootkey then return nil, "root key not found!" end -- get the root directory local rootdir = keypath:sub(p + 1) -- query value return winos._registry_query(rootkey, rootdir, valuename) end -- get registry key paths -- -- @param keypath the key path (support key pattern, e.g. \\a\\b;xx*yy) -- uses "*" to match any part of a key path, -- uses "**" to recurse into subkey paths. -- @return the result array and errors -- -- @code -- local keys, errors = winos.registry_keys("HKEY_LOCAL_MACHINE\\SOFTWARE\\*\\Windows NT\\*\\CurrentVersion\\AeDebug") -- local keys, errors = winos.registry_keys("HKEY_LOCAL_MACHINE\\SOFTWARE\\**") -- @endcode -- function winos.registry_keys(keypath) -- get rootkey, e.g. HKEY_LOCAL_MACHINE local rootkey local p = keypath:find("\\", 1, true) if p then rootkey = keypath:sub(1, p - 1) end if not rootkey then return end keypath = keypath:sub(p + 1) -- get the root directory local pattern local rootdir = keypath p = rootdir:find("*", 1, true) if p then pattern = path.pattern(rootdir) rootdir = path.directory(rootdir:sub(1, p - 1)) end -- compute the recursion level -- -- infinite recursion: aaa\\** -- limit recursion level: aaa\\*\\* local recursion = 0 if keypath:find("**", 1, true) then recursion = -1 else -- "aaa\\*\\*" -> "*\\" -> recursion level: 1 -- "aaa\\*\\xxx" -> "*\\" -> recursion level: 1 -- "aaa\\*\\subkey\\xxx" -> "*\\\\" -> recursion level: 2 if p then local _, seps = keypath:sub(p):gsub("\\", "") if seps > 0 then recursion = seps end end end -- get keys local keys = {} local count, errors = winos._registry_keys(rootkey, rootdir, recursion, function (key) if not pattern or key:match("^" .. pattern .. "$") then table.insert(keys, rootkey .. '\\' .. key) if #keys > 4096 then return false end end return true end) if #keys > 4096 then return nil, "too much registry keys: " .. keypath end if count ~= nil then return keys else return nil, errors end end -- get registry values from the given key path -- -- @param keypath the key path (support value pattern, e.g. \\a\\b;xx*yy) -- uses "*" to match value name, -- @return the values array and errors -- -- @code -- local values, errors = winos.registry_values("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug") -- local values, errors = winos.registry_values("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug;Debug*") -- @endcode -- function winos.registry_values(keypath) -- get value pattern local splitinfo = keypath:split(';', {plain = true}) local pattern = splitinfo[2] if pattern then pattern = path.pattern(pattern) end keypath = splitinfo[1] -- get rootkey, e.g. HKEY_LOCAL_MACHINE local rootkey local p = keypath:find("\\", 1, true) if p then rootkey = keypath:sub(1, p - 1) end if not rootkey then return nil, "root key not found!" end -- get the root directory local rootdir = keypath:sub(p + 1) -- get value names local value_names = {} local count, errors = winos._registry_values(rootkey, rootdir, function (value_name) if not pattern or value_name:match("^" .. pattern .. "$") then table.insert(value_names, rootkey .. "\\" .. rootdir .. ";" .. value_name) end return true end) if count ~= nil then return value_names else return nil, errors end end -- inherit handles in CreateProcess safely? -- https://github.com/xmake-io/xmake/issues/2902#issuecomment-1326934902 -- function winos.inherit_handles_safely() local inherit_handles_safely = winos._INHERIT_HANDLES_SAFELY if inherit_handles_safely == nil then inherit_handles_safely = winos.version():ge("win7") or false winos._INHERIT_HANDLES_SAFELY = inherit_handles_safely end return inherit_handles_safely end -- return module: winos return winos
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/os.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 os.lua -- -- define module local os = os or {} -- load modules local io = require("base/io") local log = require("base/log") local path = require("base/path") local table = require("base/table") local utils = require("base/utils") local string = require("base/string") local process = require("base/process") -- save original interfaces os._uid = os._uid or os.uid os._gid = os._gid or os.gid os._getpid = os._getpid or os.getpid os._exit = os._exit or os.exit os._mkdir = os._mkdir or os.mkdir os._rmdir = os._rmdir or os.rmdir os._touch = os._touch or os.touch os._tmpdir = os._tmpdir or os.tmpdir os._fscase = os._fscase or os.fscase os._setenv = os._setenv or os.setenv os._getenvs = os._getenvs or os.getenvs os._cpuinfo = os._cpuinfo or os.cpuinfo os._meminfo = os._meminfo or os.meminfo os._readlink = os._readlink or os.readlink -- syserror code os.SYSERR_UNKNOWN = -1 os.SYSERR_NONE = 0 os.SYSERR_NOT_PERM = 1 os.SYSERR_NOT_FILEDIR = 2 os.SYSERR_NOT_ACCESS = 3 -- copy single file or directory function os._cp(src, dst, rootdir, opt) opt = opt or {} assert(src and dst) -- reserve the source directory structure if opt.rootdir is given if rootdir then if not path.is_absolute(src) then src = path.absolute(src) end if not src:startswith(rootdir) then return false, string.format("cannot copy file %s to %s, invalid rootdir(%s)", src, dst, rootdir) end end -- is file or link? local symlink = opt.symlink local writeable = opt.writeable if os.isfile(src) or (symlink and os.islink(src)) then -- the destination is directory? append the filename if os.isdir(dst) or path.islastsep(dst) then if rootdir then dst = path.join(dst, path.relative(src, rootdir)) else dst = path.join(dst, path.filename(src)) end end -- copy or link file if opt.force and os.isfile(dst) then os.rmfile(dst) end if not os.cpfile(src, dst, symlink, writeable) then local errors = os.strerror() if symlink and os.islink(src) then local reallink = os.readlink(src) return false, string.format("cannot link %s(%s) to %s, %s", src, reallink, dst, errors) else return false, string.format("cannot copy file %s to %s, %s", src, dst, errors) end end -- is directory? elseif os.isdir(src) then -- the destination directory exists? append the filename if os.isdir(dst) or path.islastsep(dst) then if rootdir then dst = path.join(dst, path.relative(src, rootdir)) else dst = path.join(dst, path.filename(path.translate(src))) end end -- copy directory if not os.cpdir(src, dst, symlink) then return false, string.format("cannot copy directory %s to %s, %s", src, dst, os.strerror()) end else return false, string.format("cannot copy file %s, file not found!", src) end return true end -- move single file or directory function os._mv(src, dst, opt) opt = opt or {} assert(src and dst) if os.exists(src) then -- the destination directory exists? append the filename if os.isdir(dst) or path.islastsep(dst) then dst = path.join(dst, path.filename(path.translate(src))) end -- move file or directory if opt.force and os.isfile(dst) then os.rmfile(dst) end if not os.rename(src, dst) then return false, string.format("cannot move %s to %s %s", src, dst, os.strerror()) end else return false, string.format("cannot move %s to %s, file %s not found!", src, dst, os.strerror()) end return true end -- remove single file or directory function os._rm(filedir) assert(filedir) -- is file or link? if os.isfile(filedir) or os.islink(filedir) then if not os.rmfile(filedir) then return false, string.format("cannot remove file %s %s", filedir, os.strerror()) end -- is directory? elseif os.isdir(filedir) then if not os.rmdir(filedir) then return false, string.format("cannot remove directory %s %s", filedir, os.strerror()) end end return true end -- remove empty parent directories of this file path function os._rm_empty_parentdirs(filepath) local parentdir = path.directory(filepath) while parentdir and os.isdir(parentdir) and os.emptydir(parentdir) do local ok, errors = os._rm(parentdir) if not ok then return false, errors end parentdir = path.directory(parentdir) end return true end -- get the ramdisk root directory -- https://github.com/xmake-io/xmake/issues/3408 function os._ramdir() local ramdir_root = os._ROOT_RAMDIR if ramdir_root == nil then ramdir_root = os.getenv("XMAKE_RAMDIR") end if ramdir_root == nil then ramdir_root = false os._ROOT_RAMDIR = ramdir_root end return ramdir_root or nil end -- set on change environments callback for scheduler function os._sched_chenvs_set(envs) os._SCHED_CHENVS = envs end -- set on change directory callback for scheduler function os._sched_chdir_set(chdir) os._SCHED_CHDIR = chdir end -- notify envs have been changed function os._notify_envs_changed(envs) if os._SCHED_CHENVS then os._SCHED_CHENVS(envs) end end -- the current host is belong to the given hosts? function os._is_host(host, ...) if not host then return false end -- exists this host? and escape '-' for _, h in ipairs(table.join(...)) do if h and type(h) == "string" and host:find(h:gsub("%-", "%%-")) then return true end end end -- the current platform is belong to the given architectures? function os._is_arch(arch, ...) if not arch then return false end -- exists this architecture? and escape '-' for _, a in ipairs(table.join(...)) do if a and type(a) == "string" and arch:find("^" .. a:gsub("%-", "%%-") .. "$") then return true end end end -- match wildcard files function os._match_wildcard_pathes(v) if v:find("*", 1, true) then return (os.filedirs(v)) end return v end -- split too long path environment variable for windows -- -- @see https://github.com/xmake-io/xmake-repo/pull/489 -- https://stackoverflow.com/questions/34491244/environment-variable-is-too-large-on-windows-10 -- function os._deduplicate_pathenv(value) if value and #value > 4096 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 -- trace process for profile(stuck,trace)? function os._is_tracing_process() local is_tracing = os._IS_TRACING_PROCESS if is_tracing == nil then local profile = os.getenv("XMAKE_PROFILE") if profile then profile = profile:trim() if profile == "trace" or profile == "stuck" then is_tracing = true end end is_tracing = is_tracing or false os._IS_TRACING_PROCESS = is_tracing end return is_tracing end -- run all exit callback function os._run_exit_cbs(ok, errors) local exit_callbacks = os._EXIT_CALLBACKS if exit_callbacks then for _, cb in ipairs(exit_callbacks) do cb(ok, errors) end end end -- get shell path, e.g. sh, bash function os._get_shell_path(opt) opt = opt or {} local setenvs = opt.setenvs or opt.envs or {} local addenvs = opt.addenvs or {} local paths = {} local p = setenvs.PATH if type(p) == "string" then p = path.splitenv(p) end if p then table.join2(paths, p) end p = addenvs.PATH if type(p) == "string" then p = path.splitenv(p) end if p then table.join2(paths, p) end for _, p in ipairs(paths) do for _, name in ipairs({"sh", "bash"}) do local filepath = path.join(p, name) if os.isexec(filepath) then return filepath end end end end -- match files or directories -- -- @param pattern the search pattern -- uses "*" to match any part of a file or directory name, -- uses "**" to recurse into subdirectories. -- -- @param mode the match mode -- - only find file: 'f' or false or nil -- - only find directory: 'd' or true -- - find file and directory: 'a' -- @return the result array and count -- -- @code -- local dirs, count = os.match("./src/*", true) -- local files, count = os.match("./src/**.c") -- local file = os.match("./src/test.c", 'f', function (filepath, isdir) -- return true -- continue it -- return false -- break it -- end) -- @endcode -- function os.match(pattern, mode, callback) -- support path instance pattern = tostring(pattern) -- get the excludes local excludes = pattern:match("|.*$") if excludes then excludes = excludes:split("|", {plain = true}) end -- translate excludes if excludes then local _excludes = {} for _, exclude in ipairs(excludes) do exclude = path.translate(exclude) exclude = path.pattern(exclude) table.insert(_excludes, exclude) end excludes = _excludes end -- translate path and remove some repeat separators pattern = path.translate((pattern:gsub("|.*$", ""))) -- translate mode if type(mode) == "string" then local modes = {a = -1, f = 0, d = 1} mode = modes[mode] assert(mode, "invalid match mode: %s", mode) elseif mode then mode = 1 else mode = 0 end -- match the single file without wildchard? if os.isfile(pattern) then if mode <= 0 then return {pattern}, 1 else return {}, 0 end -- match the single directory without wildchard? elseif os.isdir(pattern) then if (mode == -1 or mode == 1) then return {pattern}, 1 else return {}, 0 end end -- remove "./" or '.\\' prefix if pattern:sub(1, 2):find('%.[/\\]') then pattern = pattern:sub(3) end -- get the root directory local rootdir = pattern local startpos = pattern:find("*", 1, true) if startpos then rootdir = rootdir:sub(1, startpos - 1) end rootdir = path.directory(rootdir .. "_") -- patch '_' to avoid getting incorrect directory for `/foo/*` -- compute the recursion level -- -- infinite recursion: src/**.c -- limit recursion level: src/*/*.c local recursion = 0 if pattern:find("**", 1, true) then recursion = -1 else -- "src/*/*.c" -> "*/" -> recursion level: 1 -- "src/*/main.c" -> "*/" -> recursion level: 1 -- "src/*/subdir/main.c" -> "*//" -> recursion level: 2 if startpos then local _, seps = pattern:sub(startpos):gsub("[/\\]", "") if seps > 0 then recursion = seps end end end -- convert pattern to a lua pattern pattern = path.pattern(pattern) -- find it return os.find(rootdir, pattern, recursion, mode, excludes, callback) end -- match directories -- -- @note only return {} without count to simplify code, e.g. table.unpack(os.dirs("")) -- function os.dirs(pattern, callback) return (os.match(pattern, 'd', callback)) end -- match files function os.files(pattern, callback) return (os.match(pattern, 'f', callback)) end -- match files and directories function os.filedirs(pattern, callback) return (os.match(pattern, 'a', callback)) end -- copy files or directories and we can reserve the source directory structure -- e.g. os.cp("src/**.h", "/tmp/", {rootdir = "src", symlink = true}) function os.cp(srcpath, dstpath, opt) -- check arguments if not srcpath or not dstpath then return false, string.format("invalid arguments!") end -- reserve the source directory structure if opt.rootdir is given local rootdir = opt and opt.rootdir if rootdir then rootdir = tostring(rootdir) if not path.is_absolute(rootdir) then rootdir = path.absolute(rootdir) end end -- copy files or directories srcpath = tostring(srcpath) dstpath = tostring(dstpath) local srcpathes = os._match_wildcard_pathes(srcpath) if type(srcpathes) == "string" then return os._cp(srcpathes, dstpath, rootdir, opt) else for _, _srcpath in ipairs(srcpathes) do local ok, errors = os._cp(_srcpath, dstpath, rootdir, opt) if not ok then return false, errors end end end return true end -- move files or directories function os.mv(srcpath, dstpath, opt) -- check arguments if not srcpath or not dstpath then return false, string.format("invalid arguments!") end -- copy files or directories srcpath = tostring(srcpath) dstpath = tostring(dstpath) local srcpathes = os._match_wildcard_pathes(srcpath) if type(srcpathes) == "string" then return os._mv(srcpathes, dstpath, opt) else for _, _srcpath in ipairs(srcpathes) do local ok, errors = os._mv(_srcpath, dstpath, opt) if not ok then return false, errors end end end return true end -- remove files or directories function os.rm(filepath, opt) -- check arguments if not filepath then return false, string.format("invalid arguments!") end -- remove file or directories opt = opt or {} filepath = tostring(filepath) local filepathes = os._match_wildcard_pathes(filepath) if type(filepathes) == "string" then local ok, errors = os._rm(filepathes) if not ok then return false, errors end if opt.emptydirs then return os._rm_empty_parentdirs(filepathes) end else for _, _filepath in ipairs(filepathes) do local ok, errors = os._rm(_filepath) if not ok then return false, errors end if opt.emptydirs then ok, errors = os._rm_empty_parentdirs(_filepath) if not ok then return false, errors end end end end return true end -- link file or directory to the new symfile function os.ln(srcpath, dstpath, opt) opt = opt or {} srcpath = tostring(srcpath) dstpath = tostring(dstpath) if opt.force and os.isfile(dstpath) then os.rmfile(dstpath) end if not os.link(srcpath, dstpath) then return false, string.format("cannot link %s to %s, %s", srcpath, dstpath, os.strerror()) end return true end -- change to directory function os.cd(dir) assert(dir) -- support path instance dir = tostring(dir) -- the previous directory local oldir = os.curdir() -- change to the previous directory? if dir == "-" then -- exists the previous directory? if os._PREDIR then dir = os._PREDIR os._PREDIR = nil else -- error return nil, string.format("not found the previous directory %s", os.strerror()) end end -- is directory? if os.isdir(dir) then -- change to directory if not os.chdir(dir) then return nil, string.format("cannot change directory %s %s", dir, os.strerror()) end -- save the previous directory os._PREDIR = oldir -- not exists? else return nil, string.format("cannot change directory %s, not found this directory %s", dir, os.strerror()) end -- do chdir callback for scheduler if os._SCHED_CHDIR then os._SCHED_CHDIR(os.curdir()) end return oldir end -- touch file or directory, it will modify atime/mtime or create a new file -- we will do not change it if atime/mtime is zero function os.touch(filepath, opt) opt = opt or {} if os._touch and not os._touch(filepath, opt.atime or 0, opt.mtime or 0) then return false, string.format("cannot touch %s, %s", filepath, os.strerror()) end return true end -- create directories function os.mkdir(dir) -- check arguments if not dir then return false, string.format("invalid arguments!") end -- support path instance dir = tostring(dir) -- create directories local dirs = table.wrap(os._match_wildcard_pathes(dir)) for _, _dir in ipairs(dirs) do if not os._mkdir(_dir) then return false, string.format("cannot create directory: %s, %s", _dir, os.strerror()) end end return true end -- remove directories function os.rmdir(dir) -- check arguments if not dir then return false, string.format("invalid arguments!") end -- support path instance dir = tostring(dir) -- remove directories local dirs = table.wrap(os._match_wildcard_pathes(dir)) for _, _dir in ipairs(dirs) do if not os._rmdir(_dir) then return false, string.format("cannot remove directory: %s, %s", _dir, os.strerror()) end end return true end -- get the temporary directory function os.tmpdir(opt) -- is in fakeroot? @note: uid always be 0 in root and fakeroot if os._FAKEROOT == nil then local ldpath = os.getenv("LD_LIBRARY_PATH") if ldpath and ldpath:find("libfakeroot", 1, true) then os._FAKEROOT = true else os._FAKEROOT = false end end -- get root tmpdir local tmpdir_root = nil if opt and opt.ramdisk == false then if os._ROOT_TMPDIR == nil then os._ROOT_TMPDIR = (os.getenv("XMAKE_TMPDIR") or os.getenv("TMPDIR") or os._tmpdir()):trim() end tmpdir_root = os._ROOT_TMPDIR else if os._ROOT_TMPDIR_RAM == nil then os._ROOT_TMPDIR_RAM = (os.getenv("XMAKE_TMPDIR") or os._ramdir() or os.getenv("TMPDIR") or os._tmpdir()):trim() end tmpdir_root = os._ROOT_TMPDIR_RAM end -- make sub-directory name local subdir = os._TMPSUBDIR if not subdir then local name = "." .. xmake._NAME subdir = path.join((os._FAKEROOT and (name .. "fake") or name) .. (os.uid().euid or ""), os.date("%y%m%d")) os._TMPSUBDIR = subdir end -- get a temporary directory for each user local tmpdir = path.join(tmpdir_root, subdir) if not os.isdir(tmpdir) then os.mkdir(tmpdir) end return tmpdir end -- generate the temporary file path -- -- e.g. -- os.tmpfile("key") -- os.tmpfile({key = "xxx", ramdisk = false}) -- function os.tmpfile(opt_or_key) local opt local key = opt_or_key if type(key) == "table" then key = opt_or_key.key opt = opt_or_key end return path.join(os.tmpdir(opt), "_" .. (hash.uuid4(key):gsub("-", ""))) end -- exit program function os.exit(...) return os._exit(...) end -- register exit callback -- -- e.g. -- os.atexit(function (ok, errors) -- print(ok, errors) -- end) -- function os.atexit(on_exit) local exit_callbacks = os._EXIT_CALLBACKS if exit_callbacks == nil then exit_callbacks = {} os._EXIT_CALLBACKS = exit_callbacks end table.insert(exit_callbacks, on_exit) end -- run command function os.run(cmd) -- parse arguments local argv = os.argv(cmd) if not argv or #argv <= 0 then return false, string.format("invalid command: %s", cmd) end -- run it return os.runv(argv[1], table.slice(argv, 2)) end -- run command with arguments list function os.runv(program, argv, opt) -- init options opt = opt or {} -- make temporary log file local logfile = os.tmpfile() -- execute it local ok, errors = os.execv(program, argv, table.join(opt, {stdout = opt.stdout or logfile, stderr = opt.stderr or logfile})) if ok ~= 0 then -- get command local cmd = program if argv then cmd = cmd .. " " .. os.args(argv) end -- get subprocess errors if ok ~= nil then errors = io.readfile(logfile) if not errors or #errors == 0 then errors = string.format("runv(%s) failed(%d)", cmd, ok) end else errors = string.format("cannot runv(%s), %s", cmd, errors and errors or "unknown reason") end -- remove the temporary log file os.rm(logfile) -- failed return false, errors end -- remove the temporary log file os.rm(logfile) -- ok return true end -- execute command function os.exec(cmd) -- parse arguments local argv = os.argv(cmd) if not argv or #argv <= 0 then return -1 end -- run it return os.execv(argv[1], table.slice(argv, 2)) end -- execute command with arguments list -- -- @param program "clang", "xcrun -sdk macosx clang", "~/dir/test\ xxx/clang" -- filename "clang", "xcrun"", "~/dir/test\ xxx/clang" -- @param argv the arguments -- @param opt the options, e.g. {stdin = filepath/file/pipe, stdout = filepath/file/pipe, stderr = filepath/file/pipe, -- envs = {PATH = "xxx;xx", CFLAGS = "xx"}} -- function os.execv(program, argv, opt) -- is not executable program file? opt = opt or {} local filename = tostring(program) if not os.isexec(program) then -- parse the filename and arguments, e.g. "xcrun -sdk macosx clang" local splitinfo = program:split("%s") filename = splitinfo[1] if #splitinfo > 1 then argv = table.join(table.slice(splitinfo, 2), argv) end end -- run shell file? parse `#!/usr/bin/env bash` in xx.sh -- -- e.g. os.execv("./configure", {"--help"}) => os.execv("/usr/bin/env", {"bash", "./configure", "--help"}) if opt.shell and os.isfile(filename) then local shellfile = filename local file = io.open(filename, 'r') for line in file:lines() do if line and line:startswith("#!") then -- we cannot run `/bin/sh` directly on windows -- because `/bin/sh` is not real file path, maybe we need to convert it. local host = os.host() if host == "windows" then filename = os._get_shell_path(opt) or "sh" argv = table.join(shellfile, argv) else line = line:sub(3) local shellargv = {} local splitinfo = line:split("%s") filename = splitinfo[1] if #splitinfo > 1 then shellargv = table.slice(splitinfo, 2) end table.insert(shellargv, shellfile) table.join2(shellargv, argv) argv = shellargv end break end end file:close() end -- uses the given environments? local envs = nil local setenvs = opt.setenvs or opt.envs local addenvs = opt.addenvs if setenvs or addenvs then local envars = os.getenvs() if setenvs then for k, v in pairs(setenvs) do if type(v) == "table" then v = path.joinenv(v) end envars[k] = v end end if addenvs then for k, v in pairs(addenvs) do if type(v) == "table" then v = path.joinenv(v) end local o = envars[k] if o then v = v .. path.envsep() .. o end envars[k] = v end end envs = {} for k, v in pairs(envars) do -- we try to fix too long value before running process if type(v) == "string" and #v > 4096 and os.host() == "windows" then v = os._deduplicate_pathenv(v) end table.insert(envs, k .. '=' .. v) end end -- init open options local openopt = { envs = envs, stdin = opt.stdin, stdout = opt.stdout, stderr = opt.stderr, curdir = opt.curdir, detach = opt.detach, exclusive = opt.exclusive} -- open command local ok = -1 local errors local proc = process.openv(filename, argv or {}, openopt) if proc ~= nil then -- trace process if os._is_tracing_process() then -- we cannot use cprint, it will cause dead-loop on windows, winos.version/os.iorunv utils.print("%s: %s %s", proc, filename, argv and os.args(argv) or "") end -- wait process if not opt.detach then local waitok, status = proc:wait(opt.timeout or -1) if waitok > 0 then ok = status elseif waitok == 0 and opt.timeout then proc:kill() waitok, status = proc:wait(-1) if waitok > 0 then ok = status end errors = "wait process timeout" end else ok = 0 end -- close process proc:close() else -- cannot execute process return nil, os.strerror() end return ok, errors end -- run command and return output and error data function os.iorun(cmd) -- parse arguments local argv = os.argv(cmd) if not argv or #argv <= 0 then return false, string.format("invalid command: %s", cmd) end -- run it return os.iorunv(argv[1], table.slice(argv, 2)) end -- run command with arguments and return output and error data function os.iorunv(program, argv, opt) -- make temporary output and error file opt = opt or {} local outfile = os.tmpfile() local errfile = os.tmpfile() -- run command local ok, errors = os.execv(program, argv, table.join(opt, {stdout = outfile, stderr = errfile})) if ok == nil then local cmd = program if argv then cmd = cmd .. " " .. os.args(argv) end errors = string.format("cannot runv(%s), %s", cmd, errors and errors or "unknown reason") end -- get output and error data local outdata = io.readfile(outfile) local errdata = io.readfile(errfile) -- remove the temporary output and error file os.rm(outfile) os.rm(errfile) return ok == 0, outdata, errdata, errors end -- raise an exception and abort the current script -- -- the parent function will capture it if we uses pcall or xpcall -- function os.raiselevel(level, msg, ...) -- set level of this function level = level + 1 -- flush log log:flush() -- flush io buffer io.flush() -- raise it if type(msg) == "string" then error(string.tryformat(msg, ...), level) elseif type(msg) == "table" then local errobjstr, errors = string.serialize(msg, {strip = true, indent = false}) if errobjstr then error("[@encode(error)]: " .. errobjstr, level) else error(errors, level) end elseif msg ~= nil then error(tostring(msg), level) else error(msg, level) end end -- raise an exception and abort the current script -- -- the parent function will capture it if we uses pcall or xpcall -- function os.raise(msg, ...) -- add return to make it a tail call return os.raiselevel(1, msg, ...) end -- is executable program file? function os.isexec(filepath) assert(filepath) -- TODO -- check permission -- check executable program exist if os.isfile(filepath) then return true end if os.host() == "windows" then for _, suffix in ipairs({".exe", ".cmd", ".bat"}) do if os.isfile(filepath .. suffix) then return true end end end end -- get system host function os.host() return xmake._HOST end -- get system architecture function os.arch() return xmake._ARCH end -- get subsystem host, e.g. msys, cygwin on windows function os.subhost() return xmake._SUBHOST end -- get subsystem host architecture function os.subarch() return xmake._SUBARCH end -- get features function os.features() return xmake._FEATURES end -- the current host is belong to the given hosts? function os.is_host(...) return os._is_host(os.host(), ...) end -- the current architecture is belong to the given architectures? function os.is_arch(...) return os._is_arch(os.arch(), ...) end -- the current subsystem host is belong to the given hosts? function os.is_subhost(...) return os._is_host(os.subhost(), ...) end -- the current subsystem architecture is belong to the given architectures? function os.is_subarch(...) return os._is_arch(os.subarch(), ...) end -- get the system null device function os.nuldev(input) if input then if os.host() == "windows" then -- init the input nuldev if xmake._NULDEV_INPUT == nil then -- create an empty file -- -- for fix issue on mingw: -- $ gcc -fopenmp -S -o nul -xc nul -- gcc: fatal error:input file 'nul' is the same as output file -- local inputfile = os.tmpfile() io.writefile(inputfile, "") xmake._NULDEV_INPUT = inputfile end else if xmake._NULDEV_INPUT == nil then xmake._NULDEV_INPUT = "/dev/null" end end return xmake._NULDEV_INPUT else if os.host() == "windows" then -- @note cannot cache this file path to avoid multi-processes writing to the same file at the same time return os.tmpfile() else if xmake._NULDEV_OUTPUT == nil then xmake._NULDEV_OUTPUT = "/dev/null" end return xmake._NULDEV_OUTPUT end end end -- get uid function os.uid(...) os._UID = {} if os._uid then os._UID = os._uid(...) or {} end return os._UID end -- get gid function os.gid(...) os._GID = {} if os._gid then os._GID = os._gid(...) or {} end return os._GID end -- get pid function os.getpid(...) local pid = os._PID if pid == nil then pid = os._getpid() os._PID = pid end return pid end -- check the current command is running as root function os.isroot() return os.uid().euid == 0 end -- is case-insensitive filesystem? function os.fscase(filepath) if os._FSCASE == nil or filepath then if os._fscase then if filepath then assert(os.exists(filepath), filepath .. " not found in os.fscase()") else local tmpdir = os.tmpdir() if not os.isdir(tmpdir) then os.mkdir(tmpdir) end filepath = tmpdir end local fscase = os._fscase(filepath) if fscase ~= -1 then os._FSCASE = (fscase == 1) return os._FSCASE end end if os.host() == "windows" then os._FSCASE = false else -- get temporary directory local tmpdir = os.tmpdir() -- get matching pattern, this is equal to os.filedirs(path.join(tmpdir, "*")) -- -- @note we cannot use os.match() becase os.fscase() will be called in os.match() -- local pattern = path.join(tmpdir, "*") pattern = pattern:gsub("([%+%.%-%^%$%(%)%%])", "%%%1") pattern = pattern:gsub("%*", "\002") pattern = pattern:gsub("\002", "[^/]*") -- attempt to detect it local file = os.find(tmpdir, pattern, 0, -1, nil, function (file, isdir) return false end) if file and #file > 0 then local file1 = file[1] local file2 = file1:gsub(".", function (ch) return (ch >= 'a' and ch <= 'z') and ch:upper() or ch:lower() end) os._FSCASE = not (os.exists(file1) and os.exists(file2)) else os._FSCASE = true end end end return os._FSCASE end -- get shell function os.shell() return require("base/tty").shell() end -- get term function os.term() return require("base/tty").term() end -- get all current environment variables -- e.g. envs["PATH"] = "/xxx:/yyy/foo" function os.getenvs() local envs = {} for _, line in ipairs(os._getenvs()) do local p = line:find('=', 1, true) if p then local key = line:sub(1, p - 1):trim() -- only translate Path to PATH on windows -- @see https://github.com/xmake-io/xmake/issues/3752 if os.host() == "windows" and key:lower() == "path" then key = key:upper() end local values = line:sub(p + 1):trim() if #key > 0 then envs[key] = values end end end return envs end -- set all current environment variables -- e.g. envs["PATH"] = "/xxx:/yyy/foo" function os.setenvs(envs) local oldenvs = os.getenvs() if envs then local changed = false -- remove new added values for name, _ in pairs(oldenvs) do if not envs[name] then if os._setenv(name, "") then changed = true end end end -- change values for name, values in pairs(envs) do if oldenvs[name] ~= values then if os._setenv(name, values) then changed = true end end end if changed then os._notify_envs_changed(envs) end end return oldenvs end -- add environment variables -- e.g. envs["PATH"] = "/xxx:/yyy/foo" function os.addenvs(envs) local oldenvs = os.getenvs() if envs then local changed = false for name, values in pairs(envs) do local ok local oldenv = oldenvs[name] if oldenv == "" or oldenv == nil then ok = os._setenv(name, values) elseif not oldenv:startswith(values) then ok = os._setenv(name, values .. path.envsep() .. oldenv) end if ok then changed = true end end if changed then os._notify_envs_changed() end end return oldenvs end -- join environment variables function os.joinenvs(envs, oldenvs) oldenvs = oldenvs or os.getenvs() local newenvs = oldenvs if envs then newenvs = table.copy(oldenvs) for name, values in pairs(envs) do local oldenv = oldenvs[name] if oldenv == "" or oldenv == nil then newenvs[name] = values elseif not oldenv:startswith(values) then newenvs[name] = values .. path.envsep() .. oldenv end end end return newenvs end -- set values to environment variable function os.setenv(name, ...) local ok local values = {...} if #values <= 1 then -- keep compatible with original implementation ok = os._setenv(name, values[1] or "") else ok = os._setenv(name, path.joinenv(values)) end if ok then os._notify_envs_changed() end return ok end -- add values to environment variable function os.addenv(name, ...) local values = {...} if #values > 0 then local ok local changed = false local oldenv = os.getenv(name) local appendenv = path.joinenv(values) if oldenv == "" or oldenv == nil then ok = os._setenv(name, appendenv) if ok then changed = true end elseif not oldenv:startswith(appendenv) then ok = os._setenv(name, appendenv .. path.envsep() .. oldenv) if ok then changed = true end else ok = true end if changed then os._notify_envs_changed() end return ok else return true end end -- set values to environment variable with the given seperator function os.setenvp(name, values, sep) sep = sep or path.envsep() local ok = os._setenv(name, table.concat(table.wrap(values), sep)) if ok then os._notify_envs_changed() end return ok end -- add values to environment variable with the given seperator function os.addenvp(name, values, sep) sep = sep or path.envsep() values = table.wrap(values) if #values > 0 then local ok local changed = false local oldenv = os.getenv(name) local appendenv = table.concat(values, sep) if oldenv == "" or oldenv == nil then ok = os._setenv(name, appendenv) if ok then changed = true end elseif not oldenv:startswith(appendenv) then ok = os._setenv(name, appendenv .. sep .. oldenv) if ok then changed = true end else ok = true end if changed then os._notify_envs_changed() end return ok else return true end end -- read string data from pasteboard function os.pbpaste() if os.host() == "macosx" then local ok, result = os.iorun("pbpaste") if ok then return result end elseif os.host() == "linux" then local ok, result = os.iorun("xsel --clipboard --output") if ok then return result end else -- TODO end end -- copy string data to pasteboard function os.pbcopy(data) if os.host() == "macosx" then os.run("bash -c \"echo '" .. data .. "' | pbcopy\"") elseif os.host() == "linux" then os.run("bash -c \"echo '" .. data .. "' | xsel --clipboard --input\"") else -- TODO end end -- get cpu info function os.cpuinfo(name) return require("base/cpu").info(name) end -- get memory info function os.meminfo(name) return require("base/memory").info(name) end -- get the default parallel jobs number function os.default_njob() local njob local ncpu = os.cpuinfo().ncpu if ncpu > 2 then njob = ncpu + 2 if os.host() == "windows" and njob > 128 then njob = 128 end if njob > 512 then njob = 512 end elseif ncpu == 2 then njob = 3 else njob = 2 end return njob or 2 end -- read the content of symlink function os.readlink(symlink) return os._readlink(path.absolute(symlink)) end -- get the program directory function os.programdir() return xmake._PROGRAM_DIR end -- get the program file function os.programfile() return xmake._PROGRAM_FILE end -- get the working directory function os.workingdir() return xmake._WORKING_DIR end -- get the project directory function os.projectdir() return xmake._PROJECT_DIR end -- get the project file function os.projectfile() return xmake._PROJECT_FILE end -- return module return os
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/pipe.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 pipe.lua -- -- define module local pipe = pipe or {} local _instance = _instance or {} -- load modules local io = require("base/io") local bytes = require("base/bytes") local table = require("base/table") local string = require("base/string") local scheduler = require("base/scheduler") -- the pipe events, @see tbox/platform/pipe.h pipe.EV_READ = 1 pipe.EV_WRITE = 2 pipe.EV_CONN = 2 -- new a pipe file function _instance.new(cdata, name) local pipefile = table.inherit(_instance) pipefile._NAME = name pipefile._PIPE = cdata setmetatable(pipefile, _instance) return pipefile end -- get the pipe name function _instance:name() return self._NAME end -- get poller object type, poller.OT_PIPE function _instance:otype() return 2 end -- get cdata of pipe file function _instance:cdata() return self._PIPE end -- write data to pipe file function _instance:write(data, opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- get data address and size for bytes and string if type(data) == "string" then data = bytes(data) end local datasize = data:size() local dataaddr = data:caddr() -- init start and last opt = opt or {} local start = opt.start or 1 local last = opt.last or datasize if start < 1 or start > datasize then return -1, string.format("%s: invalid start(%d)!", self, start) end if last < start - 1 or last > datasize + start - 1 then return -1, string.format("%s: invalid last(%d)!", self, last) end -- write it local write = 0 local real = 0 local errors = nil if opt.block then local size = last + 1 - start while start <= last do real, errors = io.pipe_write(self:cdata(), dataaddr + start - 1, last + 1 - start) if real > 0 then write = write + real start = start + real elseif real == 0 then local events, waiterrs = _instance.wait(self, pipe.EV_WRITE, opt.timeout or -1) if events ~= pipe.EV_WRITE then errors = waiterrs break end else break end end if write ~= size then write = -1 end else write, errors = io.pipe_write(self:cdata(), dataaddr + start - 1, last + 1 - start) if write < 0 and errors then errors = string.format("%s: %s", self, errors) end end return write, errors end -- read data from pipe function _instance:read(buff, size, opt) assert(buff) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- check buffer size = size or buff:size() if buff:size() < size then return -1, string.format("%s: too small buffer!", self) end -- check size if size == 0 then return 0 elseif size == nil or size < 0 then return -1, string.format("%s: invalid size(%d)!", self, size) end -- init start in buffer opt = opt or {} local start = opt.start or 1 local pos = start - 1 if start >= buff:size() or start < 1 then return -1, string.format("%s: invalid start(%d)!", self, start) end -- read it local read = 0 local real = 0 local data_or_errors = nil if opt.block then local results = {} while read < size do real, data_or_errors = io.pipe_read(self:cdata(), buff:caddr() + pos + read, math.min(buff:size() - pos - read, size - read)) if real > 0 then read = read + real elseif real == 0 then local events, waiterrs = _instance.wait(self, pipe.EV_READ, opt.timeout or -1) if events ~= pipe.EV_READ then data_or_errors = waiterrs break end else break end end if read == size then data_or_errors = buff:slice(start, read) else read = -1 end else read, data_or_errors = io.pipe_read(self:cdata(), buff:caddr() + pos, math.min(buff:size() - pos, size)) if read > 0 then data_or_errors = buff:slice(start, read) end end if read < 0 and data_or_errors then data_or_errors = string.format("%s: %s", self, data_or_errors) end return read, data_or_errors end -- connect pipe, only for named pipe (server-side) function _instance:connect(opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- only for named pipe if not self:name() then return -1, string.format("%s: cannot connect to anonymous pipe!", self) end -- connect it local ok, errors = io.pipe_connect(self:cdata()) if ok == 0 then opt = opt or {} local events, waiterrs = _instance.wait(self, pipe.EV_CONN, opt.timeout or -1) if events == pipe.EV_CONN then ok, errors = io.pipe_connect(self:cdata()) else errors = waiterrs end end if ok < 0 and errors then errors = string.format("%s: %s", self, errors) end return ok, errors end -- wait pipe events function _instance:wait(events, timeout) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- wait events local result = -1 local errors = nil if scheduler:co_running() then result, errors = scheduler:poller_wait(self, events, timeout or -1) else result, errors = io.pipe_wait(self:cdata(), events, timeout or -1) end if result < 0 and errors then errors = string.format("%s: %s", self, errors) end return result, errors end -- close pipe file function _instance:close() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- cancel pipe events from the scheduler if scheduler:co_running() then ok, errors = scheduler:poller_cancel(self) if not ok then return false, errors end end -- close it ok = io.pipe_close(self:cdata()) if ok then self._PIPE = nil end return ok end -- ensure the pipe is opened function _instance:_ensure_opened() if not self:cdata() then return false, string.format("%s: has been closed!", self) end return true end -- tostring(pipe) function _instance:__tostring() return "<pipe: " .. (self:name() or "anonymous") .. ">" end -- gc(pipe) function _instance:__gc() if self:cdata() and io.pipe_close(self:cdata()) then self._PIPE = nil end end -- open a named pipe file -- -- 1. named pipe (server-side): -- -- local pipe, errors = pipe.open("xxx", 'w') -- if pipe then -- if pipe:connect() then -- pipe:write(...) -- end -- pipe:close() -- end -- -- 2. named pipe (client-side): -- -- local pipe, errors = pipe.open("xxx") -- if pipe then -- pipe:read(...) -- pipe:close() -- end -- -- mode: "r", "w", "rB" (block), "wB" (block), "rA" (non-block), "wA" (non-block) -- function pipe.open(name, mode, buffsize) -- open named pipe local pipefile, errors = io.pipe_open(name, mode, buffsize or 0) if pipefile then return _instance.new(pipefile, name) else return nil, string.format("failed to open pipe: %s, %s", name, errors or "unknown reason") end end -- open anonymous pipe pair -- -- local rpipe, wpipe, errors = pipe.openpair() -- rpipe:read(...) -- wpipe:write(...) -- -- mode: -- -- "BB": read block/write block -- "BA": read block/write non-block -- "AB": read non-block/write block -- "AA": read non-block/write non-block (default) -- function pipe.openpair(mode, buffsize) -- open anonymous pipe pair local rpipefile, wpipefile, errors = io.pipe_openpair(mode, buffsize or 0) if rpipefile and wpipefile then return _instance.new(rpipefile), _instance.new(wpipefile) else return nil, nil, string.format("failed to open anonymous pipe pair, %s", errors or "unknown reason") end end -- return module return pipe
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/bloom_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 bloom_filter.lua -- -- define module: bloom_filter local bloom_filter = bloom_filter or {} local _instance = _instance or {} -- load modules local io = require("base/io") local utils = require("base/utils") local bytes = require("base/bytes") local table = require("base/table") -- save metatable and builtin functions bloom_filter._open = bloom_filter._open or bloom_filter.open bloom_filter._close = bloom_filter._close or bloom_filter.close bloom_filter._data = bloom_filter._data or bloom_filter.data bloom_filter._size = bloom_filter._size or bloom_filter.size bloom_filter._data_set = bloom_filter._data_set or bloom_filter.data_set bloom_filter._clear = bloom_filter._clear or bloom_filter.clear bloom_filter._set = bloom_filter._set or bloom_filter.set bloom_filter._get = bloom_filter._get or bloom_filter.get -- the bloom filter probability bloom_filter.PROBABILITY_0_1 = 3 -- 1 / 2^3 = 0.125 ~= 0.1 bloom_filter.PROBABILITY_0_01 = 6 -- 1 / 2^6 = 0.015625 ~= 0.01 bloom_filter.PROBABILITY_0_001 = 10 -- 1 / 2^10 = 0.0009765625 ~= 0.001 bloom_filter.PROBABILITY_0_0001 = 13 -- 1 / 2^13 = 0.0001220703125 ~= 0.0001 bloom_filter.PROBABILITY_0_00001 = 16 -- 1 / 2^16 = 0.0000152587890625 ~= 0.00001 bloom_filter.PROBABILITY_0_000001 = 20 -- 1 / 2^20 = 0.00000095367431640625 ~= 0.000001 -- new a bloom filter function _instance.new(handle) local instance = table.inherit(_instance) instance._HANDLE = handle setmetatable(instance, _instance) return instance end -- get cdata of the bloom filter function _instance:cdata() return self._HANDLE end -- get the bloom filter data function _instance:data() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return nil, errors end -- get the bloom filter data local data = bloom_filter._data(self:cdata()) local size = bloom_filter._size(self:cdata()) if not data or size == 0 then return nil, "no data!" end -- mount this data return bytes(size, data) end -- set the bloom filter data function _instance:data_set(data) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- set data local datasize = data:size() local dataaddr = data:caddr() if not dataaddr or datasize == 0 then return false, "empty data!" end return bloom_filter._data_set(self:cdata(), dataaddr, datasize) end -- clear the bloom filter data function _instance:clear() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- do clear return bloom_filter._clear(self:cdata()) end -- set the bloom filter data item -- --@code -- if bloom_filter:set(item)) then -- print("this data not exists, set ok!") -- else -- -- note: maybe false positives -- print("this data have been existed, set failed!") -- end --@endcode -- function _instance:set(item) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- do set ok = bloom_filter._set(self:cdata(), item) return true, ok end -- get the bloom filter data item -- --@code -- if bloom_filter:get(item)) then -- -- note: maybe false positives -- print("this data have been existed, get ok!") -- else -- print("this data not exists, get failed!") -- end --@endcode -- function _instance:get(item) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- do get ok = bloom_filter._get(self:cdata(), item) return true, ok end -- ensure it is opened function _instance:_ensure_opened() if not self:cdata() then return false, string.format("%s: has been closed!", self) end return true end -- tostring(bloom_filter) function _instance:__tostring() return string.format("<bloom_filter: %s>", self:cdata()) end -- gc(bloom_filter) function _instance:__gc() if self:cdata() and bloom_filter._close(self:cdata()) then self._HANDLE = nil end end -- new a bloom filter, e.g. {probability = 0.001, hash_count = 3, item_maxn = 1000000} function bloom_filter.new(opt) opt = opt or {} local probability = opt.probability or 0.001 local maps = { [0.1] = bloom_filter.PROBABILITY_0_1, [0.01] = bloom_filter.PROBABILITY_0_01, [0.001] = bloom_filter.PROBABILITY_0_001, [0.0001] = bloom_filter.PROBABILITY_0_0001, [0.00001] = bloom_filter.PROBABILITY_0_00001, [0.000001] = bloom_filter.PROBABILITY_0_000001 } probability = assert(maps[probability], "invalid probability(%f)", probability) local hash_count = opt.hash_count or 3 local item_maxn = opt.item_maxn or 1000000 local handle, errors = bloom_filter._open(probability, hash_count, item_maxn) if handle then return _instance.new(handle) else return nil, errors or "failed to open a bloom filter!" end end -- return module: bloom_filter return bloom_filter
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/timer.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 timer.lua -- -- load modules local heap = require("base/heap") local object = require("base/object") -- define module: timer local timer = timer or object() -- tostring(timer) function timer:__tostring() return string.format("<timer: %s>", self:name()) end -- get all timer tasks function timer:_tasks() return self._TASKS end -- post timer task after delay and will be auto-remove it after be expired function timer:post(func, delay, opt) return self:post_at(func, os.mclock() + delay, delay, opt) end -- post timer task at the absolute time and will be auto-remove it after be expired -- -- we can mark the returned task as canceled to cancel the pending task, e.g. task.cancel = true -- function timer:post_at(func, when, period, opt) opt = opt or {} local task = {when = when, func = func, period = period, continuous = opt.continuous, cancel = false} self:_tasks():push(task) return task end -- post timer task after the relative time and will be auto-remove it after be expired function timer:post_after(func, after, period, opt) return self:post_at(func, os.mclock() + after, period, opt) end -- get the delay of next task function timer:delay() local delay = nil local tasks = self:_tasks() if tasks:length() > 0 then local task = tasks:peek() if task then local now = os.mclock() delay = task.when > now and task.when - now or 0 end end return delay end -- run the timer next loop function timer:next() local tasks = self:_tasks() while tasks:length() > 0 do local triggered = false local task = tasks:peek() if task then -- timeout or canceled? if task.cancel or task.when <= os.mclock() then tasks:pop() if task.continuous and not task.cancel then task.when = os.mclock() + task.period tasks:push(task) end -- run timer task if task.func then local ok, errors = task.func(task.cancel) if not ok then return false, errors end triggered = true end end end if not triggered then break end end return true end -- kill all timer tasks function timer:kill() local tasks = self:_tasks() while tasks:length() > 0 do local task = tasks:peek() if task then tasks:pop() if task.func then -- cancel it task.func(true) end end end end -- get timer name function timer:name() return self._NAME end -- init timer function timer:init(name) self._NAME = name or "none" self._TASKS = heap.valueheap {cmp = function(a, b) return a.when < b.when end} end -- new timer function timer:new(name) self = self() self:init(name) return self end -- return module: timer return timer
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/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 -- -- define module: filter local filter = filter or {} -- load modules local os = require("base/os") local winos = require("base/winos") local table = require("base/table") local utils = require("base/utils") local string = require("base/string") local scheduler = require("base/scheduler") -- globals local escape_table1 = {["$"] = "\001", ["("] = "\002", [")"] = "\003", ["%"] = "\004"} local escape_table2 = {["\001"] = "$", ["\002"] = "(", ["\003"] = ")", ["\004"] = "%"} -- new filter instance function filter.new() -- init an filter instance local self = table.inherit(filter) -- init handler self._HANDLERS = {} -- ok return self end -- filter the shell command -- -- e.g. -- -- print("$(shell echo hello xmake)") -- add_ldflags("$(shell pkg-config --libs sqlite3)") -- function filter.shell(cmd) -- empty? if #cmd == 0 then os.raise("empty $(shell)!") end -- run shell scheduler:enable(false) -- disable coroutine scheduler to fix `attempt to yield across C-call boundary` when call gsub -> yield local ok, outdata, errdata = os.iorun(cmd) scheduler:enable(true) if not ok then os.raise("run $(shell %s) failed, errors: %s", cmd, errdata or "") end -- trim it if outdata then outdata = outdata:trim() end -- return the shell result return outdata end -- filter the environment variables function filter.env(name) return os.getenv(name) end -- filter the winreg path function filter.reg(path) -- must be windows if os.host() ~= "windows" then return end -- query registry value return (winos.registry_query(path)) end -- set handlers function filter:set_handlers(handlers) self._HANDLERS = handlers end -- get handlers function filter:handlers() return self._HANDLERS end -- register handler function filter:register(name, handler) self._HANDLERS[name] = handler end -- get variable value function filter:get(variable) -- check assert(variable) -- is shell? if variable:startswith("shell ") then return filter.shell(variable:sub(7)) -- is environment variable? elseif variable:startswith("env ") then return filter.env(variable:sub(5)) elseif variable:startswith("reg ") then return filter.reg(variable:sub(5)) end -- parse variable:mode local varmode = variable:split(':') local mode = varmode[2] variable = varmode[1] -- handler it local result = nil for name, handler in pairs(self._HANDLERS) do result = handler(variable) if result then break end end -- TODO need improve -- handle mode if mode and result then if mode == "upper" then result = result:upper() elseif mode == "lower" then result = result:lower() end end -- ok? return result end -- filter the builtin variables: "hello $(variable)" for string -- -- e.g. -- -- print("$(host)") -- print("$(env PATH)") -- print("$(shell echo hello xmake!)") -- print("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\XXXX;Name)") -- function filter:handle(value) -- check assert(type(value) == "string") -- escape "%$", "%(", "%)", "%%" to "\001", "\002", "\003", "\004" value = value:gsub("%%([%$%(%)%%])", function (ch) return escape_table1[ch] end) -- filter the builtin variables local values = {} local variables = {} value:gsub("%$%((.-)%)", function (variable) table.insert(variables, variable) end) -- we cannot call self:get() in gsub, because it will trigger "attempt to yield a c-call boundary" for _, variable in ipairs(variables) do -- escape "%$", "%(", "%)", "%%" to "$", "(", ")", "%" local name = variable:gsub("[\001\002\003\004]", function (ch) return escape_table2[ch] end) values[variable] = self:get(name) or "" end value = value:gsub("%$%((.-)%)", function (variable) return values[variable] end) return value:gsub("[\001\002\003\004]", function (ch) return escape_table2[ch] end) end -- return module: filter return filter
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/socket.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 socket.lua -- -- define module local socket = socket or {} local _instance = _instance or {} -- load modules local io = require("base/io") local libc = require("base/libc") local bytes = require("base/bytes") local table = require("base/table") local string = require("base/string") local scheduler = require("base/scheduler") -- the socket types socket.TCP = 1 socket.UDP = 2 socket.ICMP = 3 -- the socket families socket.IPV4 = 1 socket.IPV6 = 2 socket.UNIX = 3 -- the socket events, @see tbox/platform/socket.h socket.EV_RECV = 1 socket.EV_SEND = 2 socket.EV_CONN = socket.EV_SEND socket.EV_ACPT = socket.EV_RECV -- the socket control code socket.CTRL_SET_RECVBUFF = 2 socket.CTRL_SET_SENDBUFF = 4 -- new a socket function _instance.new(socktype, family, sock) local instance = table.inherit(_instance) instance._SOCK = sock instance._TYPE = socktype instance._FAMILY = family setmetatable(instance, _instance) return instance end -- get socket type function _instance:type() return self._TYPE end -- get socket family function _instance:family() return self._FAMILY end -- get cdata of socket function _instance:cdata() return self._SOCK end -- get poller object type, poller.OT_SOCK function _instance:otype() return 1 end -- get socket rawfd function _instance:rawfd() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return nil, errors end -- get rawfd local result, errors = io.socket_rawfd(self:cdata()) if not result and errors then errors = string.format("%s: %s", self, errors) end return result, errors end -- get socket peer address function _instance:peeraddr() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return nil, errors end -- get peer address local result, errors = io.socket_peeraddr(self:cdata()) if not result and errors then errors = string.format("%s: %s", self, errors) end return result, errors end -- control socket function _instance:ctrl(code, value) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- control it local ok, errors = io.socket_ctrl(self:cdata(), code, value) if not ok and errors then errors = string.format("%s: %s", self, errors) end return ok, errors end -- bind socket function _instance:bind(addr, port) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- bind it local ok, errors = io.socket_bind(self:cdata(), addr, port, self:family()) if not ok and errors then errors = string.format("%s: %s", self, errors) end return ok, errors end -- bind socket from the unix address function _instance:bind_unix(addr, opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- must be unix socket if self:family() ~= socket.UNIX then return -1, string.format("%s: must be unix socket!", self) end -- bind it opt = opt or {} local ok, errors = io.socket_bind(self:cdata(), addr, opt.is_abstract, self:family()) if not ok and errors then errors = string.format("%s: %s", self, errors) end return ok, errors end -- listen socket function _instance:listen(backlog) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- listen it local ok, errors = io.socket_listen(self:cdata(), backlog or 10) if not ok and errors then errors = string.format("%s: %s", self, errors) end return ok, errors end -- accept socket function _instance:accept(opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- accept it local sock, errors = io.socket_accept(self:cdata()) if not sock and not errors then opt = opt or {} local events, waiterrs = _instance.wait(self, socket.EV_ACPT, opt.timeout or -1) if events == socket.EV_ACPT then sock, errors = io.socket_accept(self:cdata()) else errors = waiterrs end end if not sock and errors then errors = string.format("%s: %s", self, errors) end if sock then sock = _instance.new(self:type(), self:family(), sock) end return sock, errors end -- connect socket function _instance:connect(addr, port, opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- connect it local ok, errors = io.socket_connect(self:cdata(), addr, port, self:family()) if ok == 0 then opt = opt or {} -- trace socket if socket._is_tracing_socket() then print(string.format("%s: connecting %s:%d, timeout: %d", self, addr, port, opt.timeout or -1)) end local events, waiterrs = _instance.wait(self, socket.EV_CONN, opt.timeout or -1) if events == socket.EV_CONN then ok, errors = io.socket_connect(self:cdata(), addr, port, self:family()) else errors = waiterrs end end if ok < 0 and errors then errors = string.format("%s: %s", self, errors) end return ok, errors end -- connect socket from the unix address function _instance:connect_unix(addr, opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- must be unix socket if self:family() ~= socket.UNIX then return -1, string.format("%s: must be unix socket!", self) end -- connect it opt = opt or {} local ok, errors = io.socket_connect(self:cdata(), addr, opt.is_abstract, self:family()) if ok == 0 then local events, waiterrs = _instance.wait(self, socket.EV_CONN, opt.timeout or -1) if events == socket.EV_CONN then ok, errors = io.socket_connect(self:cdata(), addr, opt.is_abstract, self:family()) else errors = waiterrs end end if ok < 0 and errors then errors = string.format("%s: %s", self, errors) end return ok, errors end -- send data to socket function _instance:send(data, opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- get data address and size for bytes and string if type(data) == "string" then data = bytes(data) end local datasize = data:size() local dataaddr = data:caddr() -- init start and last opt = opt or {} local start = opt.start or 1 local last = opt.last or datasize if start < 1 or start > datasize then return -1, string.format("%s: invalid start(%d)!", self, start) end if last < start - 1 or last > datasize + start - 1 then return -1, string.format("%s: invalid last(%d)!", self, last) end -- send it local send = 0 local real = 0 local wait = false local errors = nil if opt.block then local size = last + 1 - start while start <= last do real, errors = io.socket_send(self:cdata(), dataaddr + start - 1, last + 1 - start) if real > 0 then send = send + real start = start + real wait = false elseif real == 0 and not wait then local events, waiterrs = _instance.wait(self, socket.EV_SEND, opt.timeout or -1) if events == socket.EV_SEND then wait = true elseif events == 0 then os.raise("%s: send timeout!", self) else errors = waiterrs break end else break end end if send ~= size then send = -1 end else send, errors = io.socket_send(self:cdata(), dataaddr + start - 1, last + 1 - start) if send < 0 and errors then errors = string.format("%s: %s", self, errors) end end return send, errors end -- send file to socket function _instance:sendfile(file, opt) -- ensure the socket opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- ensure the file opened local ok, errors = file:_ensure_opened() if not ok then return -1, errors end -- empty file? if file:size() == 0 then return -1, string.format("%s: send empty file!", self) end -- init start and last opt = opt or {} local start = opt.start or 1 local last = opt.last or file:size() -- check start and last if start > last or start < 1 then return -1, string.format("%s: invalid start(%d) and last(%d)!", self, start, last) end -- send it local send = 0 local real = 0 local wait = false local errors = nil if opt.block then local size = last + 1 - start while start <= last do real, errors = io.socket_sendfile(self:cdata(), file._FILE, start, last) if real > 0 then send = send + real start = start + real wait = false elseif real == 0 and not wait then local events, waiterrs = _instance.wait(self, socket.EV_SEND, opt.timeout or -1) if events == socket.EV_SEND then wait = true elseif events == 0 then os.raise("%s: sendfile timeout!", self) else errors = waiterrs break end else break end end if send ~= size then send = -1 end else send, errors = io.socket_sendfile(self:cdata(), file._FILE, start, last) if send < 0 and errors then errors = string.format("%s: %s", self, errors) end end return send, errors end -- recv data from socket function _instance:recv(buff, size, opt) assert(buff) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- check buffer size = size or buff:size() if buff:size() < size then return -1, string.format("%s: too small buffer!", self) end -- check size if size == 0 then return 0 elseif size == nil or size < 0 then return -1, string.format("%s: invalid size(%d)!", self, size) end -- init start in buffer opt = opt or {} local start = opt.start or 1 local pos = start - 1 if start >= buff:size() or start < 1 then return -1, string.format("%s: invalid start(%d)!", self, start) end -- recv it local recv = 0 local real = 0 local wait = false local data_or_errors = nil if opt.block then while recv < size do real, data_or_errors = io.socket_recv(self:cdata(), buff:caddr() + pos + recv, math.min(buff:size() - pos - recv, size - recv)) if real > 0 then recv = recv + real wait = false elseif real == 0 and not wait then local events, waiterrs = _instance.wait(self, socket.EV_RECV, opt.timeout or -1) if events == socket.EV_RECV then wait = true elseif events == 0 then os.raise("%s: recv timeout!", self) else data_or_errors = waiterrs break end else break end end if recv == size then data_or_errors = buff:slice(start, recv) else recv = -1 end else recv, data_or_errors = io.socket_recv(self:cdata(), buff:caddr() + pos, math.min(buff:size() - pos, size)) if recv > 0 then data_or_errors = buff:slice(start, recv) end end if recv < 0 and data_or_errors then data_or_errors = string.format("%s: %s", self, data_or_errors) end return recv, data_or_errors end -- send udp data to peer function _instance:sendto(data, addr, port, opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- only for udp if self:type() ~= socket.UDP then return -1, string.format("%s: sendto() only for udp socket!", self) end -- check address if not addr or not port then return -1, string.format("%s: sendto empty address!", self) end -- get data address and size for bytes and string if type(data) == "string" then data = bytes(data) end local datasize = data:size() local dataaddr = data:caddr() -- init start and last opt = opt or {} local start = opt.start or 1 local last = opt.last or datasize if start < 1 or start > datasize then return -1, string.format("%s: invalid start(%d)!", self, start) end if last < start - 1 or last > datasize + start - 1 then return -1, string.format("%s: invalid last(%d)!", self, last) end -- send it local send = 0 local wait = false local errors = nil if opt.block then while true do send, errors = io.socket_sendto(self:cdata(), dataaddr + start - 1, last + 1 - start, addr, port, self:family()) if send == 0 and not wait then local events, waiterrs = _instance.wait(self, socket.EV_SEND, opt.timeout or -1) if events == socket.EV_SEND then wait = true else errors = waiterrs break end else break end end else send, errors = io.socket_sendto(self:cdata(), dataaddr + start - 1, last + 1 - start, addr, port, self:family()) if send < 0 and errors then errors = string.format("%s: %s", self, errors) end end return send, errors end -- recv udp data from peer function _instance:recvfrom(buff, size, opt) assert(buff) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- only for udp if self:type() ~= socket.UDP then return -1, string.format("%s: sendto() only for udp socket!", self) end -- check buffer size = size or buff:size() if buff:size() < size then return -1, string.format("%s: too small buffer!", self) end -- check size if size == 0 then return 0 elseif size == nil or size < 0 then return -1, string.format("%s: invalid size(%d)!", self, size) end -- init start in buffer opt = opt or {} local start = opt.start or 1 local pos = start - 1 if start >= buff:size() or start < 1 then return -1, string.format("%s: invalid start(%d)!", self, start) end -- recv it local recv = 0 local wait = false local data_or_errors = nil if opt.block then while true do recv, data_or_errors, addr, port = io.socket_recvfrom(self:cdata(), buff:caddr() + pos, math.min(buff:size() - pos, size)) if recv > 0 then data_or_errors = buff:slice(start, recv) break elseif recv == 0 and not wait then local events, waiterrs = _instance.wait(self, socket.EV_RECV, opt.timeout or -1) if events == socket.EV_RECV then wait = true else recv = -1 data_or_errors = waiterrs break end else break end end else recv, data_or_errors, addr, port = io.socket_recvfrom(self:cdata(), buff:caddr() + pos, math.min(buff:size() - pos, size)) if recv > 0 then data_or_errors = buff:slice(start, recv) end end if recv < 0 and data_or_errors then data_or_errors = string.format("%s: %s", self, data_or_errors) end return recv, data_or_errors, addr, port end -- wait socket events function _instance:wait(events, timeout) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- wait events local result = -1 local errors = nil if scheduler:co_running() then result, errors = scheduler:poller_wait(self, events, timeout or -1) else result, errors = io.socket_wait(self:cdata(), events, timeout or -1) end if result < 0 and errors then errors = string.format("%s: %s", self, errors) end return result, errors end -- kill socket function _instance:kill() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- kill it io.socket_kill(self:cdata()) return true end -- close socket function _instance:close() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- cancel socket events from the scheduler if scheduler:co_running() then ok, errors = scheduler:poller_cancel(self) if not ok then return false, errors end end -- close it ok = io.socket_close(self:cdata()) if ok then self._SOCK = nil end return ok end -- ensure the socket is opened function _instance:_ensure_opened() if not self:cdata() then return false, string.format("%s: has been closed!", self) end return true end -- tostring(socket) function _instance:__tostring() local rawfd = self:cdata() and self:rawfd() or "closed" local types = {"tcp", "udp", "icmp"} return string.format("<socket: %s%s/%s>", types[self:type()], self:family() == socket.IPV6 and "6" or "4", rawfd) end -- gc(socket) function _instance:__gc() if self:cdata() and io.socket_close(self:cdata()) then self._SOCK = nil end end -- trace socket for profile(stuck,trace)? function socket._is_tracing_socket() local is_tracing = socket._IS_TRACING_SOCKET if is_tracing == nil then local profile = os.getenv("XMAKE_PROFILE") if profile then profile = profile:trim() if profile == "trace" or profile == "stuck" then is_tracing = true end end is_tracing = is_tracing or false socket._IS_TRACING_SOCKET = is_tracing end return is_tracing end -- open a socket -- -- @param socktype the socket type, e.g. tcp, udp, icmp -- @param family the address family, e.g. ipv4, ipv6 -- -- @return the socket instance -- function socket.open(socktype, family) socktype = socktype or socket.TCP family = family or socket.IPV4 local sock, errors = io.socket_open(socktype, family) if sock then return _instance.new(socktype, family, sock) else return nil, errors or string.format("failed to open socket(%s/%s)!", socktype, family) end end -- open tcp socket function socket.tcp(opt) opt = opt or {} return socket.open(socket.TCP, opt.family or socket.IPV4) end -- open udp socket function socket.udp(opt) opt = opt or {} return socket.open(socket.UDP, opt.family or socket.IPV4) end -- open unix socket function socket.unix(opt) return socket.open(socket.TCP, socket.UNIX) end -- open and bind tcp socket function socket.bind(addr, port, opt) local sock, errors = socket.tcp(opt) if not sock then return nil, errors end local ok, errors = sock:bind(addr, port) if not ok then sock:close() return nil, string.format("bind %s:%s failed, %s!", addr, port, errors or "unknown reason") end return sock end -- open and bind tcp socket from the unix address function socket.bind_unix(addr, opt) local sock, errors = socket.unix(opt) if not sock then return nil, errors end local ok, errors = sock:bind_unix(addr, opt) if not ok then sock:close() return nil, string.format("bind unix://%s failed, %s!", addr, errors or "unknown reason") end return sock end -- open and connect tcp socket function socket.connect(addr, port, opt) local sock, errors = socket.tcp(opt) if not sock then return nil, errors end local ok, errors = sock:connect(addr, port, opt) if ok <= 0 then sock:close() return nil, errors end return sock end -- open and connect tcp socket from the unix address function socket.connect_unix(addr, opt) local sock, errors = socket.unix(opt) if not sock then return nil, errors end local ok, errors = sock:connect_unix(addr, opt) if ok <= 0 then sock:close() return nil, errors end return sock end -- return module return socket
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/cli.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 cli.lua -- -- define module local cli = cli or {} local segment = cli._segment or {} -- load modules local string = require("base/string") local hashset = require("base/hashset") segment.__index = segment cli._segment = segment function segment:__tostring() return self.string end function segment:__todisplay() return string.format("${color.dump.string}%s${reset} ${color.dump.keyword}(%s)${reset}", self.string, self.type) end function segment:is(type) return self.type == type end function cli._make_segment(type, string, argv, argi, obj) obj.type = type obj.string = string obj.argv = argv obj.argi = argi return setmetatable(obj, segment) end function cli._make_arg(value, argv, argi) return cli._make_segment("arg", value, argv, argi, { value = value }) end function cli._make_flag(key, short, argv, argi) return cli._make_segment("flag", short and ("-" .. key) or ("--" .. key), argv, argi, { key = key, value = true, short = short or false }) end function cli._make_option(key, value, short, argv, argi) return cli._make_segment("option", short and ("-" .. key .. " " .. value) or ("--" .. key .. "=" .. value), argv, argi, { key = key, value = value, short = short or false }) end -- parse a argv string, command & sub-command should be omitted before calling this function -- @see https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html function cli.parse(args, flags) return cli.parsev(os.argv(args), flags) end -- parse a argv array, command & sub-command should be omitted before calling this function -- @see https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html function cli.parsev(argv, flags) local parsed = {} local raw = false local index = 1 local value = nil flags = hashset.from(flags or {}) while index <= #argv do value = argv[index] if raw or not value:startswith("-") or #value < 2 then -- all args after "--" or first arg, args don"t start with "-", and short args (include a single char "-") raw = true table.insert(parsed, cli._make_arg(value, argv, index)) elseif value == "--" then -- stop parsing after "--" raw = true table.insert(parsed, cli._make_segment("sep", "--", argv, index, {})) elseif value:startswith("--") then -- "--key:value", "--key=value", "--long-flag" local sep = value:find("[=:]", 3, false) if sep then table.insert(parsed, cli._make_option(value:sub(3, sep - 1), value:sub(sep + 1), false, argv, index)) else table.insert(parsed, cli._make_flag(value:sub(3), false, argv, index)) end else local strp = 2 while strp <= #value do local ch = value:sub(strp, strp) if flags:has(ch) then -- is a flag table.insert(parsed, cli._make_flag(ch, true, argv, index)) else -- is an option if strp == #value then -- is last char, use next arg as value table.insert(parsed, cli._make_option(ch, argv[index + 1] or "", true, argv, index)) index = index + 1 else -- is not last char, use remaining as value table.insert(parsed, cli._make_option(ch, value:sub(strp + 1), true, argv, index)) strp = #value end end strp = strp + 1 end end index = index + 1 end return parsed end -- return module return cli
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/heap.lua
--!A cross-platform build utility based on Lua -- -- priority queue implemented as a binary heap. -- written by Cosmin Apreutesei. Public Domain. -- -- @see https://github.com/luapower/heap -- -- modified by ruki -- @file heap.lua -- -- define module: heap local heap = heap or {} local ffi --init on demand so that the module can be used without luajit local assert, floor = assert, math.floor -- heap algorithm working over abstract API that counts from one. function heap._make(add, remove, swap, length, cmp) local function moveup(child) local parent = floor(child / 2) while child > 1 and cmp(child, parent) do swap(child, parent) child = parent parent = floor(child / 2) end return child end local function movedown(parent) local last = length() local child = parent * 2 while child <= last do if child + 1 <= last and cmp(child + 1, child) then child = child + 1 -- sibling is smaller end if not cmp(child, parent) then break end swap(parent, child) parent = child child = parent * 2 end return parent end local function push(...) add(...) return moveup(length()) end local function pop(i) swap(i, length()) remove() movedown(i) end local function rebalance(i) if moveup(i) == i then movedown(i) end end return push, pop, rebalance end -- cdata heap working over a cdata array function heap.cdataheap(h) ffi = ffi or require("ffi") assert(h and h.size, "size expected") assert(h.size >= 2, "size too small") assert(h.ctype, "ctype expected") local ctype = ffi.typeof(h.ctype) h.data = h.data or ffi.new(ffi.typeof("$[?]", ctype), h.size) local t, n, maxn = h.data, h.length or 0, h.size - 1 local function add(v) n = n + 1; t[n] = v end local function rem() n = n - 1 end local function swap(i, j) t[0] = t[i]; t[i] = t[j]; t[j] = t[0] end local function length() return n end local cmp = h.cmp and function(i, j) return h.cmp(t[i], t[j]) end or function(i, j) return t[i] < t[j] end local push, pop, rebalance = heap._make(add, rem, swap, length, cmp) local function get(i, box) assert(i >= 1 and i <= n, "invalid index") if box then box[0] = t[i] else return ffi.new(ctype, t[i]) end end function h:push(v) assert(n < maxn, "buffer overflow") push(v) end function h:pop(i, box) assert(n > 0, "buffer underflow") local v = get(i or 1, box) pop(i or 1) return v end function h:peek(i, box) return get(i or 1, box) end function h:replace(i, v) assert(i >= 1 and i <= n, "invalid index") t[i] = v rebalance(i) end h.length = length return h end -- value heap working over a Lua table function heap.valueheap(h) h = h or {} local t, n = h, #h local function add(v) n = n + 1; t[n] = v end local function rem() t[n] = nil; n = n - 1 end local function swap(i, j) t[i], t[j] = t[j], t[i] end local function length() return n end local cmp = h.cmp and function(i, j) return h.cmp(t[i], t[j]) end or function(i, j) return t[i] < t[j] end local push, pop, rebalance = heap._make(add, rem, swap, length, cmp) local function get(i) assert(i >= 1 and i <= n, "invalid index") return t[i] end function h:push(v) assert(v ~= nil, "invalid value") push(v) end function h:pop(i) assert(n > 0, "buffer underflow") local v = get(i or 1) pop(i or 1) return v end function h:peek(i) return get(i or 1) end function h:replace(i, v) assert(i >= 1 and i <= n, "invalid index") t[i] = v rebalance(i) end h.length = length return h end -- return module: heap return heap
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/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 -- -- load modules local object = require("base/object") -- define module local list = list or object { _init = {"_length"} } {0} -- clear list function list:clear() self._length = 0 self._first = nil self._last = nil end -- insert item after the given item function list:insert(t, after) if not after then return self:insert_last(t) end assert(t ~= after) if after._next then after._next._prev = t t._next = after._next else self._last = t end t._prev = after after._next = t self._length = self._length + 1 end -- insert the first item in head function list:insert_first(t) if self._first then self._first._prev = t t._next = self._first self._first = t else self._first = t self._last = t end self._length = self._length + 1 end -- insert the last item in tail function list:insert_last(t) if self._last then self._last._next = t t._prev = self._last self._last = t else self._first = t self._last = t end self._length = self._length + 1 end -- remove item function list:remove(t) if t._next then if t._prev then t._next._prev = t._prev t._prev._next = t._next else assert(t == self._first) t._next._prev = nil self._first = t._next end elseif t._prev then assert(t == self._last) t._prev._next = nil self._last = t._prev else assert(t == self._first and t == self._last) self._first = nil self._last = nil end t._next = nil t._prev = nil self._length = self._length - 1 return t end -- remove the first item function list:remove_first() if not self._first then return end local t = self._first if t._next then t._next._prev = nil self._first = t._next t._next = nil else self._first = nil self._last = nil end self._length = self._length - 1 return t end -- remove last item function list:remove_last() if not self._last then return end local t = self._last if t._prev then t._prev._next = nil self._last = t._prev t._prev = nil else self._first = nil self._last = nil end self._length = self._length - 1 return t end -- push item to tail function list:push(t) self:insert_last(t) end -- pop item from tail function list:pop() self:remove_last() end -- shift item: 1 2 3 <- 2 3 function list:shift() self:remove_first() end -- unshift item: 1 2 -> t 1 2 function list:unshift(t) self:insert_first(t) end -- get first item function list:first() return self._first end -- get last item function list:last() return self._last end -- get next item function list:next(last) if last then return last._next else return self._first end end -- get the previous item function list:prev(last) if last then return last._prev else return self._last end end -- get list size function list:size() return self._length end -- is empty? function list:empty() return self:size() == 0 end -- get items -- -- e.g. -- -- for item in list:items() do -- print(item) -- end -- function list:items() local iter = function (list, item) return list:next(item) end return iter, self, nil end -- get reverse items function list:ritems() local iter = function (list, item) return list:prev(item) end return iter, self, nil end -- new list function list.new() return list() end -- return module: list return list
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/graph.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 graph.lua -- -- load modules local table = require("base/table") local object = require("base/object") -- define module local graph = graph or object { _init = {"_directed"} } {true} local edge = edge or object { _init = {"_from", "_to", "_weight"} } -- new edge, from -> to function edge.new(from, to, weight) return edge {from, to, weight or 1.0} end function edge:from() return self._from end function edge:to() return self._to end function edge:other(v) if v == self._from then return self._to else return self._from end end function edge:weight() return self._weight end -- clear graph function graph:clear() self._vertices = {} self._edges = {} self._adjacent_edges = {} end -- is empty? function graph:empty() return #self:vertices() == 0 end -- is directed? function graph:is_directed() return self._directed end -- get vertices function graph:vertices() return self._vertices end -- get adjacent edges of the the given vertex function graph:adjacent_edges(v) return self._adjacent_edges[v] end -- get the vertex at the given index function graph:vertex(idx) return self:vertices()[idx] end -- has the given vertex? function graph:has_vertex(v) return table.contains(self:vertices(), v) end -- remove the given vertex? function graph:remove_vertex(v) local contains = false table.remove_if(self._vertices, function (_, item) if item == v then contains = true return true end end) if contains then self._adjacent_edges[v] = nil -- remove the adjacent edge with this vertex in the other vertices if not self:is_directed() then for _, w in ipairs(self:vertices()) do local edges = self:adjacent_edges(w) if edges then table.remove_if(edges, function (_, e) return e:other(w) == v end) end end end end end -- topological sort function graph:topological_sort() local visited = {} for _, v in ipairs(self:vertices()) do visited[v] = false end local order_vertices = {} local function dfs(v) visited[v] = true local edges = self:adjacent_edges(v) if edges then for _, e in ipairs(edges) do local w = e:other(v) if not visited[w] then dfs(w) end end end table.insert(order_vertices, v) end for _, v in ipairs(self:vertices()) do if not visited[v] then dfs(v) end end return table.reverse(order_vertices) end -- find cycle function graph:find_cycle() local visited = {} local stack = {} local cycle = {} local function dfs(v) visited[v] = true stack[v] = true table.insert(cycle, v) local edges = self:adjacent_edges(v) if edges then for _, e in ipairs(edges) do local w = e:other(v) if not visited[w] then if dfs(w) then return true elseif stack[w] then return true end elseif stack[w] then for i = #cycle, 1, -1 do if cycle[i] == w then cycle = table.slice(cycle, i) return true end end end end end table.remove(cycle) stack[v] = false return false end for _, v in ipairs(self:vertices()) do if not visited[v] then if dfs(v) then return cycle end end end end -- get edges function graph:edges() return self._edges end -- add edge function graph:add_edge(from, to, weight) local e = edge.new(from, to, weight) if not self:has_vertex(from) then table.insert(self._vertices, from) self._adjacent_edges[from] = {} end if not self:has_vertex(to) then table.insert(self._vertices, to) self._adjacent_edges[to] = {} end if self:is_directed() then table.insert(self._adjacent_edges[e:from()], e) else table.insert(self._adjacent_edges[e:from()], e) table.insert(self._adjacent_edges[e:to()], e) end table.insert(self._edges, e) end -- has the given edge? function graph:has_edge(from, to) local edges = self:adjacent_edges(from) if edges then for _, e in ipairs(edges) do if e:to() == to then return true end end end return false end -- clone graph function graph:clone() local gh = graph.new(self:is_directed()) for _, v in ipairs(self:vertices()) do local edges = self:adjacent_edges(v) if edges then for _, e in ipairs(edges) do gh:add_edge(e:from(), e:to(), e:weight()) end end end return gh end -- reverse graph function graph:reverse() if not self:is_directed() then return self:clone() end local gh = graph.new(self:is_directed()) for _, v in ipairs(self:vertices()) do local edges = self:adjacent_edges(v) if edges then for _, e in ipairs(edges) do gh:add_edge(e:to(), e:from(), e:weight()) end end end return gh end -- dump graph function graph:dump() local vertices = self:vertices() local edges = self:edges() print(string.format("graph: %s, vertices: %d, edges: %d", self:is_directed() and "directed" or "not-directed", #vertices, #edges)) print("vertices: ") for _, v in ipairs(vertices) do print(string.format(" %s", v)) end print("") print("edges: ") for _, e in ipairs(edges) do print(string.format(" %s -> %s", e:from(), e:to())) end end -- new graph function graph.new(directed) local gh = graph {directed} gh:clear() return gh end -- return module: graph return graph
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/semver.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 semver.lua -- -- define module: semver local semver = semver or {} local _instance = _instance or {} -- load modules local os = require("base/os") local string = require("base/string") -- get the version info function _instance:get(name) local value = self._INFO[name] if value ~= nil then return value end end -- get the major version, e.g. v{major}.{minor}.{patch} function _instance:major() return self:get("major") end -- get the minor version function _instance:minor() return self:get("minor") end -- get the patch version function _instance:patch() return self:get("patch") end -- get the build version, e.g. v1.0.1+{build} function _instance:build() return self:get("build") end -- get the prerelease version, e.g. v1.0.1-{prerelease} function _instance:prerelease() return self:get("prerelease") end -- get the raw version string function _instance:rawstr() return self:get("raw") end -- get the short version string function _instance:shortstr() local str = self:major() if self:minor() then str = str .. "." .. self:minor() end if self:patch() then str = str .. "." .. self:patch() end return str end -- satisfies the given semantic version(e.g. '> 1.0 < 2.0', '~1.5')? function _instance:satisfies(version) return semver.satisfies(self:rawstr(), version) end -- is in the given version range, [version1, version2]? function _instance:at(version1, version2) return self:ge(version1) and self:le(version2) end -- add string compatible interface, string.sub function _instance:sub(...) return self:rawstr():sub(...) end -- add string compatible interface, string.gsub function _instance:gsub(...) return self:rawstr():gsub(...) end -- add string compatible interface, string.split function _instance:split(...) return self:rawstr():split(...) end -- add string compatible interface, string.startswith function _instance:startswith(...) return self:rawstr():startswith(...) end -- add string compatible interface, string.endswith function _instance:endswith(...) return self:rawstr():endswith(...) end -- v1 == v2 (str/ver)? function _instance:eq(version) if type(version) == "string" then return semver.compare(self:rawstr(), version) == 0 elseif type(version) == "table" then return semver.compare(self:rawstr(), version:rawstr()) == 0 end end -- v1 < v2 (str/ver)? function _instance:lt(version) if type(version) == "string" then return semver.compare(self:rawstr(), version) < 0 elseif type(version) == "table" then return semver.compare(self:rawstr(), version:rawstr()) < 0 end end -- v1 <= v2 (str/ver)? function _instance:le(version) if type(version) == "string" then return semver.compare(self:rawstr(), version) <= 0 elseif type(version) == "table" then return semver.compare(self:rawstr(), version:rawstr()) <= 0 end end -- v1 > v2 (str/ver)? function _instance:gt(version) return not self:le(version) end -- v1 >= v2 (str/ver)? function _instance:ge(version) return not self:lt(version) end -- v1 == v2? function _instance:__eq(version) if type(self) == "string" then return version:eq(self) else return self:eq(version) end end -- v1 < v2? function _instance:__lt(version) if type(self) == "string" then return version:gt(self) else return self:lt(version) end end -- v1 <= v2? function _instance:__le(version) if type(self) == "string" then return version:ge(self) else return self:le(version) end end -- get the raw version string function _instance:__tostring() return self:rawstr() end -- add string compatible interface, e.g. version .. str function _instance.__concat(op1, op2) if type(op1) == "string" then return op1 .. op2:rawstr() elseif type(op2) == "string" then return op1:rawstr() .. op2 else return op1:rawstr() .. op2:rawstr() end end -- new an instance function semver.new(version) -- parse version first local info, errors = semver.parse(version) if not info then return nil, errors end -- new an instance local instance = table.inherit(_instance) instance._INFO = info return instance end -- try to match valid version from string function semver.match(str, pos, pattern) local patterns = pattern or {"%d+[.]%d+[-+.%w]*", "%d+[.]%d+[.]%d+", "%d+[.]%d+"} for _, pattern in ipairs(table.wrap(patterns)) do local version_str = str:match(pattern, pos) if version_str then local info = semver.parse(version_str) if info then local instance = table.inherit(_instance) instance._INFO = info return instance end end end end -- return module: semver return semver
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/tty.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 tty.lua -- -- define module local tty = tty or {} -- load modules local io = require("base/io") -- save metatable and builtin functions tty._term_mode = tty._term_mode or tty.term_mode -- @see https://www2.ccs.neu.edu/research/gpc/VonaUtils/vona/terminal/vtansi.htm -- http://www.termsys.demon.co.uk/vtansi.htm -- write control characters function tty._iowrite(...) local isatty = tty._ISATTY if isatty == nil then isatty = io.isatty() tty._ISATTY = isatty end if isatty then io.write(...) end end -- get colorterm setting -- -- COLORTERM: 8color/color8, 256color/color256, truecolor, nocolor -- function tty._colorterm() local colorterm = tty._COLORTERM if colorterm == nil then colorterm = os.getenv("XMAKE_COLORTERM") or os.getenv("COLORTERM") or "" tty._COLORTERM = colorterm end return colorterm end -- erases from the current cursor position to the end of the current line. function tty.erase_line_to_end() if tty.has_vtansi() then tty._iowrite("\x1b[K") end return tty end -- erases from the current cursor position to the start of the current line. function tty.erase_line_to_start() if tty.has_vtansi() then tty._iowrite("\x1b[1K") end return tty end -- erases the entire current line function tty.erase_line() if tty.has_vtansi() then tty._iowrite("\x1b[2K") end return tty end -- erases the screen from the current line down to the bottom of the screen. function tty.erase_down() if tty.has_vtansi() then tty._iowrite("\x1b[J") end return tty end -- erases the screen from the current line up to the top of the screen. function tty.erase_up() if tty.has_vtansi() then tty._iowrite("\x1b[1J") end return tty end -- erases the screen with the background colour and moves the cursor to home. function tty.erase_screen() if tty.has_vtansi() then tty._iowrite("\x1b[2J") end return tty end -- save current cursor position. function tty.cursor_save() if tty.has_vtansi() then tty._iowrite("\x1b[s") end return tty end -- restores cursor position after a save cursor. function tty.cursor_restore() if tty.has_vtansi() then tty._iowrite("\x1b[u") end return tty end -- save current cursor position and color attrs function tty.cursor_and_attrs_save() if tty.has_vtansi() then tty._iowrite("\x1b7") end return tty end -- restores cursor position and color attrs after a save cursor. function tty.cursor_and_attrs_restore() if tty.has_vtansi() then tty._iowrite("\x1b8") end return tty end -- carriage return function tty.cr() tty._iowrite("\r") return tty end -- flush control function tty.flush() if io.isatty() then io.flush() end return tty end -- get shell name function tty.shell() local shell = tty._SHELL if shell == nil then local subhost = xmake._SUBHOST if subhost == "windows" then if os.getenv("PROMPT") then shell = "cmd" else local ok, result = os.iorun("pwsh -v") if ok then shell = "pwsh" else shell = "powershell" end end else shell = os.getenv("XMAKE_SHELL") if not shell then shell = os.getenv("SHELL") if shell then for _, shellname in ipairs({"zsh", "bash", "sh"}) do if shell:find(shellname) then shell = shellname break end end end end end tty._SHELL = shell or "sh" end return tty._SHELL end -- get terminal name -- - xterm -- - cmd -- - vstudio (in visual studio) -- - vscode (in vscode) -- - msys2 -- - cygwin -- - pwsh -- - powershell -- - mintty -- - windows-terminal -- - gnome-terminal -- - xfce4-terminal -- - konsole -- - terminator -- - rxvt -- - lxterminal -- - unknown -- function tty.term() local term = tty._TERM if term == nil then -- get term from $TERM_PROGRAM if term == nil then local TERM_PROGRAM = os.getenv("TERM_PROGRAM") if TERM_PROGRAM ~= nil then if TERM_PROGRAM:find("vscode", 1, true) then term = "vscode" elseif TERM_PROGRAM == "mintty" then term = "mintty" -- git bash end end end -- get term from $TERM if term == nil then local TERM = os.getenv("TERM") if TERM ~= nil then if TERM:find("xterm", 1, true) then term = "xterm" elseif TERM == "cygwin" then term = "cygwin" end end end -- get term from system if term == nil then local subhost = xmake._SUBHOST if subhost == "windows" then if os.getenv("XMAKE_IN_VSTUDIO") then term = "vstudio" elseif os.getenv("WT_SESSION") then term = "windows-terminal" else term = tty.shell() end elseif subhost == "msys" then term = "msys2" elseif subhost == "cygwin" then term = "cygwin" elseif subhost == "macosx" then term = "xterm" end end tty._TERM = term or "unknown" end return tty._TERM end -- has emoji? function tty.has_emoji() local has_emoji = tty._HAS_EMOJI if has_emoji == nil then local term = tty.term() local winos = require("base/winos") -- before win8? disable it if has_emoji == nil and (os.host() == "windows" and winos.version():le("win8")) then has_emoji = false end -- on msys2/cygwin/powershell? disable it if has_emoji == nil and (term == "msys2" or term == "cygwin" or term == "powershell") then has_emoji = false end -- enable it by default if has_emoji == nil then has_emoji = true end tty._HAS_EMOJI = has_emoji or false end return has_emoji end -- has vtansi? function tty.has_vtansi() return tty.has_color8() end -- has 8 colors? function tty.has_color8() local has_color8 = tty._HAS_COLOR8 if has_color8 == nil then -- detect it from $COLORTERM if has_color8 == nil then local colorterm = tty._colorterm() if colorterm == "nocolor" then has_color8 = false elseif colorterm and colorterm:find("8color", 1, true) then has_color8 = true elseif tty.has_color256() or tty.has_color24() then has_color8 = true end end -- detect it from $TERM local term = tty.term() if has_color8 == nil then if term == "vstudio" then has_color8 = false elseif term == "xterm" or term == "mintty" then has_color8 = true end end -- detect it from system if has_color8 == nil then if os.host() == "windows" then local winos = require("base/winos") if os.getenv("ANSICON") then has_color8 = true elseif winos.version():le("win8") then has_color8 = false else has_color8 = true end else -- alway enabled for unix-like system has_color8 = true end end tty._HAS_COLOR8 = has_color8 or false end return has_color8 end -- has 256 colors? function tty.has_color256() local has_color256 = tty._HAS_COLOR256 if has_color256 == nil then -- detect it from $COLORTERM if has_color256 == nil then local colorterm = tty._colorterm() if colorterm == "nocolor" then has_color256 = false elseif colorterm and (colorterm:find("256color", 1, true) or colorterm:find("color256", 1, true)) then has_color256 = true elseif tty.has_color24() then has_color256 = true end end -- detect it from $TERM local term = tty.term() local term_env = os.getenv("TERM") if has_color256 == nil then if term == "vstudio" then has_color256 = false elseif term_env and (term_env:find("256color", 1, true) or term_env:find("color256", 1, true)) then has_color256 = true end end -- detect it from system if has_color256 == nil then if os.host() == "windows" then has_color256 = false elseif os.host() == "linux" or os.host("macosx") then -- alway enabled for linux/macOS, $TERM maybe xterm, not xterm-256color, but it is supported has_color256 = true else has_color256 = false end end tty._HAS_COLOR256 = has_color256 or false end return has_color256 end -- has 24bits true color? -- -- There's no reliable way, and ncurses/terminfo's maintainer expressed he has no intent on introducing support. -- S-Lang author added a check for $COLORTERM containing either "truecolor" or "24bit" (case sensitive). -- In turn, VTE, Konsole and iTerm2 set this variable to "truecolor" (it's been there in VTE for a while, -- it's relatively new and maybe still git-only in Konsole and iTerm2). -- -- This is obviously not a reliable method, and is not forwarded via sudo, ssh etc. However, whenever it errs, -- it errs on the safe side: does not advertise support whereas it's actually supported. -- App developers can freely choose to check for this same variable, or introduce their own method -- (e.g. an option in their config file), whichever matches better the overall design of the given app. -- Checking $COLORTERM is recommended though, since that would lead to a more unique desktop experience -- where the user has to set one variable only and it takes effect across all the apps, rather than something -- separately for each app. -- function tty.has_color24() local has_color24 = tty._HAS_COLOR24 if has_color24 == nil then -- detect it from $COLORTERM if has_color24 == nil then local colorterm = tty._colorterm() if colorterm == "nocolor" then has_color24 = false elseif colorterm and (colorterm:find("truecolor", 1, true) or colorterm:find("24bit", 1, true)) then has_color24 = true end end -- detect it from $TERM local term = tty.term() local term_env = os.getenv("TERM") if has_color256 == nil then if term == "vstudio" then has_color256 = false elseif term_env and (term_env:find("truecolor", 1, true) or term_env:find("24bit", 1, true)) then has_color256 = true end end tty._HAS_COLOR24 = has_color24 or false end return has_color24 end -- get term mode, e.g. stdin, stdout, stderr -- -- local oldmode = tty.term_mode(stdtype) -- local oldmode = tty.term_mode(stdtype, newmode) -- function tty.term_mode(stdtype, newmode) local oldmode = 0 if tty._term_mode then if stdtype == "stdin" then oldmode = tty._term_mode(1, newmode) elseif stdtype == "stdout" then oldmode = tty._term_mode(2, newmode) elseif stdtype == "stderr" then oldmode = tty._term_mode(3, newmode) end end return oldmode end -- return module return tty
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/privilege.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 TitanSnow -- @file privilege.lua -- -- define module local privilege = privilege or {} -- load modules local os = require("base/os") -- store privilege function privilege.store() -- check if root if not os.isroot() then return false end local owner = {} -- sudo will set SUDO_UID & SUDO_GID -- so that can easily get original uid & gid local sudo_uid = os.getenv("SUDO_UID") local sudo_gid = os.getenv("SUDO_GID") if sudo_uid and sudo_gid then owner.uid = sudo_uid owner.gid = sudo_gid else -- find projectdir's owner local projectdir = xmake._PROJECT_DIR assert(projectdir) owner = os.getown(projectdir) if not owner then -- fallback to current dir owner = os.getown(os.curdir()) if not owner then return false end end end -- set gid if os.gid(owner.gid).errno ~= 0 then return false end -- set uid if os.uid({ruid = owner.uid}).errno ~= 0 or os.uid({euid = owner.uid}).errno ~= 0 then return false end -- set flag privilege._HAS_PRIVILEGE = true -- ok return true end -- check if has stored privilege function privilege.has() return privilege._HAS_PRIVILEGE or false end function privilege.get() -- has? if privilege._HAS_PRIVILEGE ~= true then return false end -- set uid if os.uid({euid = 0}).errno ~= 0 or os.uid({ruid = 0}).errno ~= 0 then return false end -- set gid if os.gid(0).errno ~= 0 then return false end return true end -- return module return privilege
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/hashset.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 hashset.lua -- -- define module local hashset = hashset or {} local hashset_impl = hashset.__index or {} -- load modules local table = require("base/table") local todisplay = require("base/todisplay") -- representaion for nil key hashset._NIL = setmetatable({}, { __todisplay = function() return "${reset}${color.dump.keyword}nil${reset}" end, __tostring = function() return "symbol(nil)" end }) function hashset:__todisplay() return string.format("hashset${reset}(%s) {%s}", todisplay(self._SIZE), table.concat(table.imap(table.keys(self._DATA), function (i, k) if i > 10 then return nil elseif i == 10 and self._SIZE ~= 10 then return "..." else return todisplay(k) end end), ", ")) end function hashset._to_key(key) if key == nil then key = hashset._NIL end return key end -- make a new hashset function hashset.new() return setmetatable({ _DATA = {}, _SIZE = 0 }, hashset) end -- construct from list of items function hashset.of(...) local result = hashset.new() local data = table.pack(...) for i = 1, data.n do result:insert(data[i]) end return result end -- construct from an array function hashset.from(array) assert(array) return hashset.of(table.unpack(array)) end -- check value is in hashset function hashset_impl:has(value) value = hashset._to_key(value) return self._DATA[value] or false end -- insert value to hashset, returns false if value has already in the hashset function hashset_impl:insert(value) value = hashset._to_key(value) local result = not (self._DATA[value] or false) if result then self._DATA[value] = true self._SIZE = self._SIZE + 1 end return result end -- remove value from hashset, returns false if value is not in the hashset function hashset_impl:remove(value) value = hashset._to_key(value) local result = self._DATA[value] or false if result then self._DATA[value] = nil self._SIZE = self._SIZE - 1 end return result end -- convert hashset to an array, nil in the set will be ignored function hashset_impl:to_array() local result = {} for k, _ in pairs(self._DATA) do if k ~= hashset._NIL then table.insert(result, k) end end return result end -- iterate keys of hashtable -- -- @code -- for _, key in instance:keys() do -- ... -- end -- @endcode -- function hashset_impl:keys() return function (t, key) local k, _ = next(t._DATA, key) if k == hashset._NIL then return k, nil else return k, k end end, self, nil end -- order keys iterator -- -- @code -- for _, key in instance:orderkeys() do -- ... -- end -- @endcode -- function hashset_impl:orderkeys() local orderkeys = table.keys(self._DATA) table.sort(orderkeys, function (a, b) if a == hashset._NIL then a = math.inf end if b == hashset._NIL then b = math.inf end if type(a) == "table" then a = tostring(a) end if type(b) == "table" then b = tostring(b) end return a < b end) local i = 1 return function (t, k) k = orderkeys[i] i = i + 1 if k == hashset._NIL then return k, nil else return k, k end end, self, nil end -- get size of hashset function hashset_impl:size() return self._SIZE end -- is empty? function hashset_impl:empty() return self:size() == 0 end -- get data of hashset function hashset_impl:data() return self._DATA end -- clear hashset function hashset_impl:clear() self._DATA = {} self._SIZE = 0 end -- return module hashset.__index = hashset_impl return hashset
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/option.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 option.lua -- -- define module: option local option = {} -- load modules local cli = require("base/cli") local table = require("base/table") local tty = require("base/tty") local colors = require("base/colors") local text = require("base/text") -- translate the menu function option._translate(menu) -- translate the menus if exists function local submenus_all = {} for k, submenu in pairs(menu) do if type(submenu) == "function" then local ok, _submenus_or_errors = pcall(submenu) if ok and _submenus_or_errors then for k, m in pairs(_submenus_or_errors) do submenus_all[k] = m end else return false, (_submenus_or_errors or "translate option menu failed!") end else submenus_all[k] = submenu end end table.copy2(menu, submenus_all) -- save menu option._MENU = menu -- ok return true end function option._modenarrow() -- show menu in narrow mode? local width = os.getwinsize().width return width > 0 and width < 60 end -- get the top context function option._context() local contexts = option._CONTEXTS if contexts then return contexts[#contexts] end end -- save context function option.save(taskname) option._CONTEXTS = option._CONTEXTS or {} local context = {options = {}, defaults = {}, taskname = taskname} if taskname then context.defaults = option.defaults(taskname) or context.defaults end table.insert(option._CONTEXTS, context) return context end -- restore context function option.restore() if option._CONTEXTS then table.remove(option._CONTEXTS) end end -- the command line function option.cmdline() if not xmake._ARGS then xmake._ARGS = os.args(xmake._ARGV) end return "xmake " .. xmake._ARGS end -- init the option function option.init(menu) -- check assert(menu) -- translate menu local ok, errors = option._translate(menu) if not ok then return false, errors end -- the main menu local main = option.taskmenu("main") assert(main) -- new top context local context = option.save() assert(context) -- check command if xmake._COMMAND then -- find the current task and save it for taskname, taskinfo in pairs(main.tasks) do if taskname == xmake._COMMAND or taskinfo.shortname == xmake._COMMAND then context.taskname = taskname break end end -- not found? if not context.taskname or not menu[context.taskname] then option.show_main() return false, "invalid task: " .. xmake._COMMAND end end local options = table.wrap(option.taskmenu().options) -- parse remain parts local results, err = option.parse(xmake._COMMAND_ARGV, options, { populate_defaults = false }) if not results then option.show_menu(context.taskname) return false, err end -- finish parsing context.options = results -- init the default value option.populate_defaults(options, context.defaults) -- ok return true end -- parse arguments with the given options function option.parse(argv, options, opt) -- check assert(argv and options) opt = opt or { populate_defaults = true } -- parse arguments local results = {} local flags = {} for _, o in ipairs(options) do -- get mode and name local mode = o[3] local name = o[2] assert(o and ((mode ~= "v" and mode ~= "vs") or name)) -- fill short flags if o[3] == "k" and o[1] then table.insert(flags, o[1]) end end -- run parser local pargs = cli.parsev(argv, flags) -- save parse results for i, arg in ipairs(pargs) do if arg.type == "option" or arg.type == "flag" then -- find option or flag local name_idx = arg.short and 1 or 2 local match_opt = nil for _, o in pairs(options) do local name = o[name_idx] if name == arg.key then match_opt = o break end end -- save option if match_opt and ((arg.type == "option" and match_opt[3] ~= "k") or (arg.type == "flag" and match_opt[3] == "k")) then results[match_opt[2] or match_opt[1]] = option.boolean(arg.value) else if opt.allow_unknown then results[arg.key] = option.boolean(arg.value) else return nil, string.format("Invalid %s: %s", arg.type, arg) end end elseif arg.type == "arg" then -- find a value option with name local match_opt = nil for _, o in ipairs(options) do -- get mode and name local mode = o[3] local name = o[2] -- is value and with name? if mode == "v" and name and not results[name] then match_opt = o break -- is values and with name? elseif mode == "vs" and name then match_opt = o break end end -- ok? save this value with name opt[2] if match_opt then -- get mode and name local mode = match_opt[3] local name = match_opt[2] -- save value if mode == "v" then results[name] = arg.value elseif mode == "vs" then -- the option local o = results[name] if not o then results[name] = {} o = results[name] end -- append value table.insert(o, arg.value) end else -- failed if opt.allow_unknown then if arg.key then results[arg.key] = arg.value else -- the option local o = results["$ARGS"] if not o then results["$ARGS"] = {} o = results["$ARGS"] end -- append value table.insert(o, arg.value) end else return nil, "invalid argument: " .. arg.value end end end end -- init the default value if opt.populate_defaults then option.populate_defaults(options, results) end -- ok return results end -- fill defined with option's default value, in place function option.populate_defaults(options, defined) -- check assert(options and defined) -- populate the default value for _, o in ipairs(options) do -- the long name local longname = o[2] -- key=value? if o[3] == "kv" then local shortname = o[1] -- the key local key = longname or shortname assert(key) -- move value to key if needed if shortname and defined[shortname] ~= nil then defined[key], defined[shortname] = defined[shortname], nil end -- save the default value if defined[key] == nil then defined[key] = o[4] end -- value with name? elseif o[3] == "v" and longname then -- save the default value if defined[longname] == nil then defined[longname] = o[4] end end end end -- get the current task name function option.taskname() return option._context().taskname end -- get the task menu function option.taskmenu(task) -- check assert(option._MENU) -- the current task task = task or option.taskname() or "main" -- get the task menu local taskmenu = option._MENU[task] if type(taskmenu) == "function" then -- load this task menu taskmenu = taskmenu() -- save this task menu option._MENU[task] = taskmenu end -- get it return taskmenu end -- get the given option value for the current task function option.get(name) -- check assert(name) -- the options local options = option.options() if options then local value = options[name] if value == nil then value = option.default(name) end return value end end -- set the given option for the current task function option.set(name, value) -- check assert(name) -- cannot be the first context for menu assert(#option._CONTEXTS > 1) -- the options local options = option.options() assert(options) -- set it options[name] = value end -- get the boolean value function option.boolean(value) if type(value) == "string" then local v = value:lower() if v == "true" or v == "yes" or v == "y" then value = true elseif v == "false" or v == "no" or v == "n" then value = false end end return value end -- get the given default option value for the current task function option.default(name) assert(name) -- the defaults local defaults = option.defaults() assert(defaults) -- get it return defaults[name] end -- get the current options function option.options() -- get it local context = option._context() if context then return context.options end end -- get all default options for the current or given task function option.defaults(task) -- get the default options for the current task if task == nil then return option._context().defaults end -- the task menu local taskmenu = option.taskmenu(task) -- get the default options for the given task local defaults = {} if taskmenu then option.populate_defaults(taskmenu.options, defaults) end return defaults end -- show update tips function option.show_update_tips() -- show latest version local versionfile = path.join(os.tmpdir(), "latest_version") if os.isfile(versionfile) then local versioninfo = io.load(versionfile) if versioninfo and versioninfo.version and semver.compare(versioninfo.version, xmake._VERSION_SHORT) > 0 then local updatetips = nil if os.host() == "windows" then updatetips = string.format([[ ========================================================================== | ${bright yellow}A new version of xmake is available!${clear} | | | | To update to the latest version ${bright}%s${clear}, run "xmake update". | ========================================================================== ]], versioninfo.version) else updatetips = string.format([[ ╔════════════════════════════════════════════════════════════════════════════╗ ║ ${bright yellow}A new version of xmake is available!${clear} ║ ║ ║ ║ To update to the latest version ${bright}%s${clear}, run "xmake update". ║ ╚════════════════════════════════════════════════════════════════════════════╝ ]], versioninfo.version) end io.print(colors.translate(updatetips)) end end end -- show logo function option.show_logo(logo, opt) -- define logo logo = logo or [[ _ __ ___ __ __ __ _| | ______ \ \/ / | \/ |/ _ | |/ / __ \ > < | \__/ | /_| | < ___/ /_/\_\_|_| |_|\__ \|_|\_\____| by ruki, xmake.io ]] -- make rainbow for logo opt = opt or {} if tty.has_color24() or tty.has_color256() then local lines = {} local seed = opt.seed or 236 for _, line in ipairs(logo:split("\n")) do local i = 0 local line2 = "" line:gsub(".", function (c) local code = tty.has_color24() and colors.rainbow24(i, seed) or colors.rainbow256(i, seed) line2 = string.format("%s${bright %s}%s", line2, code, c) i = i + 1 end) table.insert(lines, line2) end logo = table.concat(lines, "\n") end -- show logo io.print(colors.translate(logo)) -- define footer local footer = [[ ${point_right} ${bright}Manual${clear}: ${underline}https://xmake.io/#/getting_started${clear} ${pray} ${bright}Donate${clear}: ${underline}https://xmake.io/#/sponsor${clear} ]] -- show footer io.print(colors.translate(footer)) -- show update tips option.show_update_tips() end -- show the menu function option.show_menu(task) -- no task? print main menu if not task then option.show_main() return end -- the menu local menu = option._MENU assert(menu) -- the task menu local taskmenu = option.taskmenu(task) assert(taskmenu) -- print title if menu.title then io.print(colors.translate(menu.title)) end -- print copyright if menu.copyright then io.print(colors.translate(menu.copyright)) end -- show logo option.show_logo() -- print usage if taskmenu.usage then io.print("") io.print(colors.translate("${bright}Usage: $${default color.menu.usage}" .. taskmenu.usage .. "${clear}")) end -- print description if taskmenu.description then io.print("") io.print(colors.translate(taskmenu.description)) end -- print options if taskmenu.options then option.show_options(taskmenu.options, task) end end -- show the main menu function option.show_main() -- the menu local menu = option._MENU assert(menu) -- the main menu local main = option.taskmenu("main") assert(main) -- print title if menu.title then io.print(colors.translate(menu.title)) end -- print copyright if menu.copyright then io.print(colors.translate(menu.copyright)) end -- show logo option.show_logo() -- print usage if main.usage then io.print("") io.print(colors.translate("${bright}Usage: $${default color.menu.usage}" .. main.usage .. "${clear}")) end -- print description if main.description then io.print("") io.print(colors.translate(main.description)) end -- print tasks if main.tasks then local narrow = option._modenarrow() -- make task categories local categories = {} for taskname, taskinfo in pairs(main.tasks) do -- the category name local categoryname = taskinfo.category or "task" if categoryname == "main" then categoryname = "action" end -- the category task local category = categories[categoryname] or { name = categoryname, tasks = {} } categories[categoryname] = category -- add task to the category category.tasks[taskname] = taskinfo end -- sort categories categories = table.values(categories) table.sort(categories, function (a, b) if a.name == "action" then return true end return a.name < b.name end) -- dump tasks by categories local tablecontent = {} for _, category in ipairs(categories) do -- the category name and task assert(category.name and category.tasks) -- print category name table.insert(tablecontent, {}) table.insert(tablecontent, {{string.format("%s%ss: ", string.sub(category.name, 1, 1):upper(), string.sub(category.name, 2)), style="${reset bright}"}}) -- print tasks for taskname, taskinfo in table.orderpairs(category.tasks) do -- init the task line local taskline = string.format(narrow and " %s%s" or " %s%s", taskinfo.shortname and (taskinfo.shortname .. ", ") or " ", taskname) table.insert(tablecontent, {taskline, colors.translate(taskinfo.description or "")}) end 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 -- print options if main.options then option.show_options(main.options, "build") end end -- show the options menu function option.show_options(options, taskname) assert(options) -- remove repeat empty lines local is_action = false local emptyline_count = 0 local printed_options = {} for _, opt in ipairs(options) do if opt.category and printed_options[#printed_options].category then table.remove(printed_options) end table.insert(printed_options, opt) if opt.category and opt.category == "action" then is_action = true end end if printed_options[#printed_options].category then table.remove(printed_options) end -- narrow mode? local narrow = option._modenarrow() -- print header local tablecontent = {} table.insert(tablecontent, {}) if is_action then table.insert(tablecontent, {{"Common options:", style="${reset bright}"}}) else table.insert(tablecontent, {{"Options:", style="${reset bright}"}}) end -- print options local categories = {} for _, opt in ipairs(printed_options) do if opt.category and opt.category == "action" then -- the following options are belong action? show command section -- -- @see core/base/task.lua: translate menu -- table.insert(tablecontent, {}) table.insert(tablecontent, {{"Command options (" .. taskname .. "):", style="${reset bright}"}}) elseif opt.category and opt.category ~= "." then local category_root = opt.category:split("/")[1] if not categories[category_root] then table.insert(tablecontent, {}) table.insert(tablecontent, {{"Command options (" .. opt.category .. "):", style="${reset bright}"}}) categories[category_root] = true end elseif opt[3] == nil then table.insert(tablecontent, {}) else -- append the shortname local shortname = opt[1] local name = opt[2] local mode = opt[3] local default = opt[4] local title1, title2 local kvplaceholder = mode == "kv" and ((type(default) == "boolean") and "[y|n]" or(name and name:upper() or "XXX")) if shortname then if mode == "kv" then title1 = "-" .. shortname .. " " .. kvplaceholder else title1 = "-" .. shortname end end -- append the name if name then local leading = mode:startswith("k") and "--" or " " local kv if mode == "k" then kv = name elseif mode == "kv" then kv = name .. "=" .. kvplaceholder elseif mode == "vs" then kv = name .. " ..." else kv = name end title2 = leading .. kv elseif mode == "v" or mode == "vs" then title2 = " ..." end -- get description local optdespn = table.maxn(opt) local description = table.move(opt, 5, optdespn, 1, table.new(optdespn - 5 + 1, 0)) if #description == 0 then description[1] = "" end -- transform description local desp_strs = table.new(#description, 0) for _, v in ipairs(description) do if type(v) == "function" then v = v() end if type(v) == "string" then table.insert(desp_strs, colors.translate(v)) elseif type(v) == "table" then table.move(v, 1, #v, #desp_strs + 1, desp_strs) end end -- append the default value if default then local defaultval = tostring(default) if type(default) == "boolean" then defaultval = default and "y" or "n" end local def_desp = colors.translate(string.format(" (default: ${bright}%s${clear})", defaultval)) desp_strs[1] = desp_strs[1] .. def_desp end -- append values local values = opt.values if type(values) == "function" then values = values(false, {helpmenu = true}) end if values then for _, value in ipairs(table.wrap(values)) do table.insert(desp_strs, " - " .. tostring(value)) end end -- insert row if narrow then if title1 then table.insert(tablecontent, {{" " .. title1, " " .. title2 }, desp_strs}) else table.insert(tablecontent, {{" " .. title2 }, desp_strs}) end else if title1 then table.insert(tablecontent, {" " .. title1 .. ", " .. title2 , desp_strs}) else table.insert(tablecontent, {" " .. title2 , desp_strs}) end end end end -- set table styles tablecontent.style = {"${color.menu.option.name}"} tablecontent.width = {nil, "auto"} tablecontent.sep = narrow and " " or " " -- print table io.write(text.table(tablecontent)) end -- return module: option return option
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/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 path.lua -- -- define module: path local path = path or {} -- load modules local string = require("base/string") local table = require("base/table") local _instance = _instance or {} -- save original interfaces path._absolute = path._absolute or path.absolute path._relative = path._relative or path.relative path._translate = path._translate or path.translate -- new a path function _instance.new(p, transform) local instance = table.inherit(_instance) instance._RAWSTR = p instance._TRANSFORM = transform setmetatable(instance, _instance) table.wrap_lock(instance) instance:_update() return instance end -- update path string function _instance:_update() local transform = self._TRANSFORM if transform then self._STR = transform(self:rawstr()) else self._STR = self:rawstr() end end function _instance:str() return self._STR end function _instance:rawstr() return self._RAWSTR end function _instance:set(p) self._RAWSTR = tostring(p) self:_update() return self end function _instance:empty() local str = self._STR return str == nil or #str == 0 end function _instance:transform_set(transform) self._TRANSFORM = transform self:_update() return self end function _instance:clone() return path.new(self:rawstr(), self._TRANSFORM) end function _instance:normalize() return path.new(path.normalize(self:str()), self._TRANSFORM) end function _instance:translate(opt) return path.new(path.translate(self:str(), opt), self._TRANSFORM) end function _instance:unix() return path.new(path.unix(self:str()), self._TRANSFORM) end function _instance:filename() return path.filename(self:str()) end function _instance:basename() return path.basename(self:str()) end function _instance:extension() return path.extension(self:str()) end function _instance:directory() return path.new(path.directory(self:str()), self._TRANSFORM) end function _instance:absolute(rootdir) return path.new(path.absolute(self:str(), rootdir), self._TRANSFORM) end function _instance:relative(rootdir) return path.new(path.relative(self:str(), rootdir), self._TRANSFORM) end function _instance:join(...) local items = {self:str()} for _, item in ipairs(table.pack(...)) do table.insert(items, tostring(item)) end return path.new(path.join(table.unpack(items)), self._TRANSFORM) end function _instance:split() return path.split(self:str()) end function _instance:splitenv() return path.splitenv(self:str()) end -- concat two paths function _instance:__concat(other) if path.instance_of(self) then return path.new(path.join(self:str(), tostring(other)), self._TRANSFORM) elseif type(self) == "string" then return path.new(tostring(other), function (p) return self .. p end) else os.raise("cannot concat %s/%s", tostring(self), type(self)) end end -- tostring(path) function _instance:__tostring() return not self:empty() and self:str() or "" end -- todisplay(path) function _instance:__todisplay() return "<path: " .. (self:empty() and "empty" or self:str()) .. ">" end -- get unix-style path, it is usually used on windows -- @see https://github.com/xmake-io/xmake/issues/4731 function path.unix(p) return (tostring(p):gsub(path.sep(), "/")) end -- get cygwin-style path, e.g. c:\, C:\ -> /c/ function path.cygwin(p) return (tostring(p):gsub("^(%w):", function (drive) return "/" .. drive:lower() end):gsub("\\", "/")) end -- translate path -- -- @param p the path -- @param opt the option, e.g. {normalize = true} -- function path.translate(p, opt) return path._translate(tostring(p), opt) end -- path.translate: -- - transform the path separator -- - expand the user directory with the prefix: ~ -- - remove tail separator -- - reduce the repeat path separator, "////" => "/" -- -- path.normalize: -- - reduce "././" => "." -- - reduce "/xxx/.." => "/" -- function path.normalize(p) return path.translate(tostring(p), {normalize = true}) end -- get the directory of the path, compatible with lower version core binary if not path.directory then function path.directory(p, sep) p = tostring(p) local i = 0 if sep then -- if the path has been normalized, we can quickly find it with a unique path separator prompt i = p:lastof(sep, true) or 0 else i = math.max(p:lastof('/', true) or 0, p:lastof('\\', true) or 0) end if i > 0 then if i > 1 then i = i - 1 end return p:sub(1, i) else return "." end end end -- get absolute path function path.absolute(p, rootdir) if rootdir then rootdir = tostring(rootdir) end return path._absolute(tostring(p), rootdir) end -- get relative path function path.relative(p, rootdir) if rootdir then rootdir = tostring(rootdir) end return path._relative(tostring(p), rootdir) end -- get the filename of the path function path.filename(p, sep) p = tostring(p) local i = 0 if sep then -- if the path has been normalized, we can quickly find it with a unique path separator prompt i = p:lastof(sep, true) or 0 else i = math.max(p:lastof('/', true) or 0, p:lastof('\\', true) or 0) end if i > 0 then return p:sub(i + 1) else return p end end -- get the basename of the path function path.basename(p) p = tostring(p) local name = path.filename(p) local i = name:lastof(".", true) if i then return name:sub(1, i - 1) else return name end end -- get the file extension of the path: .xxx function path.extension(p, level) p = tostring(p) local i = p:lastof(".", true) if i then local ext = p:sub(i) if ext:find("[/\\]") then return "" end if level and level > 1 then return path.extension(p:sub(1, i - 1), level - 1) .. ext end return ext else return "" end end -- join path function path.join(p, ...) p = tostring(p) return path.translate(p .. path.sep() .. table.concat({...}, path.sep())) end -- split path by the separator function path.split(p) p = tostring(p) return p:split("[/\\]") end -- get the path seperator function path.sep() local sep = path._SEP if not sep then sep = xmake._FEATURES.path_sep path._SEP = sep end return sep end -- get the path seperator of environment variable function path.envsep() local envsep = path._ENVSEP if not envsep then envsep = xmake._FEATURES.path_envsep path._ENVSEP = envsep end return envsep end -- split environment variable with `path.envsep()`, -- also handles more speical cases such as posix flags and windows quoted paths function path.splitenv(env_path) local result = {} if xmake._HOST == "windows" then while #env_path > 0 do if env_path:startswith(path.envsep()) then env_path = env_path:sub(2) elseif env_path:startswith('"') then -- path quoted with, can contain `;` local p_end = env_path:find('"' .. path.envsep(), 2, true) or env_path:find('"$', 2) or (#env_path + 1) table.insert(result, env_path:sub(2, p_end - 1)) env_path = env_path:sub(p_end + 1) else local p_end = env_path:find(path.envsep(), 2, true) or (#env_path + 1) table.insert(result, env_path:sub(1, p_end - 1)) env_path = env_path:sub(p_end) end end else -- see https://git.kernel.org/pub/scm/utils/dash/dash.git/tree/src/exec.c?h=v0.5.9.1&id=afe0e0152e4dc12d84be3c02d6d62b0456d68580#n173 -- no escape sequences, so `:` and `%` is invalid in environment variable for _, v in ipairs(env_path:split(path.envsep(), { plain = true })) do -- flag for shells, style `<path>%<flag>` local flag = v:find("%", 1, true) if flag then v = v:sub(1, flag - 1) end if #v > 0 then table.insert(result, v) end end end return result end -- concat environment variable with `path.envsep()`, -- also handles more speical cases such as posix flags and windows quoted paths function path.joinenv(paths, envsep) if not paths or #paths == 0 then return "" end envsep = envsep or path.envsep() if xmake._HOST == "windows" then local tab = {} for _, v in ipairs(paths) do if v ~= "" then if v:find(envsep, 1, true) then v = '"' .. v .. '"' end table.insert(tab, v) end end return table.concat(tab, envsep) else return table.concat(paths, envsep) end end -- the last character is the path seperator? function path.islastsep(p) p = tostring(p) local sep = p:sub(#p, #p) return xmake._HOST == "windows" and (sep == '\\' or sep == '/') or (sep == '/') end -- convert path pattern to a lua pattern function path.pattern(pattern) -- translate wildcards, e.g. *, ** pattern = pattern:gsub("([%+%.%-%^%$%(%)%%])", "%%%1") pattern = pattern:gsub("%*%*", "\001") pattern = pattern:gsub("%*", "\002") pattern = pattern:gsub("\001", ".*") if path.sep() == '\\' then pattern = pattern:gsub("\002", "[^/\\]*") else pattern = pattern:gsub("\002", "[^/]*") end -- case-insensitive filesystem? if not os.fscase() then pattern = string.ipattern(pattern, true) end return pattern end -- get cygwin-style path on msys2/cygwin, e.g. "c:\xxx" -> "/c/xxx" function path.cygwin_path(p) p = tostring(p) p = p:gsub("\\", "/") local pos = p:find(":/") if pos == 2 then return "/" .. p:sub(1, 1) .. p:sub(3) end return p end -- new a path instance function path.new(p, transform) return _instance.new(p, transform) end -- is path instance? function path.instance_of(p) return type(p) == "table" and p.normalize and p._RAWSTR end -- register call function -- -- local p = path("/tmp/a") -- local p = path("/tmp/a", function (p) return "--key=" .. p end) setmetatable(path, { __call = function (_, ...) return path.new(...) end, }) -- return module: path return path
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/text.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 text.lua -- -- define module local text = text or {} -- load modules local string = require("base/string") local colors = require("base/colors") local math = require("base/math") local table = require("base/table") function text._iswbr(ch) if not text._CHARWBR then text._CHARWBR = { [(' '):byte()] = 100, [('\n'):byte()] = 100, [('\t'):byte()] = 100, [('\v'):byte()] = 100, [('\f'):byte()] = 100, [('\r'):byte()] = 100, [('-'):byte()] = 90, [(')'):byte()] = 50, [(']'):byte()] = 50, [('}'):byte()] = 50, [(','):byte()] = 50, [('='):byte()] = 40, [('|'):byte()] = 40, } end return text._CHARWBR[ch] or false end function text._charwidth(ch) if ch == 0x09 then -- TAB return 4 elseif ch == 0x08 then -- BS return -1 elseif ch <= 0x1F or ch == 0x7F then -- other control chars return 0 else return 1 end end function text._nextwbr(self, iter) local ptr = iter.pos + 1 local width = iter.width local str = self.str local e = self.j if ptr > e then return nil end while ptr <= e do local byte = str:byte(ptr) -- ansi sequence, skip it if byte == 27 and ptr + 2 <= e and str:byte(ptr + 1) == 91 then local ansiend = false ptr = ptr + 2 while ptr <= e do local b = str:byte(ptr) if b == 109 then ansiend = true break end ptr = ptr + 1 end if not ansiend then -- ansi sequence not finished in [i, j], no more wbr in the range return nil end else width = width + text._charwidth(byte) local wbr = text._iswbr(byte) if wbr then return { pos = ptr, width = width, quality = wbr } end end ptr = ptr + 1 end -- wbr at end of string return { pos = e, width = width, quality = 100 } end function text._iterwbr(str, i, j, wordbreak) if not i then i = 1 elseif i < 0 then i = #str + 1 + i end if not j then j = #str elseif j < 0 then j = #str + 1 + j end return text._nextwbr, { str = str, i = i, j = j, wordbreak = wordbreak }, { pos = i - 1, width = 0 } end -- @see https://unicode.org/reports/tr14/ function text._lastwbr(str, width, wordbreak) -- check assert(#str >= width) if wordbreak == "breakall" then -- To prevent overflow, word may be broken at any character return width else if (text._iswbr(str:byte(width + 1)) or -1) >= 100 then -- exact break return width end local wbr_candidate for wbr in text._iterwbr(str, 1, #str, wordbreak) do if not wbr_candidate then -- not candidate yet? always use a wbr wbr_candidate = wbr elseif (wbr.quality >= wbr_candidate.quality or wbr.quality >= 80) and wbr.width <= width then -- in range, replace with a higher quality wbr wbr_candidate = wbr end if wbr.width > width then break end end if wbr_candidate then return wbr_candidate.pos end -- not found in all str return #str end end -- break lines function text.wordwrap(str, width, opt) opt = opt or {} -- split to lines if type(str) == "table" then str = table.concat(str, "\n") end local lines = tostring(str):split("\n", {plain = true, strict = true}) local result = table.new(#lines, 0) local actual_width = 0 -- handle lines for _, v in ipairs(lines) do -- remove tailing spaces, include "\r", which will be produced by `("l1\r\nl2"):split(...)` v = v:rtrim() while #v > width do -- find word break chance local wbr = text._lastwbr(v, width, opt.wordbreak) -- break line local line = v:sub(1, wbr):rtrim() actual_width = math.max(#line, actual_width) table.insert(result, line) v = v:sub(wbr + 1):ltrim() -- prevent empty line if #v == 0 then v = nil break end end -- put remaining parts if v then actual_width = math.max(#v, actual_width) table.insert(result, v) end end -- ok return result, actual_width end function text._format_cell(cell, width, opt) local result = table.new(#cell, 0) local max_width = 0 for _, v in ipairs(cell) do local lines, aw = text.wordwrap(tostring(v), width[2], opt) table.move(lines, 1, #lines, #result + 1, result) max_width = math.max(max_width, aw) end cell.formatted = result cell.width = max_width end function text._format_col(col, width, opt) local max_width = 0 for i = 1, table.maxn(col) do local v = col[i] -- skip span cells if v and not v.span then text._format_cell(v, width, opt) max_width = math.max(max_width, v.width) end end col.width = max_width end -- make a table with colors -- -- @param data table data, array of array of cells with optional styles -- eg: { -- {"1", nil, "3"}, -- use nil to make previous cell to span next column -- {"4", "5", {"line1", "line2", style="${yellow}", align = "r"}}, -- multi-line content & set style or align for cell -- {"7", "8", {"9", style="${reset}${red}"}, style="${bright}", align = "c"}, -- set style or align for row -- style = {"${underline}"}, -- set style for columns -- -- or use "${underline}" for all columns -- width = { 20, {10, 50}, "auto"}, -- -- 2 numbers - min and max width (nil for not set, eg: {nil, 50}); -- -- a number - width, num is equivalent to {num, num}; -- -- nil - no limit, equivalent to {nil, nil} -- -- "auto" - use remain space of console, only one "auto" column is allowed -- align = {"l", "r", "c"} -- align mode for each column, "left", "center" or "right" -- -- or use a string for the whole table -- sep = "${dim} | ", -- table colunm sepertor, default is " | ", use "" to hide -- } -- priority of style and align: cell > row > col -- @param opt options for color rendering and word wrapping function text.table(data, opt) assert(data) -- init options opt = opt or { ignore_unknown = true } data.sep = data.sep or " | " opt.patch_reset = false -- col ordered cells local cols = table.new(1, 0) local n_row = table.maxn(data) local n_col = 1 -- count cols for i = 1, n_row do local row = data[i] if row == nil then data[i] = {{""}} else n_col = math.max(n_col, table.maxn(row)) end end -- reorder for i = 1, n_row do local row = data[i] local p_cell = nil for j = 1, n_col do local cell = row[j] if cell ~= nil and type(cell) ~= "table" then -- wrap cells if needed cell = {tostring(cell)} elseif cell == nil and j == 1 then cell = {""} end local col = cols[j] if not col then col = table.new(n_row, 0) cols[j] = col end if cell then col[i] = cell p_cell = cell else p_cell.span = (p_cell.span or 1) + 1 end end end -- load column options data.width = data.width or table.new(n_col, 0) data.align = data.align or table.new(n_col, 0) data.style = data.style or table.new(n_col, 0) local style = "" if type(data.style) == "string" then style = data.style data.style = table.new(n_col, 0) data.sep = style .. data.sep .. "${reset}" end local align = "l" if type(data.align) == "string" then align = data.align data.align = table.new(n_col, 0) end local sep = colors.translate(data.sep, opt) local sep_len = #colors.ignore(data.sep, opt) -- index of auto col local auto_col = nil for i = 1, n_col do -- load width local w = data.width[i] if w ~= "auto" then local wl, wu if w == nil then wl, wu = 0, math.huge elseif type(w) == "number" then if math.isnan(w) or math.isinf(w) then wl, wu = 0, math.huge else wl, wu = w, w end else wl, wu = w[1], w[2] end wl = wl or 0 wu = wu or math.huge data.width[i] = {wl, wu} else assert(not auto_col, "Only one 'auto' colunm is allowed.") auto_col = i end -- load align cols[i].align = (data.align[i] or align):sub(1, 1):lower() -- load style cols[i].style = data.style[i] or style end -- format table -- 1. format non-auto cols for i, col in ipairs(cols) do if i ~= auto_col then text._format_col(col, data.width[i], opt) end end if auto_col then -- 2. caculate auto col width local auto_width = os.getwinsize().width for i = 1, n_col do if i ~= auto_col then auto_width = auto_width - cols[i].width end end auto_width = math.max(0, auto_width - sep_len * (n_col - 1)) data.width[auto_col] = {0,auto_width} -- 3. format auto col text._format_col(cols[auto_col], data.width[auto_col], opt) end -- 4. format span cell for i, col in ipairs(cols) do for j = 1, n_row do local cell = col[j] if cell and cell.span then local w, wl = 0, 0 for ci = 0, (cell.span - 1) do -- actual width of spanned cols w = w + cols[i + ci].width -- min width of spanned cols wl = wl + data.width[i + ci][1] end text._format_cell(cell, {0, math.max(w, wl) + sep_len * (cell.span - 1)}, opt) end end end -- render cells -- row ordered cells local rows = table.new(n_row, 0) -- reorder for i = 1, n_row do local d_row = data[i] or {} local row = table.new(n_col, 0) local line = 1 for j = 1, n_col do local cell = cols[j][i] if cell then assert(cell.formatted) line = math.max(#cell.formatted, line) end row[j] = cell end row.line = line -- load align if d_row.align then row.align = d_row.align:sub(1, 1):lower() end -- load style row.style = d_row.style or "" rows[i] = row end local results = table.new(n_row, 0) local reset = colors.translate("${reset}", opt) for i, row in ipairs(rows) do for l = 1, row.line do local cells = table.new(n_col, 0) local j = 1 while j <= n_col do local cell = row[j] assert(cell) local col = cols[j] if l == 1 then cell.align = cell.align or row.align or col.align cell.style = colors.translate((col.style or "") .. (row.style or "") .. (cell.style or ""), opt) end local str = cell.formatted[l] or "" local width = col.width local span = cell.span or 1 if cell.span then for ci = (j + 1), (j + span - 1) do width = width + cols[ci].width end width = width + sep_len * (span - 1) end local padded if cell.align == "r" then -- right align padded = string.rep(" ", width - #str) .. str elseif cell.align == "c" then -- centered local padding = width - #str local lp = math.floor(padding / 2) local rp = math.ceil(padding / 2) padded = string.rep(" ", lp) .. str .. string.rep(" ", rp) else --left align, emit tailing spaces for last colunm padded = str .. ((j + span == n_col + 1) and "" or string.rep(" ", width - #str)) end table.insert(cells, cell.style .. padded .. reset) j = j + span end table.insert(results, table.concat(cells, sep)) end end -- concat rendered rows results[#results + 1] = "" return table.concat(results, "\n") end -- return module return text
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/deprecated.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 deprecated.lua -- -- define module local deprecated = deprecated or {} -- add deprecated entry function deprecated.add(newformat, oldformat, ...) local utils = require("base/utils") local old = string.format(oldformat, ...) local new = newformat and string.format(newformat, ...) or false if new then utils.warning("%s is deprecated, please uses %s instead of it", old, new) else utils.warning("%s is deprecated, please remove it", old) end end -- return module return deprecated
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/debugger.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 debugger.lua -- -- define module local debugger = {} -- load modules local os = require("base/os") local path = require("base/path") -- start emmylua debugger -- -- e.g. -- -- xrepo env -b emmylua_debugger xmake --version -- function debugger:_start_emmylua_debugger() local debugger_libfile = os.getenv("EMMYLUA_DEBUGGER") local script, errors = package.loadlib(debugger_libfile, "luaopen_emmy_core") if not script then return false, errors end local debugger_inst = script() if not debugger_inst then return false, "cannot get debugger module!" end debugger_inst.tcpListen("localhost", 9966) debugger_inst.waitIDE() debugger_inst.breakHere() return true end -- start debugging function debugger:start() if self:has_emmylua() then return self:_start_emmylua_debugger() end end -- has emmylua debugger? function debugger:has_emmylua() local debugger_libfile = os.getenv("EMMYLUA_DEBUGGER") if debugger_libfile and os.isfile(debugger_libfile) then return true end end -- debugger is enabled? function debugger:enabled() return self:has_emmylua() end -- return module return debugger
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/todisplay.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 todisplay.lua -- -- define module local todisplay = todisplay or {} -- load modules local colors = require("base/colors") local math = require("base/math") function todisplay._reset() local reset = todisplay._RESET if not reset then reset = colors.translate("${reset}") todisplay._RESET = reset end return reset end -- format string with theme colors function todisplay._format(fmtkey, fmtdefault, ...) local theme = colors.theme() if theme then return colors.translate(string.format(theme:get(fmtkey), ...), { patch_reset = false, ignore_unknown = true }) else return string.format(fmtdefault, ...) end end -- translate string with theme formats function todisplay._translate(str) local theme = colors.theme() if theme then return colors.translate(str, { patch_reset = false, ignore_unknown = true }) else return colors.ignore(str) end end -- print keyword function todisplay._print_keyword(keyword) return todisplay._translate("${reset}${color.dump.keyword}") .. tostring(keyword) .. todisplay._reset() end -- print string function todisplay._print_string(str, as_key) local quote = (not as_key) or (not str:match("^[a-zA-Z_][a-zA-Z0-9_]*$")) if quote then return todisplay._translate([[${reset}${color.dump.string_quote}"${reset}${color.dump.string}]]) .. str .. todisplay._translate([[${reset}${color.dump.string_quote}"${reset}]]) else return todisplay._translate("${reset}${color.dump.string}") .. str .. todisplay._reset() end end -- print number function todisplay._print_number(num) return todisplay._translate("${reset}${color.dump.number}") .. tostring(num) .. todisplay._reset() end -- print function function todisplay._print_function(func) local funcinfo = debug.getinfo(func) local srcinfo = funcinfo.short_src if funcinfo.linedefined >= 0 then srcinfo = srcinfo .. ":" .. funcinfo.linedefined end local funcname = funcinfo.name and (funcinfo.name .. " ") or "" return todisplay._translate("${reset}${color.dump.function}function ${bright}") .. funcname .. todisplay._translate("${reset}${dim}") .. srcinfo .. todisplay._reset() end function todisplay._get_tostr_method(value) local metatable = debug.getmetatable(value) if metatable then local __todisplay = rawget(metatable, "__todisplay") local __tostring = rawget(metatable, "__tostring") return __todisplay, __tostring end return nil, nil end -- print value with default format function todisplay._print_default_scalar(value, style, formatkey) local __todisplay, __tostring = todisplay._get_tostr_method(value) if __todisplay then local ok, str = pcall(__todisplay, value) if ok then value = todisplay._translate(str) -- disable format formatkey = nil end elseif __tostring then local ok, str = pcall(__tostring, value) if ok then value = str end end if formatkey then value = todisplay._format(formatkey, "%s", value) end local reset = todisplay._reset() return reset .. todisplay._translate(style) .. value .. reset end -- print udata value with scalar format function todisplay._print_udata_scalar(value) return todisplay._print_default_scalar(value, "${color.dump.udata}", "text.dump.udata_format") end -- print table value with scalar format function todisplay._print_table_scalar(value, expand) if debug.getmetatable(value) or not expand then return todisplay._print_default_scalar(value, "${color.dump.table}", "text.dump.table_format") end local pvalues = {} local has_string_key = false local as, ae = math.huge, -math.huge local k, v for i = 1, 10 do k, v = next(value, k) if k == nil then break end if type(k) == "string" then pvalues[k] = todisplay._print_scalar(v, false) has_string_key = true elseif type(k) == "number" and math.isint(k) then pvalues[k] = todisplay._print_scalar(v, false) as = math.min(k, as) ae = math.max(k, ae) else -- no common table or array return todisplay._print_default_scalar(value, "${color.dump.table}", "text.dump.table_format") end end if k ~= nil then -- to large return todisplay._print_default_scalar(value, "${color.dump.table}", "text.dump.table_format") end local results = {} local is_arr = as >= 1 and ae <= 20 if is_arr then local nilstr for i = 1, ae do local pv = pvalues[i] if pv == nil then if not nilstr then nilstr = todisplay._print_keyword("nil") end pv = nilstr end results[i] = pv end end if has_string_key then for pk, pv in pairs(pvalues) do if type(pk) == "string" then local pkstr = todisplay._print_string(pk, true) table.insert(results, pkstr .. " = " .. pv) elseif not is_arr then local pkstr = todisplay._print_number(pk) table.insert(results, pkstr .. " = " .. pv) end end end if #results == 0 then return todisplay._translate("${reset}${color.dump.table}") .. "{ }" .. todisplay._reset() end return todisplay._translate("${reset}${color.dump.table}") .. "{ " .. table.concat(results, ", ") .." }" .. todisplay._reset() end -- print scalar value function todisplay._print_scalar(value, expand) if type(value) == "nil" or type(value) == "boolean" then return todisplay._print_keyword(value) elseif type(value) == "number" then return todisplay._print_number(value) elseif type(value) == "string" then return todisplay._print_string(value) elseif type(value) == "function" then return todisplay._print_function(value) elseif type(value) == "userdata" then return todisplay._print_udata_scalar(value) elseif type(value) == "table" then return todisplay._print_table_scalar(value, expand) else return todisplay._print_default_scalar(value, "${color.dump.default}", "text.dump.default_format") end end function todisplay.print(value) return todisplay._print_scalar(value, true) end setmetatable(todisplay, { __call = function (_, ...) return todisplay.print(...) end }) return todisplay
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/interpreter.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 interpreter.lua -- -- define module: interpreter local interpreter = interpreter or {} -- load modules local os = require("base/os") local path = require("base/path") local table = require("base/table") local utils = require("base/utils") local string = require("base/string") local scopeinfo = require("base/scopeinfo") local deprecated = require("base/deprecated") local sandbox = require("sandbox/sandbox") -- raise without interpreter stack -- @see https://github.com/xmake-io/xmake/issues/3553 function interpreter._raise(errors) os.raise("[nobacktrace]: " .. (errors or "")) end -- traceback function interpreter._traceback(errors) -- disable backtrace? if errors then local _, pos = errors:find("[nobacktrace]: ", 1, true) if pos then return errors:sub(pos + 1) end end -- init results local results = "" if errors then results = errors .. "\n" end results = results .. "stack traceback:\n" -- make results local level = 2 while true do -- get debug info local info = debug.getinfo(level, "Sln") -- end? if not info then break end -- function? if info.what == "C" then results = results .. string.format(" [C]: in function '%s'\n", info.name) elseif info.name then results = results .. string.format(" [%s:%d]: in function '%s'\n", info.short_src, info.currentline, info.name) elseif info.what == "main" then results = results .. string.format(" [%s:%d]: in main chunk\n", info.short_src, info.currentline) break else results = results .. string.format(" [%s:%d]:\n", info.short_src, info.currentline) end -- next level = level + 1 end return results end -- merge the current root values to the previous scope function interpreter._merge_root_scope(root, root_prev, override) -- merge it root_prev = root_prev or {} for scope_kind_and_name, _ in pairs(root or {}) do -- only merge sub-scope for each kind("target@@xxxx") or __rootkind -- we need to ignore the sub-root scope e.g. target{} after fetching root scope -- if scope_kind_and_name:find("@@", 1, true) or scope_kind_and_name == "__rootkind" then local scope_values = root_prev[scope_kind_and_name] or {} local scope_root = root[scope_kind_and_name] or {} for name, values in pairs(scope_root) do if not name:startswith("__override_") then if scope_root["__override_" .. name] then if override or scope_values[name] == nil then scope_values[name] = values end else scope_values[name] = table.join(values, scope_values[name] or {}) end end end root_prev[scope_kind_and_name] = scope_values end end -- ok? return root_prev end -- fetch the root values to the child values in root scope -- and we will only use the child values if be override mode function interpreter._fetch_root_scope(root) -- fetch it for scope_kind_and_name, _ in pairs(root or {}) do -- is scope_kind@@scope_name? scope_kind_and_name = scope_kind_and_name:split("@@", {plain = true}) if #scope_kind_and_name == 2 then local scope_kind = scope_kind_and_name[1] local scope_name = scope_kind_and_name[2] local scope_values = root[scope_kind .. "@@" .. scope_name] or {} local scope_root = root[scope_kind] or {} for name, values in pairs(scope_root) do if not name:startswith("__override_") then if scope_root["__override_" .. name] then if scope_values[name] == nil then scope_values[name] = values scope_values["__override_" .. name] = true end else scope_values[name] = table.join(values, scope_values[name] or {}) end end end root[scope_kind .. "@@" .. scope_name] = scope_values end end end -- save api source info, e.g. call api() in sourcefile:linenumber function interpreter:_save_sourceinfo_to_scope(scope, apiname, values) -- save api source info, e.g. call api() in sourcefile:linenumber local sourceinfo = debug.getinfo(3, "Sl") if sourceinfo then scope["__sourceinfo_" .. apiname] = scope["__sourceinfo_" .. apiname] or {} local sourcescope = scope["__sourceinfo_" .. apiname] for _, value in ipairs(values) do if type(value) == "string" then sourcescope[value] = {file = sourceinfo.short_src or sourceinfo.source, line = sourceinfo.currentline} end end end end -- register scope end: scopename_end() function interpreter:_api_register_scope_end(...) assert(self and self._PUBLIC and self._PRIVATE) -- done for _, apiname in ipairs({...}) do -- check assert(apiname) -- register scope api self:api_register(nil, apiname .. "_end", function (self, ...) -- check assert(self and self._PRIVATE and apiname) -- the scopes local scopes = self._PRIVATE._SCOPES assert(scopes) -- enter root scope scopes._CURRENT = nil -- clear scope kind scopes._CURRENT_KIND = nil end) end end -- register scope api: xxx_apiname() function interpreter:_api_register_scope_api(scope_kind, action, apifunc, ...) assert(self and self._PUBLIC and self._PRIVATE) assert(apifunc) -- done for _, apiname in ipairs({...}) do -- check assert(apiname) -- the full name local fullname = apiname if action ~= nil then fullname = action .. "_" .. apiname end -- register scope api self:api_register(scope_kind, fullname, function (self, ...) -- check assert(self and self._PRIVATE and apiname) -- the scopes local scopes = self._PRIVATE._SCOPES assert(scopes) -- call function return apifunc(self, scopes, apiname, ...) end) end end -- register api: xxx_values() function interpreter:_api_register_xxx_values(scope_kind, action, apifunc, ...) assert(self and self._PUBLIC and self._PRIVATE) assert(action and apifunc) -- uses the root scope kind if no scope kind if not scope_kind then scope_kind = "__rootkind" end -- define implementation local implementation = function (self, scopes, apiname, ...) -- init root scopes scopes._ROOT = scopes._ROOT or {} -- init current root scope local root = scopes._ROOT[scope_kind] or {} scopes._ROOT[scope_kind] = root -- clear the current scope if be not belong to the current scope kind if scopes._CURRENT and scopes._CURRENT_KIND ~= scope_kind then os.raise("%s() cannot be called in %s(), please move it to the %s scope!", apiname, scopes._CURRENT_KIND, scope_kind == "__rootkind" and "root" or scope_kind) scopes._CURRENT = nil end -- the current scope local scope = scopes._CURRENT or root assert(scope) -- set values (set, on, before, after ...)? mark as "override" if apiname and (action ~= "add" and action ~= "del" and action ~= "remove") then scope["__override_" .. apiname] = true end -- save api source info, e.g. call api() in sourcefile:linenumber self:_save_sourceinfo_to_scope(scope, apiname, {...}) -- call function return apifunc(self, scope, apiname, ...) end -- register implementation self:_api_register_scope_api(scope_kind, action, implementation, ...) end -- register api for xxx_script function interpreter:_api_register_xxx_script(scope_kind, action, ...) -- define implementation local implementation = function (self, scope, name, ...) -- patch action to name if action ~= "on" then name = name .. "_" .. action end -- get arguments, pattern1, pattern2, ..., script function or name local args = {...} -- get and save extra config local extra_config = args[#args] if table.is_dictionary(extra_config) then table.remove(args) scope["__extra_" .. name] = extra_config end -- mark as override scope["__override_" .. name] = true -- get patterns local patterns = {} if #args > 1 then patterns = table.slice(args, 1, #args - 1) end -- get script function or name local script_func_or_name = args[#args] -- get script local script, errors = self:_script(script_func_or_name) if not script then if #patterns > 0 then os.raise("%s_%s(%s, %s): %s", action, name, table.concat(patterns, ', '), tostring(script_func_or_name), errors) else os.raise("%s_%s(%s): %s", action, name, tostring(script_func_or_name), errors) end end -- save script for all patterns if #patterns > 0 then local scripts = scope[name] or {} for _, pattern in ipairs(patterns) do -- check assert(type(pattern) == "string") -- convert pattern to a lua pattern ('*' => '.*') pattern = pattern:gsub("([%+%.%-%^%$%%])", "%%%1") pattern = pattern:gsub("%*", "\001") pattern = pattern:gsub("\001", ".*") -- save script if type(scripts) == "table" then scripts[pattern] = script elseif type(scripts) == "function" then scripts = {__generic__ = scripts} scripts[pattern] = script end end scope[name] = scripts else -- save the generic script local scripts = scope[name] if type(scripts) == "table" then scripts["__generic__"] = script else scripts = script end scope[name] = scripts end end -- register implementation self:_api_register_xxx_values(scope_kind, action, implementation, ...) end -- translate api paths function interpreter:_api_translate_paths(values, apiname, infolevel) local results = {} for _, p in ipairs(values) do if type(p) ~= "string" or #p == 0 then local sourceinfo = debug.getinfo(infolevel or 3, "Sl") interpreter._raise(string.format("%s(%s): invalid path value at %s:%d", apiname, tostring(p), sourceinfo.short_src or sourceinfo.source, sourceinfo.currentline)) end if not p:find("^%s-%$%(.-%)") and not path.is_absolute(p) then table.insert(results, path.relative(path.absolute(p, self:scriptdir()), self:rootdir())) else table.insert(results, p) end end return results end -- get api function within scope function interpreter:_api_within_scope(scope_kind, apiname) local priv = self._PRIVATE assert(priv) -- the scopes local scopes = priv._SCOPES assert(scopes) -- get scope api if scope_kind and priv._APIS then -- get api function local api_scope = priv._APIS[scope_kind] if api_scope then return api_scope[apiname] end end end -- set api function within scope function interpreter:_api_within_scope_set(scope_kind, apiname, apifunc) local priv = self._PRIVATE assert(priv) -- the scopes local scopes = priv._SCOPES assert(scopes) -- get scope api if scope_kind and priv._APIS then -- get api function local api_scope = priv._APIS[scope_kind] if api_scope then api_scope[apiname] = apifunc end end end -- clear results function interpreter:_clear() assert(self and self._PRIVATE) -- clear it self._PRIVATE._SCOPES = {} self._PRIVATE._MTIMES = {} end -- filter values function interpreter:_filter(values, level) assert(self and values ~= nil) -- return values directly if no filter local filter = self._PRIVATE._FILTER if filter == nil then return values end -- init level if level == nil then level = 0 end -- filter keyvalues if table.is_dictionary(values) then local results = {} for key, value in pairs(values) do key = (type(key) == "string" and filter:handle(key) or key) if type(value) == "string" then results[key] = filter:handle(value) elseif type(value) == "table" and level < 1 then results[key] = self:_filter(value, level + 1) -- only filter 2 levels for table values else results[key] = value end values = results end else -- filter value or arrays values = table.wrap(values) for idx = 1, #values do local value = values[idx] if type(value) == "string" then value = filter:handle(value) elseif table.is_array(value) then for i = 1, #value do local v = value[i] if type(v) == "string" then v = filter:handle(v) elseif type(v) == "table" and level < 1 then v = self:_filter(v, level + 1) end value[i] = v end end values[idx] = value end end return values end -- handle scope data function interpreter:_handle(scope, deduplicate, enable_filter) assert(scope) -- remove repeat values and unwrap it local results = {} for name, values in pairs(scope) do -- filter values -- -- @note we need to do filter before removing repeat values -- https://github.com/xmake-io/xmake/issues/1732 if enable_filter then values = self:_filter(values) end -- remove repeat first for each slice with removed item (__remove_xxx) if deduplicate and not table.is_dictionary(values) then local policy = self:deduplication_policy(name) if policy ~= false then local unique_func = policy == "toleft" and table.reverse_unique or table.unique values = unique_func(values, function (v) return type(v) == "string" and v:startswith("__remove_") end) end end -- unwrap it if be only one values = table.unwrap(values) -- update it results[name] = values end return results end -- make results function interpreter:_make(scope_kind, deduplicate, enable_filter) assert(self and self._PRIVATE) -- the scopes local scopes = self._PRIVATE._SCOPES -- empty scope? if not scopes or not scopes._ROOT then os.raise("the scope %s() is empty!", scope_kind) end -- get the root scope info of the given scope kind, e.g. root.target local results = {} local scope_opt = {interpreter = self, deduplicate = deduplicate, enable_filter = enable_filter} if scope_kind and scope_kind:startswith("root.") then local root_scope = scopes._ROOT[scope_kind:sub(6)] if root_scope then results = self:_handle(root_scope, deduplicate, enable_filter) end return scopeinfo.new(scope_kind, results, scope_opt) -- get the root scope info without scope kind elseif scope_kind == "root" or scope_kind == nil then local root_scope = scopes._ROOT["__rootkind"] if root_scope then results = self:_handle(root_scope, deduplicate, enable_filter) end return scopeinfo.new(scope_kind, results, scope_opt) -- get the results of the given scope kind elseif scope_kind then -- not this scope for kind? local scope_for_kind = scopes[scope_kind] if scope_for_kind then -- fetch the root values in root scope first interpreter._fetch_root_scope(scopes._ROOT) -- merge results for scope_name, scope in pairs(scope_for_kind) do -- add scope values local scope_values = {} for name, values in pairs(scope) do if not name:startswith("__override_") then scope_values[name] = values end end -- merge root values with the given scope name local scope_root = scopes._ROOT[scope_kind .. "@@" .. scope_name] if scope_root then for name, values in pairs(scope_root) do if not scope["__override_" .. name] then scope_values[name] = table.join(values, scope_values[name] or {}) end end end -- add this scope results[scope_name] = scopeinfo.new(scope_kind, self:_handle(scope_values, deduplicate, enable_filter), scope_opt) end end end return results end -- load script function interpreter:_script(script) -- this script is module name? import it first if type(script) == "string" then -- import module as script local modulename = script script = function (...) -- import it _g._module = _g._module or import(modulename, {anonymous = true}) return _g._module(...) end end -- make sandbox instance with the given script local instance, errors = sandbox.new(script, self:filter(), self:scriptdir()) if not instance then return nil, errors end -- get sandbox script return instance:script() end -- get builtin modules function interpreter.builtin_modules() local builtin_modules = interpreter._BUILTIN_MODULES if builtin_modules == nil then builtin_modules = {} local builtin_module_files = os.match(path.join(os.programdir(), "core/sandbox/modules/interpreter/*.lua")) if builtin_module_files then for _, builtin_module_file in ipairs(builtin_module_files) do local module_name = path.basename(builtin_module_file) assert(module_name) local script, errors = loadfile(builtin_module_file) if script then local ok, results = utils.trycall(script) if not ok then os.raise(results) end builtin_modules[module_name] = results else os.raise(errors) end end end interpreter._BUILTIN_MODULES = builtin_modules end return builtin_modules end -- new an interpreter instance function interpreter.new() -- init an interpreter instance local instance = { _PUBLIC = {} , _PRIVATE = { _SCOPES = {} , _MTIMES = {} , _SCRIPT_FILES = {} , _FILTER = require("base/filter").new()}} -- inherit the interfaces of interpreter table.inherit2(instance, interpreter) -- dispatch the api calling for scope setmetatable(instance._PUBLIC, { __index = function (tbl, key) -- get interpreter instance if type(key) == "string" and key == "_INTERPRETER" and rawget(tbl, "_INTERPRETER_READABLE") then return instance end -- get the scope kind local priv = instance._PRIVATE local current_kind = priv._SCOPES._CURRENT_KIND local scope_kind = current_kind or priv._ROOTSCOPE -- get the api function from the given scope local apifunc = instance:_api_within_scope(scope_kind, key) -- get the api function from the root scope if not apifunc and priv._ROOTAPIS then apifunc = priv._ROOTAPIS[key] end -- ok? return apifunc end , __newindex = function (tbl, key, val) if type(key) == "string" and (key == "_INTERPRETER" or key == "_INTERPRETER_READABLE") then return end rawset(tbl, key, val) end}) -- register the builtin interfaces instance:api_register(nil, "includes", interpreter.api_builtin_includes) instance:api_register(nil, "add_subdirs", interpreter.api_builtin_add_subdirs) instance:api_register(nil, "add_subfiles", interpreter.api_builtin_add_subfiles) instance:api_register(nil, "set_xmakever", interpreter.api_builtin_set_xmakever) -- register the interpreter interfaces instance:api_register(nil, "interp_save_scope", interpreter.api_interp_save_scope) instance:api_register(nil, "interp_restore_scope", interpreter.api_interp_restore_scope) instance:api_register(nil, "interp_get_scopekind", interpreter.api_interp_get_scopekind) instance:api_register(nil, "interp_get_scopename", interpreter.api_interp_get_scopename) instance:api_register(nil, "interp_add_scopeapis", interpreter.api_interp_add_scopeapis) -- register the builtin modules for module_name, module in pairs(interpreter.builtin_modules()) do instance:api_register_builtin(module_name, module) end -- ok? return instance end -- load script file, e.g. xmake.lua -- -- @param opt {on_load_data = function (data) return data end} -- function interpreter:load(file, opt) assert(self and self._PUBLIC and self._PRIVATE and file) -- load the script opt = opt or {} local script, errors = loadfile(file, "bt", {on_load = opt.on_load_data}) if not script then return nil, errors end -- clear first self:_clear() -- translate to absolute file path for scriptdir/rootdir file = path.absolute(file) -- init the current file self._PRIVATE._CURFILE = file self._PRIVATE._SCRIPT_FILES = {file} -- init the root directory self._PRIVATE._ROOTDIR = path.directory(file) assert(self._PRIVATE._ROOTDIR) -- init mtime for the current file self._PRIVATE._MTIMES[path.relative(file, self._PRIVATE._ROOTDIR)] = os.mtime(file) -- bind public scope setfenv(script, self._PUBLIC) -- do interpreter return xpcall(script, interpreter._traceback) end -- make results function interpreter:make(scope_kind, deduplicate, enable_filter) -- get the results with the given scope self._PENDING = true local ok, results = xpcall(interpreter._make, interpreter._traceback, self, scope_kind, deduplicate, enable_filter) self._PENDING = false if not ok then return nil, results end return results end -- is pending? function interpreter:pending() return self._PENDING end -- get all loaded script files (xmake.lua) function interpreter:scriptfiles() assert(self and self._PRIVATE) return self._PRIVATE._SCRIPT_FILES end -- get mtimes function interpreter:mtimes() assert(self and self._PRIVATE) return self._PRIVATE._MTIMES end -- get filter function interpreter:filter() assert(self and self._PRIVATE) return self._PRIVATE._FILTER end -- get root directory function interpreter:rootdir() assert(self and self._PRIVATE) return self._PRIVATE._ROOTDIR end -- set root directory function interpreter:rootdir_set(rootdir) assert(self and self._PRIVATE and rootdir) self._PRIVATE._ROOTDIR = rootdir end -- get script directory function interpreter:scriptdir() assert(self and self._PRIVATE and self._PRIVATE._CURFILE) return path.directory(self._PRIVATE._CURFILE) end -- set root scope kind -- -- the root api will affect these scopes -- function interpreter:rootscope_set(scope_kind) assert(self and self._PRIVATE) self._PRIVATE._ROOTSCOPE = scope_kind end -- get the deduplication policy function interpreter:deduplication_policy(name) local policies = self._PRIVATE._DEDUPLICATION_POLICIES if name then return policies and policies[name] else return policies end end -- set the deduplication policy -- -- we need to be able to precisely control the direction of deduplication of different types of values. -- the default is to de-duplicate from left to right, but like links/syslinks need to be de-duplicated from right to left. -- -- e.g -- -- interp:deduplication_set("defines", "right") -- remove duplicates to the right (default) -- interp:deduplication_set("links", "left") -- remove duplicates to the left -- interp:deduplication_set("links", false) -- disable deduplication -- -- @see https://github.com/xmake-io/xmake/issues/1903 -- function interpreter:deduplication_policy_set(name, policy) self._PRIVATE._DEDUPLICATION_POLICIES = self._PRIVATE._DEDUPLICATION_POLICIES or {} self._PRIVATE._DEDUPLICATION_POLICIES[name] = policy end -- get apis function interpreter:apis(scope_kind) assert(self and self._PRIVATE) -- get apis from the given scope kind if scope_kind and scope_kind ~= "__rootkind" then local apis = self._PRIVATE._APIS return apis and apis[scope_kind] or {} else return self._PRIVATE._ROOTAPIS or {} end end -- get api definitions function interpreter:api_definitions() return self._API_DEFINITIONS end -- register api -- -- interp:api_register(nil, "apiroot", function () end) -- interp:api_register("scope_kind", "apiname", function () end) -- -- result: -- -- _PRIVATE -- { -- _APIS -- { -- scope_kind -- { -- apiname = function () end -- } -- } -- -- _ROOTAPIS -- { -- apiroot = function () end -- } -- } -- function interpreter:api_register(scope_kind, name, func) assert(self and self._PUBLIC and self._PRIVATE) assert(name and func) -- register api to the given scope kind if scope_kind and scope_kind ~= "__rootkind" then -- get apis self._PRIVATE._APIS = self._PRIVATE._APIS or {} local apis = self._PRIVATE._APIS -- get scope apis[scope_kind] = apis[scope_kind] or {} local scope = apis[scope_kind] -- register api scope[name] = function (...) return func(self, ...) end else -- get root apis self._PRIVATE._ROOTAPIS = self._PRIVATE._ROOTAPIS or {} local apis = self._PRIVATE._ROOTAPIS -- register api to the root scope apis[name] = function (...) return func(self, ...) end end end -- register api for builtin function interpreter:api_register_builtin(name, func) assert(self and self._PUBLIC and func) self._PUBLIC[name] = func end -- register api for scope() -- -- interp:api_register_scope("scope_kind1", "scope_kind2") -- -- api: -- set_$(scope_kind1)("scope_name1") -- ... -- -- set_$(scope_kind2)("scope_name1", "scope_name2") -- ... -- -- result: -- -- _PRIVATE -- { -- _SCOPES -- { -- scope_kind1 -- { -- "scope_name1" -- { -- -- } -- } -- -- scope_kind2 -- { -- "scope_name1" -- { -- -- } -- -- "scope_name2" <-- _SCOPES._CURRENT -- { -- __scriptdir = "" (the directory of xmake.lua) -- } -- } -- } -- } -- function interpreter:api_register_scope(...) -- define implementation local implementation = function (self, scopes, scope_kind, ...) local scope_args = table.pack(...) local scope_name = scope_args[1] local scope_info = scope_args[2] -- check invalid scope name, @see https://github.com/xmake-io/xmake/issues/4547 if scope_args.n > 0 and type(scope_name) ~= "string" then local errors = string.format("%s(%s): invalid %s name", scope_kind, scope_name, scope_kind) local sourceinfo = debug.getinfo(2, "Sl") if sourceinfo then errors = string.format("%s:%s: %s", sourceinfo.short_src or sourceinfo.source, sourceinfo.currentline, errors) end interpreter._raise(errors) end -- init scope for kind local scope_for_kind = scopes[scope_kind] or {} scopes[scope_kind] = scope_for_kind -- enter the given scope if scope_name ~= nil then -- init scope for name local scope = scope_for_kind[scope_name] or {} scope_for_kind[scope_name] = scope -- save the current scope scopes._CURRENT = scope -- save script directory of scope when enter this scope first scope.__scriptdir = scope.__scriptdir or self:scriptdir() else -- enter root scope scopes._CURRENT = nil end -- update the current scope kind scopes._CURRENT_KIND = scope_kind -- init scope_kind.scope_name for the current root scope scopes._ROOT = scopes._ROOT or {} if scope_name ~= nil then scopes._ROOT[scope_kind .. "@@" .. scope_name] = {} end -- with scope info? translate it -- -- e.g. -- option("text", {showmenu = true, default = true, description = "test option"}) -- target("tbox", {kind = "static", files = {"src/*.c", "*.cpp"}}) -- if scope_info and table.is_dictionary(scope_info) then for name, values in pairs(scope_info) do local apifunc = self:api_func("set_" .. name) or self:api_func("add_" .. name) or self:api_func("on_" .. name) or self:api_func(name) if apifunc then apifunc(table.unpack(table.wrap(values))) else os.raise("unknown %s for %s(\"%s\")", name, scope_kind, scope_name) end end -- enter root scope scopes._CURRENT = nil scopes._CURRENT_KIND = nil -- with scope function? -- -- e.g. -- -- target("foo", function () -- set_kind("binary") -- add_files("src/*.cpp") -- end) -- elseif scope_info and type(scope_info) == "function" then -- configure scope info scope_info() -- enter root scope scopes._CURRENT = nil scopes._CURRENT_KIND = nil end end -- register implementation to the root scope self:_api_register_scope_api(nil, nil, implementation, ...) -- register scope end self:_api_register_scope_end(...) end -- register api for set_values -- -- interp:api_register_set_values("scope_kind", "name1", "name2", ...) -- -- api: -- set_$(name1)("value1") -- set_$(name2)("value1", "value2", ...) -- -- result: -- -- _PRIVATE -- { -- _SCOPES -- { -- _ROOT -- { -- scope_kind -- { -- name2 = {"value3"} -- } -- } -- -- scope_kind -- { -- "scope_name" <-- _SCOPES._CURRENT -- { -- name1 = {"value1"} -- name2 = {"value1", "value2", ...} -- -- __override_name1 = true <- override -- } -- } -- } -- } -- function interpreter:api_register_set_values(scope_kind, ...) -- define implementation local implementation = function (self, scope, name, ...) -- get extra config local values = {...} local extra_config = values[#values] if table.is_dictionary(extra_config) then table.remove(values) else extra_config = nil end -- @note we need to mark table value as meta object to avoid wrap/unwrap -- if these values cannot be expanded, especially when there is only one value -- -- e.g. set_shflags({"-Wl,-exported_symbols_list", exportfile}, {force = true, expand = false}) if extra_config and extra_config.expand == false then for _, value in ipairs(values) do table.wrap_lock(value) end else -- expand values values = table.join(table.unpack(values)) end -- save values if #values > 0 then scope[name] = values else -- set("xx", nil)? remove it scope[name] = nil end -- save extra config if extra_config then scope["__extra_" .. name] = scope["__extra_" .. name] or {} local extrascope = scope["__extra_" .. name] for _, value in ipairs(values) do extrascope[value] = extra_config end end end -- register implementation self:_api_register_xxx_values(scope_kind, "set", implementation, ...) end -- register api for add_values function interpreter:api_register_add_values(scope_kind, ...) -- define implementation local implementation = function (self, scope, name, ...) -- get extra config local values = {...} local extra_config = values[#values] if table.is_dictionary(extra_config) then table.remove(values) else extra_config = nil end -- @note we need to mark table value as meta object to avoid wrap/unwrap -- if these values cannot be expanded, especially when there is only one value -- -- e.g. add_shflags({"-Wl,-exported_symbols_list", exportfile}, {force = true, expand = false}) if extra_config and extra_config.expand == false then for _, value in ipairs(values) do table.wrap_lock(value) end else -- expand values values = table.join(table.unpack(values)) end -- save values scope[name] = table.join2(scope[name] or {}, values) -- save extra config if extra_config then scope["__extra_" .. name] = scope["__extra_" .. name] or {} local extrascope = scope["__extra_" .. name] for _, value in ipairs(values) do extrascope[value] = extra_config end end end -- register implementation self:_api_register_xxx_values(scope_kind, "add", implementation, ...) end -- register api for set_keyvalues -- -- interp:api_register_set_keyvalues("scope_kind", "name1", "name2", ...) -- -- api: -- set_$(name1)("key", "value1") -- set_$(name2)("key", "value1", "value2", ...) -- -- get: -- -- get("name") => {key => values} -- get("name.key") => values -- function interpreter:api_register_set_keyvalues(scope_kind, ...) -- define implementation local implementation = function (self, scope, name, key, ...) -- get extra config local values = {...} local extra_config = values[#values] if table.is_dictionary(extra_config) then table.remove(values) else extra_config = nil end -- save values to "name" scope[name] = scope[name] or {} scope[name][key] = table.unwrap(values) -- expand values if only one -- save values to "name.key" local name_key = name .. "." .. key scope[name_key] = scope[name][key] -- fix override attributes scope["__override_" .. name] = false scope["__override_" .. name_key] = true -- save extra config if extra_config then scope["__extra_" .. name_key] = scope["__extra_" .. name_key] or {} local extrascope = scope["__extra_" .. name_key] for _, value in ipairs(values) do extrascope[value] = extra_config end end end -- register implementation self:_api_register_xxx_values(scope_kind, "set", implementation, ...) end -- register api for set_groups function interpreter:api_register_set_groups(scope_kind, ...) -- define implementation local implementation = function (self, scope, name, ...) -- get extra config local values = {...} local extra_config = values[#values] if table.is_dictionary(extra_config) then table.remove(values) else extra_config = nil end -- expand values values = table.join(table.unpack(values)) table.wrap_lock(values) -- save values scope[name] = values -- save extra config if extra_config then scope["__extra_" .. name] = scope["__extra_" .. name] or {} local extrascope = scope["__extra_" .. name] local key = table.concat(values, "_") extrascope[key] = extra_config end end -- register implementation self:_api_register_xxx_values(scope_kind, "set", implementation, ...) end -- register api for add_groups function interpreter:api_register_add_groups(scope_kind, ...) -- define implementation local implementation = function (self, scope, name, ...) -- get extra config local values = {...} local extra_config = values[#values] if table.is_dictionary(extra_config) then table.remove(values) else extra_config = nil end -- expand values values = table.join(table.unpack(values)) -- save values -- -- @note maybe scope[name] has been unwrapped, we need wrap it first -- https://github.com/xmake-io/xmake/issues/4428 scope[name] = table.wrap(scope[name]) table.wrap_lock(values) table.insert(scope[name], values) -- save extra config if extra_config then scope["__extra_" .. name] = scope["__extra_" .. name] or {} local extrascope = scope["__extra_" .. name] local key = table.concat(values, "_") extrascope[key] = extra_config end end -- register implementation self:_api_register_xxx_values(scope_kind, "add", implementation, ...) end -- register api for add_keyvalues -- -- interp:api_register_add_keyvalues("scope_kind", "name1", "name2", ...) -- function interpreter:api_register_add_keyvalues(scope_kind, ...) -- define implementation local implementation = function (self, scope, name, key, ...) -- get extra config local values = {...} local extra_config = values[#values] if table.is_dictionary(extra_config) then table.remove(values) else extra_config = nil end -- save values to "name" scope[name] = scope[name] or {} if scope[name][key] == nil then -- expand values if only one scope[name][key] = table.unwrap(values) else scope[name][key] = table.join2(table.wrap(scope[name][key]), values) end -- save values to "name.key" local name_key = name .. "." .. key scope[name_key] = scope[name][key] -- save extra config if extra_config then scope["__extra_" .. name_key] = scope["__extra_" .. name_key] or {} local extrascope = scope["__extra_" .. name_key] for _, value in ipairs(values) do extrascope[value] = extra_config end end end -- register implementation self:_api_register_xxx_values(scope_kind, "add", implementation, ...) end -- register api for on_script function interpreter:api_register_on_script(scope_kind, ...) self:_api_register_xxx_script(scope_kind, "on", ...) end -- register api for before_script function interpreter:api_register_before_script(scope_kind, ...) self:_api_register_xxx_script(scope_kind, "before", ...) end -- register api for after_script function interpreter:api_register_after_script(scope_kind, ...) self:_api_register_xxx_script(scope_kind, "after", ...) end -- register api for set_dictionary function interpreter:api_register_set_dictionary(scope_kind, ...) -- define implementation local implementation = function (self, scope, name, dict_or_key, value, extra_config) -- check if type(dict_or_key) == "table" then scope[name] = dict_or_key elseif type(dict_or_key) == "string" and value ~= nil then scope[name] = {[dict_or_key] = value} -- save extra config if extra_config and table.is_dictionary(extra_config) then scope["__extra_" .. name] = scope["__extra_" .. name] or {} local extrascope = scope["__extra_" .. name] extrascope[dict_or_key] = extra_config end else -- error os.raise("set_%s(%s): invalid value type!", name, type(dict)) end end -- register implementation self:_api_register_xxx_values(scope_kind, "set", implementation, ...) end -- register api for add_dictionary function interpreter:api_register_add_dictionary(scope_kind, ...) -- define implementation local implementation = function (self, scope, name, dict_or_key, value, extra_config) -- check scope[name] = scope[name] or {} if type(dict_or_key) == "table" then table.join2(scope[name], dict_or_key) extra_config = value elseif type(dict_or_key) == "string" and value ~= nil then scope[name][dict_or_key] = value -- save extra config if extra_config and table.is_dictionary(extra_config) then scope["__extra_" .. name] = scope["__extra_" .. name] or {} local extrascope = scope["__extra_" .. name] extrascope[dict_or_key] = extra_config end else -- error os.raise("add_%s(%s): invalid value type!", name, type(dict)) end end -- register implementation self:_api_register_xxx_values(scope_kind, "add", implementation, ...) end -- register api for set_paths function interpreter:api_register_set_paths(scope_kind, ...) -- define implementation local implementation = function (self, scope, name, ...) -- get extra config local values = {...} local extra_config = values[#values] if table.is_dictionary(extra_config) then table.remove(values) else extra_config = nil end -- translate paths values = table.join(table.unpack(values)) local paths = self:_api_translate_paths(values, "set_" .. name) -- save values scope[name] = paths -- save extra config if extra_config then scope["__extra_" .. name] = scope["__extra_" .. name] or {} local extrascope = scope["__extra_" .. name] for _, value in ipairs(paths) do extrascope[value] = extra_config end end -- save api source info, e.g. call api() in sourcefile:linenumber self:_save_sourceinfo_to_scope(scope, name, paths) end -- register implementation self:_api_register_xxx_values(scope_kind, "set", implementation, ...) end -- register api for del_paths (deprecated) function interpreter:api_register_del_paths(scope_kind, ...) -- define implementation local implementation = function (self, scope, name, ...) -- translate paths local values = table.join(...) local paths = self:_api_translate_paths(values, "del_" .. name) -- it has been marked as deprecated deprecated.add("remove_" .. name .. "(%s)", "del_" .. name .. "(%s)", table.concat(values, ", "), table.concat(values, ", ")) -- mark these paths as deleted local paths_deleted = {} for _, pathname in ipairs(paths) do table.insert(paths_deleted, "__remove_" .. pathname) end -- save values scope[name] = table.join2(scope[name] or {}, paths_deleted) -- save api source info, e.g. call api() in sourcefile:linenumber self:_save_sourceinfo_to_scope(scope, name, paths) end -- register implementation self:_api_register_xxx_values(scope_kind, "del", implementation, ...) end -- register api for remove_paths function interpreter:api_register_remove_paths(scope_kind, ...) -- define implementation local implementation = function (self, scope, name, ...) -- translate paths local values = table.join(...) local paths = self:_api_translate_paths(values, "remove_" .. name) -- mark these paths as removed local paths_removed = {} for _, pathname in ipairs(paths) do table.insert(paths_removed, "__remove_" .. pathname) end -- save values scope[name] = table.join2(scope[name] or {}, paths_removed) -- save api source info, e.g. call api() in sourcefile:linenumber self:_save_sourceinfo_to_scope(scope, name, paths) end -- register implementation self:_api_register_xxx_values(scope_kind, "remove", implementation, ...) end -- register api for add_paths function interpreter:api_register_add_paths(scope_kind, ...) -- define implementation local implementation = function (self, scope, name, ...) -- get extra config local values = {...} local extra_config = values[#values] if table.is_dictionary(extra_config) then table.remove(values) else extra_config = nil end -- translate paths values = table.join(table.unpack(values)) local paths = self:_api_translate_paths(values, "add_" .. name) -- save values scope[name] = table.join2(scope[name] or {}, paths) -- save extra config if extra_config then scope["__extra_" .. name] = scope["__extra_" .. name] or {} local extrascope = scope["__extra_" .. name] for _, value in ipairs(paths) do extrascope[value] = extra_config end end -- save api source info, e.g. call api() in sourcefile:linenumber self:_save_sourceinfo_to_scope(scope, name, paths) end -- register implementation self:_api_register_xxx_values(scope_kind, "add", implementation, ...) end -- define apis -- -- @code -- interp:api_define -- { -- values = -- { -- -- target.add_xxx -- "target.add_links" -- , "target.add_gcflags" -- , "target.add_ldflags" -- , "target.add_arflags" -- , "target.add_shflags" -- -- -- option.add_xxx -- , "option.add_links" -- , "option.add_gcflags" -- , "option.add_ldflags" -- , "option.add_arflags" -- , "option.add_shflags" -- -- -- is_xxx -- , {"is_os", function (interp, ...) end} -- } -- , paths = -- { -- -- target.add_xxx -- "target.add_linkdirs" -- -- option.add_xxx -- , "option.add_linkdirs" -- } -- } -- @endcode -- function interpreter:api_define(apis) -- register apis local scopes = {} local definitions = self._API_DEFINITIONS or {} for apitype, apifuncs in pairs(apis) do for _, apifunc in ipairs(apifuncs) do -- is {"apifunc", apiscript}? local apiscript = nil if type(apifunc) == "table" then -- check assert(#apifunc == 2 and type(apifunc[2]) == "function") -- get function and script apiscript = apifunc[2] apifunc = apifunc[1] end -- register api definition, "scope.apiname" => "apitype" definitions[apifunc] = apitype -- get api function local apiscope = nil local funcname = nil apifunc = apifunc:split('.', {plain = true}) assert(apifunc) if #apifunc == 2 then apiscope = apifunc[1] funcname = apifunc[2] else funcname = apifunc[1] end assert(funcname) -- register api script directly if apiscript ~= nil then self:api_register(apiscope, funcname, apiscript) else -- get function prefix local prefix = nil for _, name in ipairs({"set", "add", "del", "remove", "on", "before", "after"}) do if funcname:startswith(name .. "_") then prefix = name break end end assert(prefix) -- get function name funcname = funcname:sub(#prefix + 2) -- get register local register = self[string.format("api_register_%s_%s", prefix, apitype)] if not register then os.raise("interp:api_register_%s_%s() is unknown!", prefix, apitype) end -- register scope first if apiscope ~= nil and not scopes[apiscope] then self:api_register_scope(apiscope) scopes[apiscope] = true end -- register api register(self, apiscope, funcname) end end end self._API_DEFINITIONS = definitions end -- the builtin api: set_xmakever() function interpreter:api_builtin_set_xmakever(minver) -- no version if not minver then interpreter._raise("set_xmakever(): no version!") end -- parse minimum version local minvers = minver:split('.', {plain = true}) if not minvers or #minvers ~= 3 then interpreter._raise(string.format("set_xmakever(\"%s\"): invalid version format!", minver)) end -- make minimum numerical version local minvers_num = minvers[1] * 100 + minvers[2] * 10 + minvers[3] -- parse current version local curvers = xmake._VERSION_SHORT:split('.', {plain = true}) -- make current numerical version local curvers_num = curvers[1] * 100 + curvers[2] * 10 + curvers[3] -- check version if curvers_num < minvers_num then interpreter._raise(string.format("xmake v%s < v%s, please run `$xmake update` to upgrade xmake!", xmake._VERSION_SHORT, minver)) end end -- the builtin api: includes() function interpreter:api_builtin_includes(...) assert(self and self._PRIVATE and self._PRIVATE._ROOTDIR and self._PRIVATE._MTIMES) local curfile = self._PRIVATE._CURFILE local scopes = self._PRIVATE._SCOPES -- find all files local subpaths = table.join(...) local subpaths_matched = {} for _, subpath in ipairs(subpaths) do local found = false -- attempt to find files from programdir/includes/*.lua -- e.g. includes("@builtin/check") if subpath:startswith("@builtin/") then local builtin_path = subpath:sub(10) local files if builtin_path:endswith(".lua") then files = os.files(path.join(os.programdir(), "includes", builtin_path)) else files = os.files(path.join(os.programdir(), "includes", builtin_path, "xmake.lua")) end if files and #files > 0 then table.join2(subpaths_matched, files) found = true end end -- find the given files from the project directory if not found then local files = os.match(subpath, not subpath:endswith(".lua")) if files and #files > 0 then table.join2(subpaths_matched, files) found = true end end -- attempt to find files from programdir/includes/*.lua (deprecated) if not found and not path.is_absolute(subpath) then -- e.g. includes("check_cflags.lua") if subpath:startswith("check_") then local files = os.files(path.join(os.programdir(), "includes", "check", subpath)) if files and #files > 0 then table.join2(subpaths_matched, files) found = true utils.warning("deprecated: please use includes(\"@builtin/check\") instead of includes(\"%s\")", subpath) end elseif subpath:startswith("qt_") then local files = os.files(path.join(os.programdir(), "includes", "qt", subpath)) if files and #files > 0 then table.join2(subpaths_matched, files) found = true utils.warning("deprecated: please use includes(\"@builtin/qt\") instead of includes(\"%s\")", subpath) end end end if not found then utils.warning("includes(\"%s\") cannot find any files!", subpath) end end -- includes all files for _, subpath in ipairs(subpaths_matched) do if subpath and type(subpath) == "string" then -- the file path local file = subpath if not subpath:endswith(".lua") then file = path.join(subpath, path.filename(curfile)) end -- get the absolute file path if not path.is_absolute(file) then file = path.absolute(file) end -- update the current file self._PRIVATE._CURFILE = file table.insert(self._PRIVATE._SCRIPT_FILES, file) -- load the file script local script, errors = loadfile(file) if script then -- bind public scope setfenv(script, self._PUBLIC) -- save the previous root scope local root_prev = scopes._ROOT -- save the previous scope local scope_prev = scopes._CURRENT -- save the previous scope kind local scope_kind_prev = scopes._CURRENT_KIND -- clear the current root scope scopes._ROOT = nil -- clear the current scope, force to enter root scope scopes._CURRENT = nil -- save the current directory local oldir = os.curdir() -- enter the script directory os.cd(path.directory(file)) -- done interpreter local ok, errors = xpcall(script, interpreter._traceback) if not ok then interpreter._raise(errors) end -- leave the script directory os.cd(oldir) -- restore the previous scope kind scopes._CURRENT_KIND = scope_kind_prev -- restore the previous scope scopes._CURRENT = scope_prev -- fetch the root values in root scopes first interpreter._fetch_root_scope(scopes._ROOT) -- restore the previous root scope and merge current root scope -- it will override the previous values if the current values are override mode -- so we priority use the values in subdirs scope scopes._ROOT = interpreter._merge_root_scope(scopes._ROOT, root_prev, true) -- get mtime of the file self._PRIVATE._MTIMES[path.relative(file, self._PRIVATE._ROOTDIR)] = os.mtime(file) else interpreter._raise(errors) end end end -- restore the current file self._PRIVATE._CURFILE = curfile end -- the builtin api: add_subdirs(), deprecated function interpreter:api_builtin_add_subdirs(...) self:api_builtin_includes(...) local dirs = {...} deprecated.add("includes(%s)", "add_subdirs(%s)", table.concat(dirs, ", "), table.concat(dirs, ", ")) end -- the builtin api: add_subfiles(), deprecated function interpreter:api_builtin_add_subfiles(...) self:api_builtin_includes(...) local files = {...} deprecated.add("includes(%s)", "add_subfiles(%s)", table.concat(files, ", "), table.concat(files, ", ")) end -- the interpreter api: interp_save_scope() -- save the current scope function interpreter:api_interp_save_scope() assert(self and self._PRIVATE) -- the scopes local scopes = self._PRIVATE._SCOPES assert(scopes) -- save the current scope local scope = {} scope._CURRENT = scopes._CURRENT scope._CURRENT_KIND = scopes._CURRENT_KIND self._PRIVATE._SCOPES_SAVED = self._PRIVATE._SCOPES_SAVED or {} table.insert(self._PRIVATE._SCOPES_SAVED, scope) end -- the interpreter api: interp_restore_scope() -- restore the current scope function interpreter:api_interp_restore_scope() assert(self and self._PRIVATE) -- the scopes local scopes = self._PRIVATE._SCOPES assert(scopes) -- restore it local scopes_saved = self._PRIVATE._SCOPES_SAVED if scopes_saved and #scopes_saved > 0 then local scope = scopes_saved[#scopes_saved] if scope then scopes._CURRENT = scope._CURRENT scopes._CURRENT_KIND = scope._CURRENT_KIND table.remove(scopes_saved, #scopes_saved) end end end -- the interpreter api: interp_get_scopekind() function interpreter:api_interp_get_scopekind() local scopes = self._PRIVATE._SCOPES return scopes._CURRENT_KIND end -- the interpreter api: interp_get_scopename() function interpreter:api_interp_get_scopename() local scopes = self._PRIVATE._SCOPES local scope_kind = scopes._CURRENT_KIND if scope_kind and scopes[scope_kind] then local scope_current = scopes._CURRENT for name, scope in pairs(scopes[scope_kind]) do if scope_current == scope then return name end end end end -- the interpreter api: interp_add_scopeapis() function interpreter:api_interp_add_scopeapis(...) local apis = {...} local extra_config = apis[#apis] if table.is_dictionary(extra_config) then table.remove(apis) else extra_config = nil end if extra_config and #apis == 0 then self:api_define(extra_config) else local kind = "values" if extra_config and extra_config.kind then kind = extra_config.kind end return self:api_define({[kind] = apis}) end end -- get api function function interpreter:api_func(apiname) assert(self and self._PUBLIC and apiname) return self._PUBLIC[apiname] end -- call api function interpreter:api_call(apiname, ...) assert(self and apiname) local apifunc = self:api_func(apiname) if not apifunc then os.raise("call %s() failed, this api not found!", apiname) end return apifunc(...) end -- get current instance in the interpreter modules function interpreter.instance(script) -- get the sandbox instance from the given script local instance = nil if script then local scope = getfenv(script) if scope then rawset(scope, "_INTERPRETER_READABLE", true) instance = scope._INTERPRETER rawset(scope, "_INTERPRETER_READABLE", nil) end if instance then return instance end end -- find self instance for the current sandbox local level = 2 while level < 32 do local scope = getfenv(level) if scope then rawset(scope, "_INTERPRETER_READABLE", true) instance = scope._INTERPRETER rawset(scope, "_INTERPRETER_READABLE", nil) end if instance then break end level = level + 1 end return instance end -- return module: interpreter return interpreter
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/serialize.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 serialize.lua -- -- define module: serialize local serialize = serialize or {} local stub = serialize._stub or {} serialize._stub = stub serialize._dump = serialize._dump or string._dump or string.dump serialize._BCTAG = xmake._LUAJIT and "\27LJ" or "\27Lua" -- load modules local math = require("base/math") local table = require("base/table") local hashset = require("base/hashset") -- reserved keywords in lua function serialize._keywords() local keywords = serialize._KEYWORDS if not keywords then keywords = hashset.of("and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while") serialize._KEYWORDS = keywords end return keywords end function serialize._makestring(str, opt) if string.find(str, "\\", 1, true) and not string.find(str, "[%c%]%\n]") then return string.format("[[%s]]", str) else return string.format("%q", str) end end function serialize._makedefault(val, opt) return tostring(val) end function serialize._maketable(obj, opt, level, pathsegs, reftab) level = level or 0 reftab = reftab or {} pathsegs = pathsegs or {} reftab[obj] = table.copy(pathsegs) -- serialize child items local childlevel = level + 1 local serialized = {} local numidxcount = 0 local isarr = true local maxn = 0 for k, v in pairs(obj) do -- check key if type(k) == "number" then -- only checks when it may be an array if isarr then numidxcount = numidxcount + 1 if k < 1 or not math.isint(k) then isarr = false elseif k > maxn then maxn = k end end elseif type(k) == "string" then isarr = false else return nil, string.format("cannot serialize table with key of %s: <%s>", type(k), k) end -- serialize value local sval, err if type(v) == "table" then if reftab[v] then sval, err = serialize._makeref(reftab[v], opt) else table.insert(pathsegs, k) sval, err = serialize._maketable(v, opt, childlevel, pathsegs, reftab) table.remove(pathsegs) end else sval, err = serialize._make(v, opt) end if err ~= nil then return nil, err end serialized[k] = sval end -- empty table if isarr and numidxcount == 0 then return opt.indentstr and "{ }" or "{}" end -- too sparse if numidxcount * 2 < maxn then isarr = false end -- make body local bodystrs = {} if isarr then for i = 1, maxn do bodystrs[i] = serialized[i] or "nil" end else local dformat = opt.indentstr and "%s = %s" or "%s=%s" local sformat = opt.indentstr and "[%q] = %s" or "[%q]=%s" local nformat = opt.indentstr and "[%s] = %s" or "[%s]=%s" local keywords = serialize._keywords() local makepairs = opt.orderkeys and table.orderpairs or pairs for k, v in makepairs(serialized) do local format -- serialize key if type(k) == "string" then if keywords:has(k) or not k:match("^[%a_][%w_]*$") then format = sformat else format = dformat end else -- type(k) == "number" format = nformat end -- concat k = v table.insert(bodystrs, string.format(format, k, v)) end end -- make head and tail local headstr, bodysep, tailstr if opt.indentstr then local indent = "\n" .. string.rep(opt.indentstr, level) tailstr = indent .. "}" indent = indent .. opt.indentstr headstr = "{" .. indent bodysep = "," .. indent else headstr, bodysep, tailstr = "{", ",", "}" end -- concat together return headstr .. table.concat(bodystrs, bodysep) .. tailstr end function serialize._makefunction(func, opt) local ok, bytecode = pcall(serialize._dump, func, opt.strip) if not ok then return nil, string.format("%s: <%s>", bytecode, func) end return string.format("func%q", bytecode) end function serialize._resolvefunction(root, fenv, bytecode) -- check if type(bytecode) ~= "string" then return nil, string.format("invalid bytecode (string expected, got %s)", type(bytecode)) end if not bytecode:startswith(serialize._BCTAG) then return nil, "cannot load incompatible bytecode" end -- resolve funccode local func, err = load(bytecode, "=(func)", "b", fenv) if err ~= nil then if err:startswith("(func): ") then err = err:sub(#"(func): " + 1) end return nil, err end -- try restore upvalues if fenv then for i = 1, math.huge do local upname = debug.getupvalue(func, i) if upname == nil or upname == "" then break end debug.setupvalue(func, i, fenv[upname]) end end return func end function serialize._makeref(pathsegs, opt) -- root reference if pathsegs[1] == nil then return "ref()" end -- use replicas to avoid infinite generation of nested strings, e.g ref("\"xx\"") => ref("\\\"xx\\\"") => .. local pathrefs = {} for i, v in ipairs(pathsegs) do pathrefs[i] = serialize._make(v, opt) end return "ref(" .. table.concat(pathrefs, opt.indentstr and ", " or ",") .. ")" end function serialize._resolveref(root, fenv, ...) local pathsegs = table.pack("<root>", ...) local pos = root for i = 2, pathsegs.n do local pathseg = pathsegs[i] if type(pathseg) ~= "string" and type(pathseg) ~= "number" then return nil, "path segments should be string or number" end if type(pos) ~= "table" then local vpre = serialize._make(pathseg, {}) local pathstr = table.concat(pathsegs, "/", 1, i) return nil, string.format("unable to resolve [%s] in %s, which is %s", vpre, pathstr, pos) end pos = pos[pathseg] end return pos end -- make string with the level function serialize._make(obj, opt) -- call make* by type if type(obj) == "string" then return serialize._makestring(obj, opt) elseif type(obj) == "boolean" or type(obj) == "nil" then return serialize._makedefault(obj, opt) elseif type(obj) == "number" then if math.isnan(obj) then -- fix nan for lua 5.3, -nan(ind) return "nan" end return serialize._makedefault(obj, opt) elseif type(obj) == "table" then return serialize._maketable(obj, opt) elseif type(obj) == "function" then return serialize._makefunction(obj, opt) else return nil, string.format("cannot serialize %s: <%s>", type(obj), obj) end end function serialize._generateindentstr(indent) -- init indent, from nil, boolean, number or string to false or string if not indent then -- no indent return nil elseif indent == true then -- 4 spaces return " " elseif type(indent) == "number" then if indent < 0 then return nil elseif indent > 20 then return nil, "invalid opt.indent, too large" else -- indent spaces return string.rep(" ", indent) end elseif type(indent) == "string" then -- only whitespaces allowed if not (indent:trim() == "") then return nil, "invalid opt.indent, only whitespaces are accepted" end return indent else return nil, "invalid opt.indent, should be boolean, number or string" end end -- serialize to string from the given obj -- -- @param opt serialize options -- -- @return string, errors -- function serialize.save(obj, opt) -- init options if opt == true then opt = { strip = true, binary = false, indent = false } elseif not opt then opt = {} end if opt.strip == nil then opt.strip = false end if opt.binary == nil then opt.binary = false end if opt.indent == nil then opt.indent = true end local indent, ierrors = serialize._generateindentstr(opt.indent) if ierrors then return nil, ierrors end opt.indentstr = indent -- make string local ok, result, errors = pcall(serialize._make, obj, opt) if not ok then errors = "cannot serialize: " .. result end -- ok? if errors ~= nil then return nil, errors end if not opt.binary then return result end -- binary mode local func, lerr = load("return " .. result, "=") if lerr ~= nil then return nil, lerr end local dump, derr = serialize._dump(func, true) if derr ~= nil then return nil, derr end -- return shorter representation return (#dump < #result) and dump or result end -- init stub metatable stub.isstub = setmetatable({}, { __tostring = function() return "stub indentifier" end }) stub.__index = stub function stub:__call(root, fenv) return self.resolver(root, fenv, table.unpack(self.params, 1, self.params.n)) end function stub:__tostring() local fparams = {} for i = 1, self.params.n do fparams[i] = serialize._make(self.params[i], {}) end return string.format("%s(%s)", self.name, table.concat(fparams, ", ")) end -- called by functions in deserialize environment -- create a function (called stub) to finish deserialization function serialize._createstub(name, resolver, env, ...) env.has_stub = true return setmetatable({ name = name, resolver = resolver, params = table.pack(...)}, stub) end -- after deserialization by load() -- use this routine to call all stubs in deserialzed data -- -- @param obj obj to search stubs -- root root obj -- fenv fenv of deserialzer caller -- pathseg path key for current item function serialize._resolvestub(obj, root, fenv, pathseg) if type(obj) ~= "table" then return obj end if obj.isstub == stub.isstub then local ok, result_or_errors, errors = pcall(obj, root, fenv) if ok and errors == nil then return result_or_errors end -- resolve & concat path only if error occurs local pathsegs = {} local level = 1 while true do if debug.getinfo(level, "f").func ~= serialize._resolvestub then break end local _, p = debug.getlocal(level, 4) table.insert(pathsegs, 1, p) level = level + 1 end -- make error message local errmsg = (ok and errors) or result_or_errors or "unspecified error" return nil, string.format("failed to resolve stub '%s' at %s: %s", obj.name, table.concat(pathsegs, "/"), errmsg) end for k, v in pairs(obj) do local result, errors = serialize._resolvestub(v, root, fenv, k) if errors ~= nil then return nil, errors end obj[k] = result end return obj end -- create a env for deserialze load() call function serialize._createenv() -- init env local env = { nan = math.nan, inf = math.huge } -- resolve reference function env.ref(...) -- load ref return serialize._createstub("ref", serialize._resolveref, env, ...) end -- load function function env.func(...) -- load func return serialize._createstub("func", serialize._resolvefunction, env, ...) end -- return new env return env end -- load table from string in table function serialize._load(str) -- load table as script local result = nil local binary = str:startswith(serialize._BCTAG) if not binary then str = "return " .. str end -- load string local env = serialize._createenv() local script, errors = load(str, binary and "=(b)" or "=(t)", binary and "b" or "t", env) if script then -- load obj local ok, obj = pcall(script) if ok then result = obj if env.has_stub then local fenv = debug.getfenv(debug.getinfo(3, "f").func) result, errors = serialize._resolvestub(result, result, fenv, "<root>") end else -- error errors = tostring(obj) end end if errors then local data if binary then data = "<binary data>" elseif #str > 30 then data = string.format("%q... ", str:sub(8, 27)) else data = string.format("%q", str:sub(8)) end -- error return nil, string.format("cannot deserialize %s: %s", data, errors) end return result end -- deserialize string to obj -- -- @param str the serialized string -- -- @return obj, errors -- function serialize.load(str) -- check assert(str) -- load string local result, errors = serialize._load(str) if errors ~= nil then return nil, errors end return result end -- return module: serialize return serialize
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/global.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 global.lua -- -- define module local global = global or {} -- load modules local io = require("base/io") local os = require("base/os") local path = require("base/path") local utils = require("base/utils") local option = require("base/option") -- get the current given configure function global.get(name) local value = nil if global._CONFIGS then value = global._CONFIGS[name] if type(value) == "string" and value == "auto" then value = nil end end return value end -- this global name is readonly? function global.readonly(name) return global._MODES and global._MODES["__readonly_" .. name] end -- set the given configure to the current -- -- @param name the name -- @param value the value -- @param opt the argument options, e.g. {readonly = false, force = false} -- function global.set(name, value, opt) -- check assert(name) -- init options opt = opt or {} -- check readonly assert(opt.force or not global.readonly(name), "cannot set readonly global: " .. name) -- set it global._CONFIGS = global._CONFIGS or {} global._CONFIGS[name] = value -- mark as readonly if opt.readonly then global._MODES = global._MODES or {} global._MODES["__readonly_" .. name] = true end end -- get all options function global.options() -- remove values with "auto" and private item local configs = {} for name, value in pairs(table.wrap(global._CONFIGS)) do if not name:find("^_%u+") and name ~= "__version" and (type(value) ~= "string" or value ~= "auto") then configs[name] = value end end return configs end -- get the configure file function global.filepath() return path.join(global.directory(), xmake._NAME .. ".conf") end -- get the global configure directory function global.directory() if global._DIRECTORY == nil then local name = "." .. xmake._NAME local rootdir = os.getenv("XMAKE_GLOBALDIR") if not rootdir then -- compatible with the old `%appdata%/.xmake` directory if it exists local appdata = (os.host() == "windows") and os.getenv("APPDATA") if appdata and os.isdir(path.join(appdata, name)) then rootdir = appdata else rootdir = path.translate("~") end end global._DIRECTORY = path.join(rootdir, name) end return global._DIRECTORY end -- get the global cache directory function global.cachedir() return global.get("cachedir") or path.join(global.directory(), "cache") end -- load the global configuration function global.load() -- load configure from the file first local filepath = global.filepath() if os.isfile(filepath) then -- load configs local results, errors = io.load(filepath) if not results then return false, errors end -- merge the configure for name, value in pairs(results) do if global.get(name) == nil then global.set(name, value) end end end return true end -- save the global configure function global.save() -- the options local options = global.options() assert(options) -- add version options.__version = xmake._VERSION_SHORT -- save it return io.save(global.filepath(), options) end -- clear config function global.clear() global._MODES = nil global._CONFIGS = nil end -- dump the configure function global.dump() if not option.get("quiet") then utils.print("configure") utils.print("{") for name, value in pairs(global.options()) do if not name:startswith("__") then utils.print(" %s = %s", name, value) end end utils.print("}") end end -- return module return global
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/io.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 io.lua -- -- define module local io = io or {} local _file = _file or {} local _filelock = _filelock or {} -- load modules local path = require("base/path") local table = require("base/table") local string = require("base/string") local todisplay = require("base/todisplay") -- save metatable and builtin functions io._file = _file io._filelock = _filelock io._stdfile = io._stdfile or io.stdfile -- new a file function _file.new(filepath, cdata, isstdfile) local file = table.inherit(_file) file._PATH = isstdfile and filepath or path.absolute(filepath) file._FILE = cdata setmetatable(file, _file) return file end -- get the file name function _file:name() if not self._NAME then self._NAME = path.filename(self:path()) end return self._NAME end -- get the file path function _file:path() return self._PATH end -- close file function _file:close() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- close file ok, errors = io.file_close(self:cdata()) if ok then self._FILE = nil end return ok, errors end -- tostring(file) function _file:__tostring() local str = self:path() if #str > 16 then str = ".." .. str:sub(#str - 16, #str) end return "<file: " .. str .. ">" end -- todisplay(file) function _file:__todisplay() local size = _file.size(self) local filepath = _file.path(self) if not size then return string.format("file${reset} %s", todisplay(filepath)) end local unit = "B" if size >= 1000 then size = size / 1024 unit = "KiB" end if size >= 1000 then size = size / 1024 unit = "MiB" end if size >= 1000 then size = size / 1024 unit = "GiB" end return string.format("file${reset}(${color.dump.number}%.3f%s${reset}) %s", size, unit, todisplay(filepath)) end -- gc(file) function _file:__gc() if self:cdata() and io.file_close(self:cdata()) then -- remove ref to notify gc that it should be freed self._FILE = nil end end -- get file length function _file:__len() return _file.size(self) end -- get cdata function _file:cdata() return self._FILE end -- get file rawfd function _file:rawfd() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return nil, errors end -- get file rawfd local result, errors = io.file_rawfd(self:cdata()) if not result and errors then errors = string.format("%s: %s", self, errors) end return result, errors end -- get file size function _file:size() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return nil, errors end -- get file size local result, errors = io.file_size(self:cdata()) if not result and errors then errors = string.format("%s: %s", self, errors) end return result, errors end -- read data from file -- -- @param fmt the reading format -- @param opt the options -- - continuation (concat string with the given continuation characters) -- function _file:read(fmt, opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return nil, errors end -- read file opt = opt or {} local result, errors = io.file_read(self:cdata(), fmt, opt.continuation) if errors then errors = string.format("%s: %s", self, errors) end return result, errors end -- is readable? function _file:readable() local ok, errors = self:_ensure_opened() if not ok then return false, errors end return io.file_readable(self:cdata()) end -- write data to file function _file:write(...) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- data items local items = table.pack(...) for idx, item in ipairs(items) do if type(item) == "table" and item.caddr and item.size then -- write bytes items[idx] = {data = item:caddr(), size = item:size()} end end -- write file ok, errors = io.file_write(self:cdata(), table.unpack(items)) if not ok and errors then errors = string.format("%s: %s", self, errors) end return ok, errors end -- seek offset at file function _file:seek(whence, offset) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- seek file local result, errors = io.file_seek(self:cdata(), whence, offset) if not result and errors then errors = string.format("%s: %s", self, errors) end return result, errors end -- flush data to file function _file:flush() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- flush file ok, errors = io.file_flush(self:cdata()) if not ok and errors then errors = string.format("%s: %s", self, errors) end return ok, errors end -- this file is a tty? function _file:isatty() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return nil, errors end -- is a tty? ok, errors = io.file_isatty(self:cdata()) if ok == nil and errors then errors = string.format("%s: %s", self, errors) end return ok, errors end -- ensure the file is opened function _file:_ensure_opened() if not self:cdata() then return false, string.format("%s: has been closed!", self) end return true end -- read all lines from file function _file:lines(opt) opt = opt or {} return function() local l = _file.read(self, "l", opt) if not l and opt.close_on_finished then _file.close(self) end return l end end -- print file function _file:print(...) return _file.write(self, string.format(...), "\n") end -- printf file function _file:printf(...) return _file.write(self, string.format(...)) end -- save object function _file:save(object, opt) local str, errors = string.serialize(object, opt) if errors then return false, errors else return _file.write(self, str) end end -- load object function _file:load() local data, err = _file.read(self, "*all") if err then return nil, err end if data and type(data) == "string" then return data:deserialize() end end -- new an filelock function _filelock.new(lockpath, lock) local filelock = table.inherit(_filelock) filelock._PATH = path.absolute(lockpath) filelock._LOCK = lock filelock._LOCKED_NUM = 0 setmetatable(filelock, _filelock) return filelock end -- get the filelock name function _filelock:name() if not self._NAME then self._NAME = path.filename(self:path()) end return self._NAME end -- get the filelock path function _filelock:path() return self._PATH end -- get the cdata function _filelock:cdata() return self._LOCK end -- is locked? function _filelock:islocked() return self._LOCKED_NUM > 0 end -- lock file -- -- @param opt the argument option, {shared = true} -- -- @return ok, errors -- function _filelock:lock(opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- lock it if self._LOCKED_NUM > 0 or io.filelock_lock(self:cdata(), opt) then self._LOCKED_NUM = self._LOCKED_NUM + 1 return true else return false, string.format("%s: lock failed!", self) end end -- try to lock file -- -- @param opt the argument option, {shared = true} -- -- @return ok, errors -- function _filelock:trylock(opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- try lock it if self._LOCKED_NUM > 0 or io.filelock_trylock(self:cdata(), opt) then self._LOCKED_NUM = self._LOCKED_NUM + 1 return true else return false, string.format("%s: trylock failed!", self) end end -- unlock file function _filelock:unlock(opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- unlock it if self._LOCKED_NUM > 1 or (self._LOCKED_NUM > 0 and io.filelock_unlock(self:cdata())) then if self._LOCKED_NUM > 0 then self._LOCKED_NUM = self._LOCKED_NUM - 1 else self._LOCKED_NUM = 0 end return true else return false, string.format("%s: unlock failed!", self) end end -- close filelock function _filelock:close() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- close it ok = io.filelock_close(self:cdata()) if ok then self._LOCK = nil self._LOCKED_NUM = 0 end return ok end -- ensure the file is opened function _filelock:_ensure_opened() if not self:cdata() then return false, string.format("%s: has been closed!", self) end return true end -- tostring(filelock) function _filelock:__tostring() local str = _filelock.path(self) if #str > 16 then str = ".." .. str:sub(#str - 16, #str) end return "<filelock: " .. str .. ">" end -- todisplay(filelock) function _filelock:__todisplay() local str = _filelock.path(self) return "filelock${reset} " .. todisplay(str) end -- gc(filelock) function _filelock:__gc() if self:cdata() and io.filelock_close(self:cdata()) then self._LOCK = nil self._LOCKED_NUM = 0 end end -- read all lines from file function io.lines(filepath, opt) opt = opt or {} if opt.close_on_finished == nil then opt.close_on_finished = true end local file = io.open(filepath, "r", opt) if not file then return function() return nil end end return file:lines(opt) end -- read all data from file function io.readfile(filepath, opt) opt = opt or {} local file, errors = io.open(tostring(filepath), "r", opt) if not file then return nil, errors end local data, err = file:read("*all", opt) file:close() return data, err end function io.read(fmt, opt) return io.stdin:read(fmt, opt) end function io.readable() return io.stdin:readable() end function io.write(...) return io.stdout:write(...) end function io.print(...) return io.stdout:print(...) end function io.printf(...) return io.stdout:printf(...) end function io.flush() return io.stdout:flush() end -- write data to file function io.writefile(filepath, data, opt) opt = opt or {} local file, errors = io.open(tostring(filepath), "w", opt) if not file then return false, errors end file:write(data) file:close() return true end -- isatty function io.isatty(file) file = file or io.stdout return file:isatty() end -- get std file, /dev/stdin, /dev/stdout, /dev/stderr function io.stdfile(filepath) local file = nil if filepath == "/dev/stdin" then file = io._stdfile(1) elseif filepath == "/dev/stdout" then file = io._stdfile(2) elseif filepath == "/dev/stderr" then file = io._stdfile(3) end if file then return _file.new(filepath, file, true) else return nil, string.format("failed to get std file: %s", filepath) end end -- open file -- -- @param filepath the file path -- @param mode the open mode, e.g. 'r', 'rb', 'w+', 'a+', .. -- @param opt the options -- - encoding, e.g. utf8, utf16, utf16le, utf16be .. -- function io.open(filepath, mode, opt) -- init option and mode opt = opt or {} mode = mode or "r" -- open it filepath = tostring(filepath) local file = io.file_open(filepath, mode .. (opt.encoding or "")) if file then return _file.new(filepath, file) else return nil, string.format("cannot open file: %s, %s", filepath, os.strerror()) end end -- open a filelock function io.openlock(filepath) filepath = tostring(filepath) local lock = io.filelock_open(filepath) if lock then return _filelock.new(filepath, lock) else return nil, string.format("cannot open lock: %s, %s", filepath, os.strerror()) end end -- close file function io.close(file) return (file or io.stdout):close() end -- save object the the given filepath function io.save(filepath, object, opt) opt = opt or {} assert(filepath and object) filepath = tostring(filepath) -- we save it when file is only changed, we can ensure file modify time. local oldstr if opt.only_changed and os.isfile(filepath) then oldstr = io.readfile(filepath, {encoding = "binary"}) end local ok, errors, str str, errors = string.serialize(object, opt) if str then local write = true if opt.only_changed then if oldstr == str then write = false end end if write then ok, errors = io.writefile(filepath, str, {encoding = "binary"}) else ok = true end end if not ok then return false, string.format("save %s failed, %s!", filepath, errors) end return true end -- load object from the given file function io.load(filepath, opt) assert(filepath) opt = opt or {} filepath = tostring(filepath) local file, err = io.open(filepath, "rb", opt) if err then return nil, err end local result, errors = file:load() file:close() return result, errors end -- gsub the given file and return replaced data function io.gsub(filepath, pattern, replace, opt) -- read all data from file opt = opt or {} local data, errors = io.readfile(filepath, opt) if not data then return nil, 0, errors end -- replace it local count = 0 if type(data) == "string" then data, count = data:gsub(pattern, replace) else return nil, 0, string.format("data is not string!") end -- replace ok? if count ~= 0 then -- write all data to file local ok, errors = io.writefile(filepath, data, opt) if not ok then return nil, 0, errors end end return data, count end -- replace text of the given file and return new file data function io.replace(filepath, pattern, replace, opt) opt = opt or {} local data, errors = io.readfile(filepath, opt) if not data then return nil, 0, errors end local count = 0 if type(data) == "string" then data, count = data:replace(pattern, replace, opt) else return nil, 0, string.format("data is not string!") end if count ~= 0 then local ok, errors = io.writefile(filepath, data, opt) if not ok then return nil, 0, errors end end return data, count end -- insert text before line number in the given file and return new file data function io.insert(filepath, lineidx, text, opt) opt = opt or {} local data, errors = io.readfile(filepath, opt) if not data then return nil, errors end local newdata if type(data) == "string" then newdata = {} for idx, line in ipairs(data:split("\n")) do if idx == lineidx then table.insert(newdata, text) end table.insert(newdata, line) end else return nil, string.format("data is not string!") end if newdata and #newdata > 0 then local rn = data:find("\r\n", 1, true) data = table.concat(newdata, rn and "\r\n" or "\n") local ok, errors = io.writefile(filepath, data, opt) if not ok then return nil, errors end end return data, count end -- cat the given file function io.cat(filepath, linecount, opt) opt = opt or {} local file = io.open(filepath, "r", opt) if file then local count = 1 for line in file:lines(opt) do io.write(line, "\n") if linecount and count >= linecount then break end count = count + 1 end file:close() end end -- tail the given file function io.tail(filepath, linecount, opt) opt = opt or {} if linecount < 0 then return io.cat(filepath, opt) end -- open file local file = io.open(filepath, "r", opt) if file then local lines = {} for line in file:lines(opt) do table.insert(lines, line) end local tails = {} if #lines ~= 0 then local count = 1 for index = #lines, 1, -1 do table.insert(tails, lines[index]) if linecount and count >= linecount then break end count = count + 1 end end if #tails ~= 0 then for index = #tails, 1, -1 do io.print(tails[index]) end end file:close() end end -- lazy loading stdfile io.stdin = nil io.stdout = nil io.stderr = nil setmetatable(io, { __index = function (tbl, key) local val = rawget(tbl, key) if val == nil and (key == "stdin" or key == "stdout" or key == "stderr") then val = io.stdfile("/dev/" .. key) if val ~= nil then rawset(tbl, key, val) end end return val end}) -- return module return io
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/xmake.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file xmake.lua -- -- define module: xmake local xmake = xmake or {} -- load modules local semver = require("base/semver") -- get name function xmake.name() return xmake._NAME or "xmake" end -- get xmake version, e.g. v2.5.8+dev.d4cff6e11 function xmake.version() if xmake._VERSION_CACHE == nil then xmake._VERSION_CACHE = semver.new(xmake._VERSION) or false end return xmake._VERSION_CACHE or nil end -- get the xmake binary architecture function xmake.arch() return xmake._XMAKE_ARCH end -- get the git branch of xmake version, e.g. build: {"dev", "d4cff6e11"} function xmake.branch() return xmake.version():build()[1] end -- get the program directory function xmake.programdir() return xmake._PROGRAM_DIR end -- get the program file function xmake.programfile() return xmake._PROGRAM_FILE end -- use luajit? function xmake.luajit() return xmake._LUAJIT end -- get command arguments function xmake.argv() return xmake._ARGV end -- return module: xmake return xmake
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/poller.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 poller.lua -- -- define module local poller = poller or {} -- load modules local io = require("base/io") local string = require("base/string") -- the poller object type, @see tbox/platform/poller.h poller.OT_SOCK = 1 poller.OT_PIPE = 2 poller.OT_PROC = 3 poller.OT_FWATCHER = 4 -- the poller events, @see tbox/platform/poller.h poller.EV_POLLER_RECV = 1 poller.EV_POLLER_SEND = 2 poller.EV_POLLER_CONN = poller.EV_POLLER_SEND poller.EV_POLLER_ACPT = poller.EV_POLLER_RECV poller.EV_POLLER_CLEAR = 0x0010 -- edge trigger. after the event is retrieved by the user, its state is reset poller.EV_POLLER_ONESHOT = 0x0010 -- causes the event to return only the first occurrence of the filter being triggered poller.EV_POLLER_EOF = 0x0100 -- the event flag will be marked if the connection be closed in the edge trigger poller.EV_POLLER_ERROR = 0x0200 -- socket error after waiting -- get poller object data function poller:_pollerdata(cdata) return self._POLLERDATA and self._POLLERDATA[cdata] or nil end -- set poller object data function poller:_pollerdata_set(cdata, data) local pollerdata = self._POLLERDATA if not pollerdata then pollerdata = {} self._POLLERDATA = pollerdata end pollerdata[cdata] = data end -- support events? function poller:support(events) return io.poller_support(events) end -- spank poller to break the wait() and return all triggered events function poller:spank() io.poller_spank() end -- insert object events to poller function poller:insert(obj, events, udata) -- insert it local ok, errors = io.poller_insert(obj:otype(), obj:cdata(), events) if not ok then return false, string.format("%s: insert events(%d) to poller failed, %s", obj, events, errors or "unknown reason") end -- save poller object data and save obj/ref for gc self:_pollerdata_set(obj:cdata(), {obj, udata}) return true end -- modify object events in poller function poller:modify(obj, events, udata) -- modify it local ok, errors = io.poller_modify(obj:otype(), obj:cdata(), events) if not ok then return false, string.format("%s: modify events(%d) to poller failed, %s", obj, events, errors or "unknown reason") end -- update poller object data self:_pollerdata_set(obj:cdata(), {obj, udata}) return true end -- remove object from poller function poller:remove(obj) -- remove it local ok, errors = io.poller_remove(obj:otype(), obj:cdata()) if not ok then return false, string.format("%s: remove events from poller failed, %s", obj, errors or "unknown reason") end -- remove poller object data self:_pollerdata_set(obj, nil) return true end -- wait object events in poller function poller:wait(timeout) -- wait it local events, count = io.poller_wait(timeout or -1) if count < 0 then return -1, "wait events in poller failed!" end -- check count if count > 0 and count ~= #events then return -1, string.format("events(%d) != %d in poller!", #events, count) end -- wrap objects with cdata local results = {} if events then for _, v in ipairs(events) do local otype = v[1] local cdata = v[2] local events = v[3] local pollerdata = self:_pollerdata(cdata) if not pollerdata then return -1, string.format("no object data for cdata(%s)!", cdata) end local obj = pollerdata[1] assert(obj and obj:otype() == otype and obj:cdata() == cdata) table.insert(results, {obj, events, pollerdata[2]}) end end return count, results end -- return module return poller
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/fwatcher.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 fwatcher.lua -- -- define module: fwatcher local fwatcher = fwatcher or {} local _instance = _instance or {} -- load modules local os = require("base/os") local string = require("base/string") local coroutine = require("base/coroutine") local scheduler = require("base/scheduler") -- save original interfaces fwatcher._open = fwatcher._open or fwatcher.open fwatcher._add = fwatcher._add or fwatcher.add fwatcher._remove = fwatcher._remove or fwatcher.remove fwatcher._wait = fwatcher._wait or fwatcher.wait fwatcher._close = fwatcher._close or fwatcher.close -- the fwatcher event type, @see tbox/platform/fwatcher.h fwatcher.ET_MODIFY = 1 fwatcher.ET_CREATE = 2 fwatcher.ET_DELETE = 4 -- get cdata of fwatcher function _instance:cdata() local cdata = self._CDATA if not cdata and not self._CLOSED then cdata = fwatcher._open() self._CDATA = cdata end return cdata end -- get poller object type, poller.OT_FWATCHER function _instance:otype() return 4 end -- add watch directory, e.g. {recursion = true} function _instance:add(watchdir, opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- add watchdir opt = opt or {} local ok, errors = fwatcher._add(self:cdata(), watchdir, opt.recursion or false) if not ok then errors = string.format("<fwatcher>: add %s failed, %s", watchdir, errors or "unknown errors") end return ok, errors end -- remove watch directory function _instance:remove(watchdir) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- remove watchdir opt = opt or {} local ok, errors = fwatcher._remove(self:cdata(), watchdir) if not ok then errors = string.format("<fwatcher>: remove %s failed, %s", watchdir, errors or "unknown errors") end return ok, errors end -- wait event -- -- @param timeout the timeout -- -- @return ok, event, e.g {type = fwatcher.ET_MODIFY, path = "/tmp"} -- function _instance:wait(timeout) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- wait events local result = -1 local event_or_errors = nil if scheduler:co_running() then result, event_or_errors = scheduler:poller_waitfs(self, timeout or -1) else result, event_or_errors = fwatcher._wait(self:cdata(), timeout or -1) end if result < 0 and event_or_errors then event_or_errors = string.format("<fwatcher>: wait failed, %s", event_or_errors) end return result, event_or_errors end -- close instance function _instance:close() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- cancel pipe events from the scheduler if scheduler:co_running() then ok, errors = scheduler:poller_cancel(self) if not ok then return false, errors end end -- close fwatcher ok = fwatcher._close(self:cdata()) if ok then self._CDATA = nil self._CLOSED = true end return ok end -- ensure the fwatcher is opened function _instance:_ensure_opened() if not self:cdata() then return false, string.format("<fwatcher:%s>: has been closed!", self:cdata()) end return true end -- add watchdir function fwatcher.add(watchdir, opt) return _instance:add(watchdir, opt) end -- remove watchdir function fwatcher.remove(watchdir) return _instance:remove(watchdir) end -- wait event function fwatcher.wait(timeout) return _instance:wait(timeout) end -- watch directories -- -- @param watchdirs the watch directories, pattern path string or path list -- @param callback the event callback -- @param opt the option, e.g. {timeout = -1, recursion = true} -- -- @code -- fwatcher.watchdirs("/tmp/test_*", function (event) -- print(event) -- end, {timeout = -1, recursion = true}) -- @endcode function fwatcher.watchdirs(watchdirs, callback, opt) -- add watch directories opt = opt or {} if type(watchdirs) == "string" then watchdirs = os.dirs(watchdirs) end local ok = true local errors = nil for _, watchdir in ipairs(watchdirs) do ok, errors = fwatcher.add(watchdir, opt) if not ok then break end end -- do watch while ok do local result, event_or_errors = fwatcher.wait(opt.timeout or -1) if result < 0 then ok = false errors = event_or_errors break end if result > 0 then callback(event_or_errors) end end -- remove watch directories for _, watchdir in ipairs(watchdirs) do local result, rm_errors = fwatcher.remove(watchdir) if not result then ok = false errors = errors or rm_errors break end end return ok, errors end -- watch the created file path in directories -- -- @param watchdirs the watch directories, pattern path string or path list -- @param callback the event callback -- @param opt the option, e.g. {timeout = -1, recursion = true} -- -- @code -- fwatcher.on_created("/tmp/test_*", function (filepath) -- print(filepath) -- end, {timeout = -1, recursion = true}) -- @endcode function fwatcher.on_created(watchdirs, callback, opt) return fwatcher.watchdirs(watchdirs, function (event) if event and event.type == fwatcher.ET_CREATE then callback(event.path) end end, opt) end -- watch the modified file path in directories -- -- @param watchdirs the watch directories, pattern path string or path list -- @param callback the event callback -- @param opt the option, e.g. {timeout = -1, recursion = true} -- -- @code -- fwatcher.on_modified("/tmp/test_*", function (filepath) -- print(filepath) -- end, {timeout = -1, recursion = true}) -- @endcode function fwatcher.on_modified(watchdirs, callback, opt) return fwatcher.watchdirs(watchdirs, function (event) if event and event.type == fwatcher.ET_MODIFY then callback(event.path) end end, opt) end -- watch the deleted file path in directories -- -- @param watchdirs the watch directories, pattern path string or path list -- @param callback the event callback -- @param opt the option, e.g. {timeout = -1, recursion = true} -- -- @code -- fwatcher.on_deleted("/tmp/test_*", function (filepath) -- print(filepath) -- end, {timeout = -1, recursion = true}) -- @endcode function fwatcher.on_deleted(watchdirs, callback, opt) return fwatcher.watchdirs(watchdirs, function (event) if event and event.type == fwatcher.ET_DELETE then callback(event.path) end end, opt) end return fwatcher
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/coroutine.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 coroutine.lua -- -- define module: coroutine local coroutine = coroutine or {} -- load modules local utils = require("base/utils") local option = require("base/option") local string = require("base/string") -- save original interfaces coroutine._resume = coroutine._resume or coroutine.resume -- resume coroutine function coroutine.resume(co, ...) local ok, results = coroutine._resume(co, ...) if not ok then -- get errors local errors = results if option.get("diagnosis") then errors = debug.traceback(co, results) elseif type(results) == "string" then -- remove the prefix info local _, pos = results:find(":%d+: ") if pos then errors = results:sub(pos + 1) end end return false, errors end return true, results end -- return module: coroutine return coroutine
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/profiler.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 profiler.lua -- -- define module local profiler = {} -- load modules local os = require("base/os") local path = require("base/path") local heap = require("base/heap") local table = require("base/table") local utils = require("base/utils") local string = require("base/string") -- get the function key function profiler:_func_key(funcinfo) local name = funcinfo.name or 'anonymous' local line = funcinfo.linedefined or 0 local source = funcinfo.short_src or 'C_FUNC' return name .. source .. line end -- get the function title function profiler:_func_title(funcinfo) local name = funcinfo.name or 'anonymous' local line = string.format("%d", funcinfo.linedefined or 0) local source = funcinfo.short_src or 'C_FUNC' if os.isfile(source) then source = path.relative(source, xmake._PROGRAM_DIR) end return string.format("%-30s: %s: %s", name, source, line) end -- get the function report function profiler:_func_report(funcinfo) local key = self:_func_key(funcinfo) local report = self._REPORTS_BY_KEY[key] if not report then report = { funcinfo = funcinfo, callcount = 0, totaltime = 0 } self._REPORTS_BY_KEY[key] = report table.insert(self._REPORTS, report) end return report end -- get the tag key function profiler:_tag_key(name, argv) local key = name if argv then for _, item in ipairs(argv) do if type(item) == "table" then key = key .. os.args(item) else key = key .. tostring(item) end end end return key end -- get the tag title function profiler:_tag_title(name, argv) local key = name if argv then for _, item in ipairs(argv) do if type(item) == "table" then key = key .. ": " .. os.args(item) else key = key .. ": " .. tostring(item) end end end return key end -- get the tag report function profiler:_tag_report(name, argv) self._REPORTS_BY_KEY = self._REPORTS_BY_KEY or {} local key = self:_tag_key(name, argv) local report = self._REPORTS_BY_KEY[key] if not report then report = { name = name, argv = argv, callcount = 0, totaltime = 0 } self._REPORTS_BY_KEY[key] = report self._REPORTS = self._REPORTS or {} table.insert(self._REPORTS, report) end return report end -- profiling call function profiler:_profiling_call(funcinfo) local report = self:_func_report(funcinfo) report.calltime = os.clock() report.callcount = report.callcount + 1 end -- profiling return function profiler:_profiling_return(funcinfo) local stoptime = os.clock() local report = self:_func_report(funcinfo) if report.calltime and report.calltime > 0 then report.totaltime = report.totaltime + (stoptime - report.calltime) report.calltime = 0 end end -- the profiling handler function profiler._profiling_handler(hooktype) local funcinfo = debug.getinfo(2, 'nS') if hooktype == "call" then profiler:_profiling_call(funcinfo) elseif hooktype == "return" then profiler:_profiling_return(funcinfo) end end -- the tracing handler function profiler._tracing_handler(hooktype) local funcinfo = debug.getinfo(2, 'nS') if hooktype == "call" then local name = funcinfo.name local source = funcinfo.short_src if name and source and source:endswith(".lua") then local line = string.format("%d", funcinfo.linedefined or 0) utils.print("%-30s: %s: %s", name, source, line) end end end -- start profiling function profiler:start() if self:is_trace() then debug.sethook(profiler._tracing_handler, 'cr', 0) elseif self:is_perf("call") then self._REPORTS = self._REPORTS or {} self._REPORTS_BY_KEY = self._REPORTS_BY_KEY or {} self._STARTIME = self._STARTIME or os.clock() debug.sethook(profiler._profiling_handler, 'cr', 0) end end -- stop profiling function profiler:stop() if self:is_trace() then debug.sethook() elseif self:is_perf("call") then self._STOPTIME = os.clock() debug.sethook() -- calculate the total time local totaltime = self._STOPTIME - self._STARTIME -- sort reports local reports = self._REPORTS or {} table.sort(reports, function(a, b) return a.totaltime > b.totaltime end) -- show reports for _, report in ipairs(reports) do local percent = (report.totaltime / totaltime) * 100 if percent < 1 then break end utils.print("%6.3f, %6.2f%%, %7d, %s", report.totaltime, percent, report.callcount, self:_func_title(report.funcinfo)) end elseif self:is_perf("tag") then -- sort reports, topN local reports = self._REPORTS or {} local h = heap.valueheap({cmp = function(a, b) return a.totaltime > b.totaltime end}) for _, report in ipairs(reports) do h:push(report) end -- show reports local count = 0 while count < 64 and h:length() > 0 do local report = h:pop() utils.print("%6.3f, %7d, %s", report.totaltime, report.callcount, self:_tag_title(report.name, report.argv)) count = count + 1 end if h:length() > 0 then utils.print("...") end end end -- enter the given tag for perf:tag function profiler:enter(name, ...) local is_perf_tag = self._IS_PERF_TAG if is_perf_tag == nil then is_perf_tag = self:is_perf("tag") self._IS_PERF_TAG = is_perf_tag end if is_perf_tag then local argv = table.pack(...) local report = self:_tag_report(name, argv) report.calltime = os.clock() report.callcount = report.callcount + 1 end end -- leave the given tag for perf:tag function profiler:leave(name, ...) local is_perf_tag = self._IS_PERF_TAG if is_perf_tag == nil then is_perf_tag = self:is_perf("tag") self._IS_PERF_TAG = is_perf_tag end if is_perf_tag then local stoptime = os.clock() local argv = table.pack(...) local report = self:_tag_report(name, argv) if report.calltime and report.calltime > 0 then report.totaltime = report.totaltime + (stoptime - report.calltime) report.calltime = 0 end end end -- get profiler mode, e.g. perf:call, perf:tag, trace function profiler:mode() local mode = self._MODE if mode == nil then mode = os.getenv("XMAKE_PROFILE") or false self._MODE = mode end return mode or nil end -- is trace? function profiler:is_trace() local mode = self:mode() return mode and mode == "trace" end -- is perf? function profiler:is_perf(name) local mode = self:mode() if mode and name then return mode == "perf:" .. name end end -- profiler is enabled? function profiler:enabled() return self:is_perf("call") or self:is_perf("tag") or self:is_trace() end -- return module return profiler
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/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 json.lua -- -- define module: json local json = json or {} -- load modules local io = require("base/io") local os = require("base/os") local utils = require("base/utils") -- export null json.purenull = {} setmetatable(json.purenull, { __is_json_null = true, __eq = function (obj) if type(obj) == "table" then local mt = getmetatable(obj) if mt and mt.__is_json_null then return true end end return false end, __tostring = function() return "null" end}) if cjson then json.null = cjson.null else json.null = json.purenull end function json._pure_kind_of(obj) if type(obj) ~= "table" then return type(obj) end if json.is_marked_as_array(obj) then return "array" end if obj == json.purenull then return "nil" end local i = 1 for _ in pairs(obj) do if obj[i] ~= nil then i = i + 1 else return "table" end end if i == 1 then return "table" else return "array" end end function json._pure_escape_str(s) local in_char = {'\\', '"', '/', '\b', '\f', '\n', '\r', '\t'} local out_char = {'\\', '"', '/', 'b', 'f', 'n', 'r', 't'} for i, c in ipairs(in_char) do s = s:gsub(c, '\\' .. out_char[i]) end return s end function json._pure_skip_delim(str, pos, delim, err_if_missing) pos = pos + #str:match('^%s*', pos) if str:sub(pos, pos) ~= delim then if err_if_missing then os.raise("expected %s near position %d", delim, pos) end return pos, false end return pos + 1, true end function json._pure_parse_str_val(str, pos, val) val = val or '' local early_end_error = "end of input found while parsing string." if pos > #str then os.raise(early_end_error) end local c = str:sub(pos, pos) if c == '"' then return val, pos + 1 end if c ~= '\\' then return json._pure_parse_str_val(str, pos + 1, val .. c) end -- we must have a \ character. local esc_map = {b = '\b', f = '\f', n = '\n', r = '\r', t = '\t'} local nextc = str:sub(pos + 1, pos + 1) if not nextc then os.raise(early_end_error) end return json._pure_parse_str_val(str, pos + 2, val .. (esc_map[nextc] or nextc)) end function json._pure_parse_num_val(str, pos) local num_str if str:sub(pos, pos + 1) == "0x" then num_str = str:match('^-?0[xX][0-9a-fA-F]+', pos) else num_str = str:match('^-?%d+%.?%d*[eE]?[+-]?%d*', pos) end local val = tonumber(num_str) if not val then os.raise("error parsing number at position %d", pos) end return val, pos + #num_str end function json._pure_stringify(obj, as_key) local s = {} local kind = json._pure_kind_of(obj) if kind == "array" then if as_key then os.raise("can\'t encode array as key.") end s[#s + 1] = '[' for i, val in ipairs(obj) do if i > 1 then s[#s + 1] = ',' end s[#s + 1] = json._pure_stringify(val) end s[#s + 1] = ']' elseif kind == "table" then if as_key then os.raise("can\'t encode table as key.") end s[#s + 1] = '{' for k, v in pairs(obj) do if #s > 1 then s[#s + 1] = ',' end s[#s + 1] = json._pure_stringify(k, true) s[#s + 1] = ':' s[#s + 1] = json._pure_stringify(v) end s[#s + 1] = '}' elseif kind == "string" then return '"' .. json._pure_escape_str(obj) .. '"' elseif kind == "number" then if as_key then return '"' .. tostring(obj) .. '"' end return tostring(obj) elseif kind == "boolean" then return tostring(obj) elseif kind == "nil" then return "null" else os.raise("unknown type: %s", kind) end return table.concat(s) end function json._pure_parse(str, pos, end_delim) pos = pos or 1 if pos > #str then os.raise("reached unexpected end of input.") end -- skip whitespace. local pos = pos + #str:match('^%s*', pos) local first = str:sub(pos, pos) if first == '{' then local obj, key, delim_found = {}, true, true pos = pos + 1 while true do key, pos = json._pure_parse(str, pos, '}') if key == nil then return obj, pos end if not delim_found then os.raise("comma missing between object items.") end pos = json._pure_skip_delim(str, pos, ':', true) -- true -> error if missing. obj[key], pos = json._pure_parse(str, pos) pos, delim_found = json._pure_skip_delim(str, pos, ',') end elseif first == '[' then local arr, val, delim_found = {}, true, true json.mark_as_array(arr) pos = pos + 1 while true do val, pos = json._pure_parse(str, pos, ']') if val == nil then return arr, pos end if not delim_found then os.raise("comma missing between array items.") end arr[#arr + 1] = val pos, delim_found = json._pure_skip_delim(str, pos, ',') end elseif first == '"' then return json._pure_parse_str_val(str, pos + 1) elseif first == '-' or first:match("%d") then return json._pure_parse_num_val(str, pos) elseif first == end_delim then -- end of an object or array. return nil, pos + 1 else local literals = {["true"] = true, ["false"] = false, ["null"] = json.purenull} for lit_str, lit_val in pairs(literals) do local lit_end = pos + #lit_str - 1 if str:sub(pos, lit_end) == lit_str then return lit_val, lit_end + 1 end end local pos_info_str = "position " .. pos .. ": " .. str:sub(pos, pos + 10) os.raise("invalid json syntax starting at " .. pos_info_str) end end -- decode json string using pure lua function json._pure_decode(jsonstr, opt) return json._pure_parse(jsonstr) end -- encode json string using pua lua function json._pure_encode(luatable, opt) return json._pure_stringify(luatable) end -- support empty array -- @see https://github.com/mpx/lua-cjson/issues/11 function json.mark_as_array(luatable) local mt = getmetatable(luatable) or {} mt.__is_cjson_array = true return setmetatable(luatable, mt) end -- is marked as array? function json.is_marked_as_array(luatable) local mt = getmetatable(luatable) return mt and mt.__is_cjson_array end -- decode json string to the lua table -- -- @param jsonstr the json string -- @param opt the options -- -- @return the lua table -- function json.decode(jsonstr, opt) local decode = cjson and cjson.decode or json._pure_decode if opt and opt.pure then decode = json._pure_decode end local ok, luatable_or_errors = utils.trycall(decode, nil, jsonstr) if not ok then return nil, string.format("decode json failed, %s", luatable_or_errors) end return luatable_or_errors end -- encode lua table to the json string -- -- @param luatable the lua table -- @param opt the options -- -- @return the json string -- function json.encode(luatable, opt) local encode = cjson and cjson.encode or json._pure_encode if opt and opt.pure then encode = json._pure_encode end local ok, jsonstr_or_errors = utils.trycall(encode, nil, luatable) if not ok then return nil, string.format("encode json failed, %s", jsonstr_or_errors) end return jsonstr_or_errors end -- load json file to the lua table -- -- @param filepath the json file path -- @param opt the options -- - encoding for io/file, e.g. utf8, utf16, utf16le, utf16be .. -- - continuation for io/read (concat string with the given continuation characters) -- -- @return the lua table -- function json.loadfile(filepath, opt) local filedata, errors = io.readfile(filepath, opt) if not filedata then return nil, errors end return json.decode(filedata, opt) end -- save lua table to the json file -- -- @param filepath the json file path -- @param luatable the lua table -- @param opt the options -- - encoding for io/file, e.g. utf8, utf16, utf16le, utf16be .. -- -- @return the json string -- function json.savefile(filepath, luatable, opt) local jsonstr, errors = json.encode(luatable, opt) if not jsonstr then return false, errors end return io.writefile(filepath, jsonstr, opt) end -- return module: json return json
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/math.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 math.lua -- -- define module local math = math or {} -- init constants math.nan = math.log(-1) math.e = math.exp(1) math.inf = 1/0 -- @see http://lua-users.org/wiki/InfAndNanComparisons -- check a number is int -- -- @returns true for int, otherwise false -- function math:isint() assert(type(self) == "number", "number expacted") return self == math.floor(self) and self ~= math.huge and self ~= -math.huge end -- check a number is inf or -inf -- -- @returns 1 for inf, -1 for -inf, otherwise false -- function math:isinf() assert(type(self) == "number", "number expacted") if self == math.inf then return 1 elseif self == -math.inf then return -1 else return false end end -- check a number is nan -- -- @returns true for nan, otherwise false -- function math:isnan() assert(type(self) == "number", "number expacted") return self ~= self end -- return module return math
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/task.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 task.lua -- -- define module: task local task = task or {} -- load modules local os = require("base/os") local table = require("base/table") local string = require("base/string") local global = require("base/global") local interpreter = require("base/interpreter") local sandbox = require("sandbox/sandbox") local config = require("project/config") local sandbox_os = require("sandbox/modules/os") function task.common_options() if not task._COMMON_OPTIONS then task._COMMON_OPTIONS = { {'q', "quiet", "k", nil, "Quiet operation." } , {'y', "yes", "k", nil, "Input yes by default if need user confirm." } , {nil, "confirm", "kv", nil, "Input the given result if need user confirm." , values = function () return {"yes", "no", "def"} end } , {'v', "verbose", "k", nil, "Print lots of verbose information for users." } , {nil, "root", "k", nil, "Allow to run xmake as root." } , {'D', "diagnosis", "k", nil, "Print lots of diagnosis information (backtrace, check info ..) only for developers." , "And we can append -v to get more whole information." , " e.g. $ xmake -vD" } , {'h', "help", "k", nil, "Print this help message and exit." } , {} , {'F', "file", "kv", nil, "Read a given xmake.lua file." } , {'P', "project", "kv", nil, "Change to the given project directory." , "Search priority:" , " 1. The Given Command Argument" , " 2. The Envirnoment Variable: XMAKE_PROJECT_DIR" , " 3. The Current Directory" } , {category = "action"} } end return task._COMMON_OPTIONS end -- the directories of tasks function task._directories() return {path.join(global.directory(), "plugins"), path.join(os.programdir(), "plugins"), path.join(os.programdir(), "actions")} end -- translate menu function task._translate_menu(menu) assert(menu) -- the interpreter local interp = task._interpreter() assert(interp) -- translate options local options = menu.options if options then -- make full options local options_full = {} for _, opt in ipairs(options) do -- this option is function? translate it if type(opt) == "function" then -- call menu script in the sandbox local ok, results = sandbox.load(opt) if ok then if results then for _, opt in ipairs(results) do table.insert(options_full, opt) end end else -- errors return nil, string.format("taskmenu: %s", results) end else table.insert(options_full, opt) end end -- update the options options = options_full menu.options = options_full -- filter options if interp:filter() then -- filter option for _, opt in ipairs(options) do -- filter default local default = opt[4] if type(default) == "string" then opt[4] = interp:filter():handle(default) end -- filter description for i = 5, 64 do -- the description, @note some option may be nil local description = opt[i] if not description then break end -- the description is string? if type(description) == "string" then opt[i] = interp:filter():handle(description) -- the description is function? wrap it for calling it in the sandbox elseif type(description) == "function" then opt[i] = function () -- call it in the sandbox local ok, results = sandbox.load(description) if not ok then -- errors return nil, string.format("taskmenu: %s", results) end -- ok return results end end end end end -- add common options, we need to avoid repeat because the main/build task will be inserted twice if not menu._common_options then for i, v in ipairs(task.common_options()) do table.insert(options, i, v) end menu._common_options = true end end -- ok return menu end -- the interpreter function task._interpreter() -- the interpreter has been initialized? return it directly if task._INTERPRETER then return task._INTERPRETER end -- init interpreter local interp = interpreter.new() assert(interp) -- define apis interp:api_define(task.apis()) -- set filter interp:filter():register("task", function (variable) -- check assert(variable) -- attempt to get it directly from the configure local result = config.get(variable) if not result or type(result) ~= "string" then -- init maps local maps = { host = os.host() , subhost = os.subhost() , tmpdir = function () return os.tmpdir() end , curdir = function () return os.curdir() end , scriptdir = function () return sandbox_os.scriptdir() end , globaldir = global.directory() , configdir = config.directory() , projectdir = os.projectdir() , programdir = os.programdir() } -- map it result = maps[variable] if type(result) == "function" then result = result() end end -- ok? return result end) -- save interpreter task._INTERPRETER = interp -- ok? return interp end -- bind script with a sandbox instance function task._bind_script(interp, script) -- make sandbox instance with the given script local instance, errors = sandbox.new(script, interp:filter(), interp:rootdir()) if not instance then return nil, errors end -- check assert(instance:script()) -- update option script return instance:script() end -- bind tasks for menu with a sandbox instance function task._bind(tasks, interp) -- check assert(tasks) -- get interpreter interp = interp or task._interpreter() assert(interp) -- bind sandbox for menus for _, taskinst in pairs(tasks) do -- has task menu? local taskmenu = taskinst:get("menu") if taskmenu then -- translate options local options = taskmenu.options if options then -- make full options local errors = nil local options_full = {} for _, opt in ipairs(options) do -- this option is function? translate it if type(opt) == "function" then opt, errors = task._bind_script(interp, opt) if not opt then return false, errors end end -- insert option table.insert(options_full, opt) end -- update the options options = options_full taskmenu.options = options_full -- bind sandbox for scripts in option for _, opt in ipairs(options) do -- bind description and values if type(opt) == "table" then -- bind description for i = 5, 64 do -- the description, @note some option may be nil local description = opt[i] if not description then break end -- the description is function? wrap it for calling it in the sandbox if type(description) == "function" then description, errors = task._bind_script(interp, description) if not description then return false, errors end opt[i] = description end end -- bind values if type(opt.values) == "function" then local values, errors = task._bind_script(interp, opt.values) if not values then return false, errors end opt.values = values end end end end end end -- ok return true end -- load the given task script file function task._load(filepath) -- get interpreter local interp = task._interpreter() assert(interp) -- load script local ok, errors = interp:load(filepath) if not ok and os.isfile(filepath) then return nil, errors end -- load tasks local tasks, errors = interp:make("task", true, true) if not tasks then return nil, errors end -- bind tasks for menu with an sandbox instance local ok, errors = task._bind(tasks) if not ok then return nil, errors end -- ok? return tasks end -- get task apis function task.apis() return { values = { -- task.set_xxx "task.set_category" -- main, action, plugin, task (default) } , dictionary = { -- task.set_xxx "task.set_menu" } , script = { -- task.on_xxx "task.on_run" } } end -- new a task instance function task.new(name, info) local instance = table.inherit(task) instance._NAME = name instance._INFO = info return instance end -- get global tasks function task.tasks() if task._TASKS then return task._TASKS end -- load tasks local tasks = {} local dirs = task._directories() for _, dir in ipairs(dirs) do local files = os.files(path.join(dir, "*", "xmake.lua")) if files then for _, filepath in ipairs(files) do local results, errors = task._load(filepath) if results then table.join2(tasks, results) else os.raise(errors) end end end end local instances = {} for taskname, taskinfo in pairs(tasks) do instances[taskname] = task.new(taskname, taskinfo) end task._TASKS = instances return instances end -- get the given global task function task.task(name) return task.tasks()[name] end -- the menu function task.menu(tasks) -- make menu local menu = {} for taskname, taskinst in pairs(tasks) do -- has task menu? local taskmenu = taskinst:get("menu") if taskmenu then if taskinst:get("category") == "main" then -- delay to load main menu menu.main = function () -- translate main menu local mainmenu, errors = task._translate_menu(taskmenu) if not mainmenu then os.raise(errors) end -- make tasks for the main menu mainmenu.tasks = {} for name, inst in pairs(tasks) do local m = inst:get("menu") if m then mainmenu.tasks[name] = { category = inst:get("category") , shortname = m.shortname , description = m.description } end end return mainmenu end end -- delay to load task menu menu[taskname] = function () local taskmenu, errors = task._translate_menu(taskmenu) if not taskmenu then os.raise(errors) end return taskmenu end end end -- ok? return menu end -- get the task info function task:get(name) return self._INFO:get(name) end -- get the task name function task:name() return self._NAME end -- run given task function task:run(...) -- check local on_run = self:get("run") if not on_run then return false, string.format("task(\"%s\"): no run script, please call on_run() first!", self:name()) end -- save the current directory local curdir = os.curdir() -- run task local ok, errors = sandbox.load(on_run, ...) -- restore the current directory os.cd(curdir) -- ok? return ok, errors end -- return module: task return task
0
repos/xmake/xmake/core
repos/xmake/xmake/core/base/dump.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 dump.lua -- -- define module local dump = dump or {} -- load modules local todisplay = require("base/todisplay") -- print string function dump._print_string(str, as_key) io.write(todisplay._print_string(str, as_key)) end -- print keyword function dump._print_keyword(keyword) io.write(todisplay._print_keyword(keyword)) end -- print function function dump._print_function(func, as_key) if as_key then io.write(todisplay._translate("${reset}${color.dump.function}"), todisplay._format("text.dump.default_format", "%s", func), todisplay._translate("${reset}")) else io.write(todisplay._print_function(func)) end end -- print scalar value function dump._print_scalar(value, as_key) if type(value) == "string" then dump._print_string(value, as_key) elseif type(value) == "function" then dump._print_function(value, as_key) else io.write(todisplay._print_scalar(value)) end end -- print anchor function dump._print_anchor(printed_set_value) io.write(todisplay._translate("${color.dump.anchor}"), todisplay._format("text.dump.anchor", "&%s", printed_set_value.id), todisplay._translate("${reset}")) end -- print reference function dump._print_reference(printed_set_value) io.write(todisplay._translate("${color.dump.reference}"), todisplay._format("text.dump.reference", "*%s", printed_set_value.id), todisplay._translate("${reset}")) end -- print anchor and store to printed_set function dump._print_table_anchor(value, printed_set) io.write(" ") if printed_set[value].id then dump._print_anchor(printed_set[value]) printed_set.refs[value] = printed_set[value] end end -- print metatable of value function dump._print_metatable(value, metatable, inner_indent, printed_set, print_archor) if not metatable then return false end -- print metamethods local has_record = false local has_index_table = false for k, v in pairs(metatable) do if k == "__index" and type(v) == "table" then has_index_table = true elseif k:startswith("__") then if not has_record then has_record = true if print_archor then dump._print_table_anchor(value, printed_set) end end io.write("\n", inner_indent) local funcname = k:sub(3) dump._print_keyword(funcname) io.write(todisplay._translate("${reset} ${dim}=${reset} ")) if funcname == "tostring" or funcname == "len" or funcname == "todisplay" then local ok, result = pcall(v, value, value) if ok then if funcname == "todisplay" and type(result) == "string" then io.write(todisplay._translate(result)) else dump._print_scalar(result) end io.write(todisplay._translate("${dim} (evaluated)${reset}")) else dump._print_scalar(v) end elseif v and printed_set.refs[v] then dump._print_reference(printed_set.refs[v]) else dump._print_scalar(v) end io.write(",") end end if not has_index_table then return has_record end -- print index methods local index_table = metatable and rawget(metatable, "__index") for k, v in pairs(index_table) do -- hide private interfaces if type(k) ~= "string" or not k:startswith("_") then if not has_record then has_record = true if print_archor then dump._print_table_anchor(value, printed_set) end end io.write("\n", inner_indent) dump._print_keyword("(") dump._print_scalar(k, true) dump._print_keyword(")") io.write(todisplay._translate("${reset} ${dim}=${reset} ")) if v and printed_set.refs[v] then dump._print_reference(printed_set.refs[v]) else dump._print_scalar(v) end io.write(",") end end return has_record end -- init printed_set function dump._init_printed_set(printed_set, value) assert(type(value) == "table") for k, v in pairs(value) do if type(v) == "table" then -- has reference? v -> printed_set[v].obj if printed_set[v] then local obj = printed_set[v].obj if not printed_set[obj].id then printed_set.id = printed_set.id + 1 printed_set[obj].id = printed_set.id end else printed_set[v] = {obj = v, name = k} dump._init_printed_set(printed_set, v) end end end end -- returns printed_set, is_first_level function dump._get_printed_set(printed_set, value) local first_level = not printed_set if type(printed_set) ~= "table" then printed_set = {id = 0, refs = {}} if type(value) == "table" then printed_set[value] = {obj = value} dump._init_printed_set(printed_set, value) end end return printed_set, first_level end -- print udata function dump._print_udata(value, first_indent, remain_indent, printed_set) local first_level local metatable = debug.getmetatable(value) printed_set, first_level = dump._get_printed_set(printed_set, metatable) io.write(first_indent) if not first_level then io.write(todisplay._print_udata_scalar(value)) end local inner_indent = remain_indent .. " " -- print open brackets io.write(todisplay._translate("${reset}${color.dump.udata}[${reset}")) -- print metatable local no_value = not dump._print_metatable(value, metatable, inner_indent, printed_set, false) -- print close brackets if no_value then io.write(todisplay._translate(" ${color.dump.udata}]${reset}")) else io.write("\b \n", remain_indent, todisplay._translate("${reset}${color.dump.udata}]${reset}")) end end -- print table function dump._print_table(value, first_indent, remain_indent, printed_set) local first_level printed_set, first_level = dump._get_printed_set(printed_set, value) io.write(first_indent) local metatable = debug.getmetatable(value) local tostringmethod = metatable and (rawget(metatable, "__todisplay") or rawget(metatable, "__tostring")) if not first_level and tostringmethod then return dump._print_scalar(value) end local inner_indent = remain_indent .. " " local first_value = true -- print open brackets io.write(todisplay._translate("${reset}${color.dump.table}{${reset}")) local function print_newline() if first_value then dump._print_table_anchor(value, printed_set) first_value = false end io.write("\n", inner_indent) end -- print metatable if first_level then first_value = not dump._print_metatable(value, metatable, inner_indent, printed_set, true) end -- print array items local is_arr = (value[1] ~= nil) and (table.maxn(value) < 2 * #value) if is_arr then for i = 1, table.maxn(value) do print_newline() local v = value[i] if type(v) == "table" then if printed_set.refs[v] then dump._print_reference(printed_set.refs[v]) else dump._print_table(v, "", inner_indent, printed_set) end else dump._print_scalar(v) end io.write(",") end end -- print data for k, v in pairs(value) do if not is_arr or type(k) ~= "number" then print_newline() dump._print_scalar(k, true) io.write(todisplay._translate("${reset} ${dim}=${reset} ")) if type(v) == "table" then if printed_set.refs[v] then dump._print_reference(printed_set.refs[v]) else dump._print_table(v, "", inner_indent, printed_set) end else dump._print_scalar(v) end io.write(",") end end -- print close brackets if first_value then io.write(todisplay._translate(" ${color.dump.table}}${reset}")) else io.write("\b \n", remain_indent, todisplay._translate("${reset}${color.dump.table}}${reset}")) end end -- print value function dump._print(value, indent, verbose) indent = tostring(indent or "") if type(value) == "table" then dump._print_table(value, indent, indent:gsub(".", " "), not verbose) elseif type(value) == "userdata" then dump._print_udata(value, indent, indent:gsub(".", " "), not verbose) else io.write(indent) dump._print_scalar(value) end io.write("\n") end return dump._print
0
repos/xmake/xmake/core/base
repos/xmake/xmake/core/base/private/is_cross.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file is_cross.lua -- -- load modules local os = require("base/os") -- is cross-compilation? function is_cross(plat, arch) plat = plat or os.subhost() arch = arch or os.subarch() local host_os = os.host() if host_os == "windows" then if plat == "windows" then local host_arch = os.arch() -- maybe cross-compilation for arm64 on x86/x64 if (host_arch == "x86" or host_arch == "x64") and arch == "arm64" then return true -- maybe cross-compilation for x86/64 on arm64 elseif host_arch == "arm64" and arch ~= "arm64" then return true end return false elseif plat == "mingw" then return false end end if plat ~= os.host() and plat ~= os.subhost() then return true end if arch ~= os.arch() and arch ~= os.subarch() then return true end return false end return is_cross
0
repos/xmake/xmake/core/base
repos/xmake/xmake/core/base/private/match_copyfiles.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 match_copyfiles.lua -- -- load modules local table = require("base/table") local utils = require("base/utils") local path = require("base/path") local os = require("base/os") -- match the copyfiles for instance -- e.g. -- -- add_headerfiles -- add_configfiles -- add_installfiles -- add_extrafiles function match_copyfiles(instance, filetype, outputdir, opt) opt = opt or {} -- get copyfiles? local copyfiles = opt.copyfiles or instance:get(filetype) if not copyfiles then return end -- get the extra information local extrainfo = table.wrap(instance:extraconf(filetype)) -- get the source paths and destinate paths local srcfiles = {} local dstfiles = {} local fileinfos = {} local srcfiles_removed = {} local removed_count = 0 for _, copyfile in ipairs(table.wrap(copyfiles)) do -- mark as removed files? local removed = false local prefix = "__remove_" if copyfile:startswith(prefix) then copyfile = copyfile:sub(#prefix + 1) removed = true end -- get the root directory local rootdir, count = copyfile:gsub("|.*$", ""):gsub("%(.*%)$", "") if count == 0 then rootdir = nil end if rootdir and rootdir:trim() == "" then rootdir = "." end -- remove '(' and ')' local srcpaths = copyfile:gsub("[%(%)]", "") if srcpaths then -- get the source paths srcpaths = os.match(srcpaths) if srcpaths and #srcpaths > 0 then if removed then removed_count = removed_count + #srcpaths table.join2(srcfiles_removed, srcpaths) else -- add the source copied files table.join2(srcfiles, srcpaths) -- the copied directory exists? if outputdir then -- get the file info local fileinfo = extrainfo[copyfile] or {} -- get the prefix directory local prefixdir = fileinfo.prefixdir if fileinfo.rootdir then rootdir = fileinfo.rootdir end -- add the destinate copied files for _, srcpath in ipairs(srcpaths) do -- get the destinate directory local dstdir = outputdir if prefixdir then dstdir = path.join(dstdir, prefixdir) end -- the destinate file local dstfile = nil if rootdir then dstfile = path.absolute(path.relative(srcpath, rootdir), dstdir) else dstfile = path.join(dstdir, path.filename(srcpath)) end assert(dstfile) -- modify filename if fileinfo.filename then dstfile = path.join(path.directory(dstfile), fileinfo.filename) end -- filter the destinate file path if opt.pathfilter then dstfile = opt.pathfilter(dstfile, fileinfo) end -- add it table.insert(dstfiles, dstfile) table.insert(fileinfos, fileinfo) end end end end end end -- remove all srcfiles which need be removed if removed_count > 0 then table.remove_if(srcfiles, function (i, srcfile) for _, removed_file in ipairs(srcfiles_removed) do local pattern = path.translate((removed_file:gsub("|.*$", ""))) if pattern:sub(1, 2):find('%.[/\\]') then pattern = pattern:sub(3) end pattern = path.pattern(pattern) if srcfile:match(pattern) then if i <= #dstfiles then table.remove(dstfiles, i) end return true end end end) end return srcfiles, dstfiles, fileinfos end return match_copyfiles
0
repos/xmake/xmake/core/base
repos/xmake/xmake/core/base/private/instance_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 instance_deps.lua -- -- define module local instance_deps = instance_deps or {} -- load modules local option = require("base/option") local string = require("base/string") local table = require("base/table") -- load deps for instance: e.g. option, instance and rule -- -- e.g. -- -- a.deps = b -- b.deps = c -- foo.deps = a d -- -- foo.orderdeps: d -> c -> b -> a -- -- if they're targets, their links order is reverse(orderdeps), e.g. foo: a -> b -> c -> d -- function instance_deps.load_deps(instance, instances, deps, orderdeps, depspath, walkdep) local plaindeps = table.wrap(instance:get("deps")) local total = #plaindeps for idx, _ in ipairs(plaindeps) do -- we reverse to get the flat dependencies in order to ensure the correct linking order -- @see https://github.com/xmake-io/xmake/issues/3144 local depname = plaindeps[total + 1 - idx] local depinst = instances[depname] if depinst then local continue_walk = true if walkdep then continue_walk = walkdep(instance, depinst) end if continue_walk then if not deps[depname] then deps[depname] = depinst local depspath_sub if depspath then for idx, name in ipairs(depspath) do if name == depname then local circular_deps = table.slice(depspath, idx) table.insert(circular_deps, depname) os.raise("circular dependency(%s) detected!", table.concat(circular_deps, ", ")) end end depspath_sub = table.join(depspath, depname) end instance_deps.load_deps(depinst, instances, deps, orderdeps, depspath_sub, walkdep) table.insert(orderdeps, depinst) end end end end end -- sort the given instance with deps function instance_deps._sort_instance(instance, instances, orderinstances, instancerefs, depspath) if not instancerefs[instance:name()] then instancerefs[instance:name()] = true for _, depname in ipairs(table.wrap(instance:get("deps"))) do local depinst = instances[depname] if depinst then local depspath_sub if depspath then for idx, name in ipairs(depspath) do if name == depname then local circular_deps = table.slice(depspath, idx) table.insert(circular_deps, depname) os.raise("circular dependency(%s) detected!", table.concat(circular_deps, ", ")) end end depspath_sub = table.join(depspath, depname) end instance_deps._sort_instance(depinst, instances, orderinstances, instancerefs, depspath_sub) end end table.insert(orderinstances, instance) end end -- sort instances with deps -- -- e.g. -- -- a.deps = b -- b.deps = c -- foo.deps = a d -- -- orderdeps: c -> b -> a -> d -> foo function instance_deps.sort(instances) local refs = {} local orderinstances = {} for _, instance in table.orderpairs(instances) do instance_deps._sort_instance(instance, instances, orderinstances, refs, {instance:name()}) end return orderinstances end -- return module return instance_deps
0
repos/xmake/xmake/core/base
repos/xmake/xmake/core/base/private/select_script.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 select_script.lua -- -- load modules local table = require("base/table") local utils = require("base/utils") local hashset = require("base/hashset") -- match pattern, matched mode: plat|arch, excluded mode: !plat|arch function _match_pattern(pattern, plat, arch, opt) opt = opt or {} local excluded = opt.excluded local subhost = opt.subhost or os.subhost() local subarch = opt.subarch or os.subarch() local splitinfo = pattern:split("|", {strict = true, plain = true}) local pattern_plat = splitinfo[1] local pattern_arch = splitinfo[2] if pattern_plat and #pattern_plat > 0 then local matched = false local is_excluded_pattern = pattern_plat:find('!', 1, true) if excluded and is_excluded_pattern then matched = not ('!' .. plat):match('^' .. pattern_plat .. '$') elseif not is_excluded_pattern then matched = plat:match('^' .. pattern_plat .. '$') end if not matched then return false end end if pattern_arch and #pattern_arch > 0 then -- support native arch, e.g. macosx|native -- @see https://github.com/xmake-io/xmake/issues/4657 pattern_arch = pattern_arch:gsub("native", subarch) local matched = false local is_excluded_pattern = pattern_arch:find('!', 1, true) if excluded and is_excluded_pattern then matched = not ('!' .. arch):match('^' .. pattern_arch .. '$') elseif not is_excluded_pattern then matched = arch:match('^' .. pattern_arch .. '$') end if not matched then return false end end if not pattern_plat and not pattern_arch then os.raise("invalid script pattern: %s", pattern) end return true end -- match patterns function _match_patterns(patterns, plat, arch, opt) for _, pattern in ipairs(patterns) do if _match_pattern(pattern, plat, arch, opt) then return true end end end -- mattch the script pattern -- -- @note interpreter has converted pattern to a lua pattern ('*' => '.*') -- -- matched pattern: -- plat|arch@subhost|subarch -- -- e.g. -- -- `@linux` -- `@linux|x86_64` -- `@macosx,linux` -- `android@macosx,linux` -- `android|armeabi-v7a@macosx,linux` -- `android|armeabi-v7a,iphoneos@macosx,linux|x86_64` -- `android|armeabi-v7a@linux|x86_64` -- `linux|*` -- -- excluded pattern: -- !plat|!arch@!subhost|!subarch -- -- e.g. -- -- `@!linux` -- `@!linux|x86_64` -- `@!macosx,!linux` -- `!android@macosx,!linux` -- `android|!armeabi-v7a@macosx,!linux` -- `android|armeabi-v7a,!iphoneos@macosx,!linux|x86_64` -- `!android|armeabi-v7a@!linux|!x86_64` -- `!linux|*` -- function _match_script_pattern(pattern, opt) opt = opt or {} local splitinfo = pattern:split("@", {strict = true, plain = true}) local plat_part = splitinfo[1] local host_part = splitinfo[2] local plat_patterns if plat_part and #plat_part > 0 then plat_patterns = plat_part:split(",", {plain = true}) end local host_patterns if host_part and #host_part > 0 then host_patterns = host_part:split(",", {plain = true}) end local plat = opt.plat or "" local arch = opt.arch or "" local subhost = opt.subhost or os.subhost() local subarch = opt.subarch or os.subarch() if plat_patterns and #plat_patterns > 0 then if _match_patterns(plat_patterns, plat, arch, opt) then if host_patterns and #host_patterns > 0 and not _match_patterns(host_patterns, subhost, subarch, opt) then return false end return true end else if host_patterns and #host_patterns > 0 then return _match_patterns(host_patterns, subhost, subarch, opt) end end end -- match the script expression pattern -- -- e.g. -- !wasm|!arm* and !cross|!arm* -- wasm|!arm* or cross -- (!macosx and !iphoneos) or (!linux|!arm* and !cross|!arm*) -- function _match_script(pattern, opt) local idx = 0 local funcs = {} local keywords = hashset.of("and", "or") local has_logical_op = false local pattern_expr = pattern:gsub("[^%(%)%s]+", function (w) if keywords:has(w) then has_logical_op = true return end local name = "func_" .. idx local func = function () return _match_script_pattern(w, opt) end funcs[name] = func idx = idx + 1 return name .. "()" end) if has_logical_op then local script = assert(load("return (" .. pattern_expr .. ")"), "invalid pattern: " .. pattern) setfenv(script, funcs) local ok, results = utils.trycall(script) if not ok then os.raise("invalid pattern: %s, error: %s", pattern, results or "unknown") end return results else return _match_script_pattern(pattern, opt) end end -- select the matched pattern script for the current platform/architecture function select_script(scripts, opt) opt = opt or {} local result = nil if type(scripts) == "function" then result = scripts elseif type(scripts) == "table" then local script_matched for pattern, script in pairs(scripts) do if not pattern:startswith("__") and _match_script(pattern, opt) then script_matched = script break end end if not script_matched then local scripts_fallback = {} local patterns_fallback = {} local excluded_opt = table.join(opt, {excluded = true}) for pattern, script in pairs(scripts) do if not pattern:startswith("__") and _match_script(pattern, excluded_opt) then table.insert(scripts_fallback, script) table.insert(patterns_fallback, pattern) end end script_matched = scripts_fallback[1] if script_matched and #scripts_fallback > 0 then local conflict_patterns = {patterns_fallback[1]} for idx, script in ipairs(scripts_fallback) do local pattern = patterns_fallback[idx] if script ~= script_matched then table.insert(conflict_patterns, pattern) end end if #conflict_patterns > 1 then utils.warning("multiple script patterns are matched, %s", table.concat(conflict_patterns, ", ")) end end end result = script_matched or scripts["__generic__"] end return result end return select_script
0
repos/xmake/xmake/core/base
repos/xmake/xmake/core/base/compat/env.lua
-- (c) 2012 David Manura. Licensed under the same terms as Lua 5.1/5.2 (MIT license). -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- @author David Manura, ruki -- @file env.lua -- -- define module: env local env = env or {} -- from https://github.com/davidm/lua-inspect/blob/master/lib/luainspect/compat_env.lua if _G.setfenv then -- Lua 5.1 env.setfenv = _G.setfenv env.getfenv = _G.getfenv else -- >= Lua 5.2 -- helper function for `getfenv`/`setfenv` local function envlookup(f) local name, val local up = 0 local unknown repeat up = up + 1; name, val = debug.getupvalue(f, up) if name == '' then unknown = true end until name == '_ENV' or name == nil if name ~= '_ENV' then up = nil if unknown then error("upvalues not readable in Lua 5.2 when debug info missing", 3) end end return (name == '_ENV') and up, val, unknown end -- helper function for `getfenv`/`setfenv` local function envhelper(f, name) if type(f) == 'number' then if f < 0 then error(("bad argument #1 to '%s' (level must be non-negative)"):format(name), 3) elseif f < 1 then error("thread environments unsupported in Lua 5.2", 3) --[*] end f = debug.getinfo(f+2, 'f').func elseif type(f) ~= 'function' then error(("bad argument #1 to '%s' (number expected, got %s)"):format(type(name, f)), 2) end return f end -- [*] might simulate with table keyed by coroutine.running() -- 5.1 style `setfenv` implemented in 5.2 function env.setfenv(f, t) local f = envhelper(f, 'setfenv') local up, val, unknown = envlookup(f) if up then debug.upvaluejoin(f, up, function() return up end, 1) -- unique upvalue [*] debug.setupvalue(f, up, t) else local what = debug.getinfo(f, 'S').what if what ~= 'Lua' and what ~= 'main' then -- not Lua func error("'setfenv' cannot change environment of given object", 2) end -- else ignore no _ENV upvalue (warning: incompatible with 5.1) end end -- [*] http://lua-users.org/lists/lua-l/2010-06/msg00313.html -- 5.1 style `getfenv` implemented in 5.2 function env.getfenv(f) if f == 0 or f == nil then return _G end -- simulated behavior local f = envhelper(f, 'setfenv') local up, val = envlookup(f) if not up then return _G end -- simulated behavior [**] return val end -- [**] possible reasons: no _ENV upvalue, C function -- register to global _G.setfenv = env.setfenv _G.getfenv = env.getfenv debug.setfenv = env.setfenv debug.getfenv = env.getfenv end -- return module: env return env
0
repos/xmake/xmake/core/base
repos/xmake/xmake/core/base/compat/bit.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 bit.lua -- -- define module: bit local bit = bit or {} -- bit/and operation function bit.band(a, b) return a & b end -- bit/or operation function bit.bor(a, b) return a | b end -- bit/xor operation function bit.bxor(a, b) return a ~ b end -- bit/not operation function bit.bnot(a) return ~a end -- bit/lshift operation function bit.lshift(a, b) return a << b end -- bit/rshift operation function bit.rshift(a, b) return a >> b end -- tobit operation function bit.tobit(x) return x & 0xffffffff end -- tohex operation function bit.tohex(x, n) n = n or 8 local up if n <= 0 then if n == 0 then return '' end up = true n = - n end x = x & (16 ^ n - 1) return ('%0'..n..(up and 'X' or 'x')):format(x) end -- return module: bit return bit
0
repos/xmake/xmake/core
repos/xmake/xmake/core/language/menu.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 menu.lua -- -- define module local menu = menu or {} -- load modules local os = require("base/os") local path = require("base/path") local utils = require("base/utils") local table = require("base/table") local language = require("language/language") -- get the option menu for action: xmake config or global function menu.options(action) -- check assert(action) -- load all languages local languages, errors = language.load() if not languages then os.raise(errors) end -- load and merge all language options local exist = {} local results = {} for _, instance in pairs(languages) do -- get menu local menu = instance:menu() if menu then -- get the options for this action local options = menu[action] if options then -- get the language option for _, option in ipairs(options) do -- merge it and remove repeat local name = option[2] or option[1] if name then if not exist[name] then table.insert(results, option) exist[name] = true end else table.insert(results, option) end end end end end -- ok? return results end -- return module return menu
0
repos/xmake/xmake/core
repos/xmake/xmake/core/language/language.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 language.lua -- -- define module local language = language or {} local _instance = _instance or {} -- load modules local os = require("base/os") local path = require("base/path") local utils = require("base/utils") local table = require("base/table") local interpreter = require("base/interpreter") local sandbox = require("sandbox/sandbox") local config = require("project/config") local global = require("base/global") -- new an instance function _instance.new(name, info, rootdir) local instance = table.inherit(_instance) instance._NAME = name instance._INFO = info instance._ROOTDIR = rootdir return instance end -- get the language configure function _instance:get(name) local info = self._INFO:info() local value = info[name] if value ~= nil then return value end if self._g == nil and info.load ~= nil then local ok, results = sandbox.load(info.load) if not ok then os.raise(results) end self._g = results end return self._g[name] end -- get the language menu function _instance:menu() return self._INFO:get("menu") end -- get the language name function _instance:name() return self._NAME end -- get the source extensions function _instance:extensions() if self._EXTENSIONS then return self._EXTENSIONS end -- get extensions local extensions = {} for sourcekind, exts in pairs(self:sourcekinds()) do for _, extension in ipairs(table.wrap(exts)) do extensions[extension:lower()] = sourcekind end end self._EXTENSIONS = extensions return extensions end -- get the rules function _instance:rules() return self._INFO:get("rules") end -- get the source kinds function _instance:sourcekinds() return self._INFO:get("sourcekinds") end -- get the source flags function _instance:sourceflags() return self._INFO:get("sourceflags") end -- get the target kinds (targetkind => linkerkind) -- -- e.g. -- {binary = "ld", static = "ar", shared = "sh"} -- function _instance:kinds() return self._INFO:get("targetkinds") end -- get the target flags (targetkind => linkerflag) -- -- e.g. -- {binary = "ldflags", static = "arflags", shared = "shflags"} -- function _instance:targetflags() return self._INFO:get("targetflags") end -- get the mixing kinds for linker -- -- e.g. -- {"cc", "cxx"} -- function _instance:mixingkinds() return self._INFO:get("mixingkinds") end -- get the language kinds function _instance:langkinds() return self._INFO:get("langkinds") end -- get the name flags function _instance:nameflags() -- attempt to get it from cache first if self._NAMEFLAGS then return self._NAMEFLAGS end -- get nameflags local results = {} for targetkind, nameflags in pairs(table.wrap(self._INFO:get("nameflags"))) do -- make tool info local toolinfo = results[targetkind] or {} for _, namedflag in ipairs(nameflags) do -- split it by '.' local splitinfo = namedflag:split('.', {plain = true}) assert(#splitinfo == 2) -- get flag scope local flagscope = splitinfo[1] assert(flagscope) -- get flag info local flaginfo = splitinfo[2]:split(':') -- get flag name local flagname = flaginfo[1] assert(flagname) -- get check state local checkstate = false if #flaginfo == 2 and flaginfo[2] == "check" then checkstate = true end -- insert this flag info table.insert(toolinfo, {flagscope, flagname, checkstate}) end -- save this tool info results[targetkind] = toolinfo end -- cache this results self._NAMEFLAGS = results return results end -- the directory of language function language._directory() return path.join(os.programdir(), "languages") end -- the interpreter function language._interpreter() -- the interpreter has been initialized? return it directly if language._INTERPRETER then return language._INTERPRETER end -- init interpreter local interp = interpreter.new() assert(interp) -- define apis interp:api_define { values = { -- language.set_xxx "language.set_mixingkinds" -- language.add_xxx , "language.add_rules" } , script = { -- language.on_xxx "language.on_load" , "language.on_check_main" } , dictionary = { -- language.set_xxx "language.set_menu" , "language.set_nameflags" , "language.set_langkinds" , "language.set_sourcekinds" , "language.set_sourceflags" , "language.set_targetkinds" , "language.set_targetflags" } } language._INTERPRETER = interp return interp end -- load the language from the given name (c++, objc++, swift, golang, asm, ...) function language.load(name) -- load all languages if not name then if not language._LANGUAGES then for _, name in ipairs(table.wrap(os.dirs(path.join(language._directory(), "*")))) do local instance, errors = language.load(path.basename(name)) if not instance then return nil, errors end end end return language._LANGUAGES end -- get it directly from cache dirst language._LANGUAGES = language._LANGUAGES or {} if language._LANGUAGES[name] then return language._LANGUAGES[name] end -- find the language script path local scriptpath = path.join(path.join(language._directory(), name), "xmake.lua") if not os.isfile(scriptpath) then return nil, string.format("the language %s not found!", name) end -- not exists? if not scriptpath or not os.isfile(scriptpath) then return nil, string.format("the language %s not found!", name) end -- get interpreter local interp = language._interpreter() -- load script local ok, errors = interp:load(scriptpath) if not ok then return nil, errors end -- load language local results, errors = interp:make("language", true, false) if not results and os.isfile(scriptpath) then return nil, errors end -- check the language name if not results[name] then return nil, string.format("the language %s not found!", name) end -- new an instance local instance, errors = _instance.new(name, results[name], language._interpreter():rootdir()) if not instance then return nil, errors end language._LANGUAGES[name] = instance return instance end -- load the language from the given source kind: cc, cxx, mm, mxx, sc, gc, as .. function language.load_sk(sourcekind) -- load all languages local languages, errors = language.load() if not languages then return nil, errors end -- make source kind as lower sourcekind = sourcekind:lower() -- get it directly from cache dirst language._LANGUAGES_OF_SK = language._LANGUAGES_OF_SK or {} if language._LANGUAGES_OF_SK[sourcekind] then return language._LANGUAGES_OF_SK[sourcekind] end -- find language instance local result = nil for _, instance in pairs(languages) do if instance:sourcekinds()[sourcekind] ~= nil then result = instance break end end if not result then return nil, string.format("unknown language sourcekind: %s", sourcekind) end language._LANGUAGES_OF_SK[sourcekind] = result return result end -- load the language from the given source extension: .c, .cpp, .m, .mm, .swift, .go, .s .. function language.load_ex(extension) -- load all languages local languages, errors = language.load() if not languages then return nil, errors end -- make source extension as lower extension = extension:lower() -- get it directly from cache dirst language._LANGUAGES_OF_EX = language._LANGUAGES_OF_EX or {} if language._LANGUAGES_OF_EX[extension] then return language._LANGUAGES_OF_EX[extension] end -- find language instance local result = nil for _, instance in pairs(languages) do if instance:extensions()[extension] ~= nil then result = instance break end end if not result then return nil, string.format("unknown language source extension: %s", extension) end language._LANGUAGES_OF_EX[extension] = result return result end -- load the language apis function language.apis() local apis = language._APIS if not apis then local languages, errors = language.load() if not languages then os.raise(errors) end apis = {values = {}, groups = {}, paths = {}, custom = {}, dictionary = {}} for name, instance in pairs(languages) do local instance_apis = instance:get("apis") if instance_apis then table.join2(apis.values, table.wrap(instance_apis.values)) table.join2(apis.groups, table.wrap(instance_apis.groups)) table.join2(apis.paths, table.wrap(instance_apis.paths)) table.join2(apis.custom, table.wrap(instance_apis.custom)) table.join2(apis.dictionary, table.wrap(instance_apis.dictionary)) end end apis.values = table.unique(apis.values) apis.groups = table.unique(apis.groups) apis.paths = table.unique(apis.paths) apis.custom = table.unique(apis.custom) language._APIS = apis end return apis end -- get language source extensions -- -- e.g. -- -- { -- [".c"] = cc -- , [".cc"] = cxx -- , [".cpp"] = cxx -- , [".m"] = mm -- , [".mm"] = mxx -- , [".swift"] = sc -- , [".go"] = gc -- } -- function language.extensions() local extensions = language._EXTENSIONS if not extensions then local languages, errors = language.load() if not languages then os.raise(errors) end extensions = {} for name, instance in pairs(languages) do table.join2(extensions, instance:extensions()) end language._EXTENSIONS = extensions end return extensions end -- get language source kinds -- -- e.g. -- -- { -- cc = ".c" -- , cxx = {".cc", ".cpp", ".cxx"} -- , mm = ".m" -- , mxx = ".mm" -- , sc = ".swift" -- , gc = ".go" -- } -- function language.sourcekinds() local sourcekinds = language._SOURCEKINDS if not sourcekinds then local languages, errors = language.load() if not languages then os.raise(errors) end sourcekinds = {} for name, instance in pairs(languages) do table.join2(sourcekinds, instance:sourcekinds()) end language._SOURCEKINDS = sourcekinds end return sourcekinds end -- get language source flags -- -- e.g. -- -- { -- cc = {"cflags", "cxflags"} -- , cxx = {"cxxflags", "cxflags"} -- , ... -- } -- function language.sourceflags() local sourceflags = language._SOURCEFLAGS if not sourceflags then local languages, errors = language.load() if not languages then os.raise(errors) end sourceflags = {} for name, instance in pairs(languages) do table.join2(sourceflags, instance:sourceflags()) end language._SOURCEFLAGS = sourceflags end return sourceflags end -- get source kind of the source file name function language.sourcekind_of(sourcefile) -- get the source file extension local extension = path.extension(sourcefile) if not extension then return nil, string.format("%s has not extension", sourcefile) end -- get extensions local extensions = language.extensions() -- get source kind from extension local sourcekind = extensions[extension:lower()] if not sourcekind then return nil, string.format("%s is unknown extension", extension) end return sourcekind end -- get extension of the source kind function language.extension_of(sourcekind) local extension = table.wrap(language.sourcekinds()[sourcekind])[1] if not extension then return nil, string.format("%s is unknown source kind", sourcekind) end return extension end -- get linker infos(kind and flag) of the target kind and the source kinds function language.linkerinfos_of(targetkind, sourcekinds) -- load linkerinfos local linkerinfos = language._LINKERINFOS if not linkerinfos then -- load all languages local languages, errors = language.load() if not languages then return nil, errors end -- make linker infos linkerinfos = {} for name, instance in pairs(languages) do for _, mixingkind in ipairs(table.wrap(instance:mixingkinds())) do local targetflags = instance:targetflags() for _targetkind, linkerkind in pairs(table.wrap(instance:kinds())) do -- init linker info linkerinfos[_targetkind] = linkerinfos[_targetkind] or {} linkerinfos[_targetkind][linkerkind] = linkerinfos[_targetkind][linkerkind] or {} local linkerinfo = linkerinfos[_targetkind][linkerkind] -- sve linker info local linkerflag = targetflags[_targetkind] linkerinfo.linkerkind = linkerkind if linkerflag then linkerinfo.linkerflag = linkerflag end linkerinfo.mixingkinds = linkerinfo.mixingkinds or {} linkerinfo.mixingkinds[mixingkind] = 1 linkerinfo.sourcecount = (linkerinfo.sourcecount or 0) + 1 end end end language._LINKERINFOS = linkerinfos end -- find suitable linkers local results = {} for _, linkerinfo in pairs(table.wrap(linkerinfos[targetkind])) do -- match all source kinds? local count = 0 for _, sourcekind in ipairs(sourcekinds) do count = count + (linkerinfo.mixingkinds[sourcekind] or 0) end if count == #sourcekinds then table.insert(results, linkerinfo) end end if #results > 0 then -- sort it by most matches table.sort(results, function(a, b) return a.sourcecount > b.sourcecount end) return results end -- not suitable linker return nil, string.format("no suitable linker for %s.{%s}", targetkind, table.concat(sourcekinds, ' ')) end -- get language target kinds -- -- e.g. -- -- { -- binary = {"ld", "gcld", "dcld"} -- , static = {"ar", "gcar", "dcar"} -- , shared = {"sh", "dcsh"} -- } -- function language.targetkinds() local targetkinds = language._TARGETKINDS if not targetkinds then local languages, errors = language.load() if not languages then os.raise(errors) end targetkinds = {} for name, instance in pairs(languages) do for targetkind, linkerkind in pairs(table.wrap(instance:kinds())) do targetkinds[targetkind] = targetkinds[targetkind] or {} table.insert(targetkinds[targetkind], linkerkind) end end for targetkind, linkerkinds in pairs(targetkinds) do targetkinds[targetkind] = table.unique(linkerkinds) end language._TARGETKINDS = targetkinds end return targetkinds end -- get language kinds (langkind => sourcekind) -- -- e.g. -- -- { -- c = "cc" -- , cxx = "cxx" -- , m = "mm" -- , mxx = "mxx" -- , swift = "sc" -- , go = "gc" -- , as = "as" -- , rust = "rc" -- , d = "dc" -- } -- function language.langkinds() local langkinds = language._LANGKINDS if not langkinds then local languages, errors = language.load() if not languages then os.raise(errors) end langkinds = {} for name, instance in pairs(languages) do table.join2(langkinds, instance:langkinds()) end language._LANGKINDS = langkinds end return langkinds end return language
0
repos/xmake/xmake/core
repos/xmake/xmake/core/compress/lz4.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 lz4.lua -- -- define module: lz4 local lz4 = lz4 or {} local _cstream = _cstream or {} local _dstream = _dstream or {} -- load modules local io = require("base/io") local utils = require("base/utils") local bytes = require("base/bytes") local table = require("base/table") -- save metatable and builtin functions lz4._compress = lz4._compress or lz4.compress lz4._decompress = lz4._decompress or lz4.decompress lz4._block_compress = lz4._block_compress or lz4.block_compress lz4._block_decompress = lz4._block_decompress or lz4.block_decompress lz4._compress_file = lz4._compress_file or lz4.compress_file lz4._decompress_file = lz4._decompress_file or lz4.decompress_file lz4._compress_stream_open = lz4._compress_stream_open or lz4.compress_stream_open lz4._compress_stream_read = lz4._compress_stream_read or lz4.compress_stream_read lz4._compress_stream_write = lz4._compress_stream_write or lz4.compress_stream_write lz4._compress_stream_close = lz4._compress_stream_close or lz4.compress_stream_close lz4._decompress_stream_open = lz4._decompress_stream_open or lz4.decompress_stream_open lz4._decompress_stream_read = lz4._decompress_stream_read or lz4.decompress_stream_read lz4._decompress_stream_write = lz4._decompress_stream_write or lz4.decompress_stream_write lz4._decompress_stream_close = lz4._decompress_stream_close or lz4.decompress_stream_close -- new a compress stream function _cstream.new(handle) local instance = table.inherit(_cstream) instance._HANDLE = handle setmetatable(instance, _cstream) return instance end -- get cdata of stream function _cstream:cdata() return self._HANDLE end -- read data from stream function _cstream:read(buff, size, opt) assert(buff) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- check buffer size = size or buff:size() if buff:size() < size then return -1, string.format("%s: too small buffer!", self) end -- check size if size == 0 then return 0 elseif size == nil or size < 0 then return -1, string.format("%s: invalid size(%d)!", self, size) end -- init start in buffer opt = opt or {} local start = opt.start or 1 local pos = start - 1 if start >= buff:size() or start < 1 then return -1, string.format("%s: invalid start(%d)!", self, start) end -- read it local read, data_or_errors = lz4._compress_stream_read(self:cdata(), buff:caddr() + pos, math.min(buff:size() - pos, size)) if read > 0 then data_or_errors = buff:slice(start, read) end if read < 0 and data_or_errors then data_or_errors = string.format("%s: %s", self, data_or_errors) end return read, data_or_errors end -- write data to stream function _cstream:write(data, opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- get data address and size for bytes and string if type(data) == "string" then data = bytes(data) end local datasize = data:size() local dataaddr = data:caddr() -- init start and last opt = opt or {} local start = opt.start or 1 local last = opt.last or datasize if start < 1 or start > datasize then return -1, string.format("%s: invalid start(%d)!", self, start) end if last < start - 1 or last > datasize + start - 1 then return -1, string.format("%s: invalid last(%d)!", self, last) end -- write it local errors = nil local write, errors = lz4._compress_stream_write(self:cdata(), dataaddr + start - 1, last + 1 - start, opt.beof) if write < 0 and errors then errors = string.format("%s: %s", self, errors) end return write, errors end -- ensure it is opened function _cstream:_ensure_opened() if not self:cdata() then return false, string.format("%s: has been closed!", self) end return true end -- tostring(stream) function _cstream:__tostring() return string.format("<lz4/cstream: %s>", self:cdata()) end -- gc(stream) function _cstream:__gc() if self:cdata() and lz4._compress_stream_close(self:cdata()) then self._HANDLE = nil end end -- new a decompress stream function _dstream.new(handle) local instance = table.inherit(_dstream) instance._HANDLE = handle setmetatable(instance, _dstream) return instance end -- get cdata of stream function _dstream:cdata() return self._HANDLE end -- read data from stream function _dstream:read(buff, size, opt) assert(buff) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- check buffer size = size or buff:size() if buff:size() < size then return -1, string.format("%s: too small buffer!", self) end -- check size if size == 0 then return 0 elseif size == nil or size < 0 then return -1, string.format("%s: invalid size(%d)!", self, size) end -- init start in buffer opt = opt or {} local start = opt.start or 1 local pos = start - 1 if start >= buff:size() or start < 1 then return -1, string.format("%s: invalid start(%d)!", self, start) end -- read it local read, data_or_errors = lz4._decompress_stream_read(self:cdata(), buff:caddr() + pos, math.min(buff:size() - pos, size)) if read > 0 then data_or_errors = buff:slice(start, read) end if read < 0 and data_or_errors then data_or_errors = string.format("%s: %s", self, data_or_errors) end return read, data_or_errors end -- write data to stream function _dstream:write(data, opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return -1, errors end -- get data address and size for bytes and string if type(data) == "string" then data = bytes(data) end local datasize = data:size() local dataaddr = data:caddr() -- init start and last opt = opt or {} local start = opt.start or 1 local last = opt.last or datasize if start < 1 or start > datasize then return -1, string.format("%s: invalid start(%d)!", self, start) end if last < start - 1 or last > datasize + start - 1 then return -1, string.format("%s: invalid last(%d)!", self, last) end -- write it local errors = nil local write, errors = lz4._decompress_stream_write(self:cdata(), dataaddr + start - 1, last + 1 - start, opt.beof) if write < 0 and errors then errors = string.format("%s: %s", self, errors) end return write, errors end -- ensure it is opened function _dstream:_ensure_opened() if not self:cdata() then return false, string.format("%s: has been closed!", self) end return true end -- tostring(stream) function _dstream:__tostring() return string.format("<lz4/dstream: %s>", self:cdata()) end -- gc(stream) function _dstream:__gc() if self:cdata() and lz4._decompress_stream_close(self:cdata()) then self._HANDLE = nil end end -- open a compress stream function lz4.compress_stream(opt) local handle, errors = lz4._compress_stream_open() if handle then return _cstream.new(handle) else return nil, errors or "failed to open compress stream!" end end -- open a decompress stream function lz4.decompress_stream(opt) local handle, errors = lz4._decompress_stream_open() if handle then return _dstream.new(handle) else return nil, errors or "failed to open decompress stream!" end end -- compress frame data -- -- @param data the data -- @param opt the options -- -- @return the result data -- function lz4.compress(data, opt) if type(data) == "string" then data = bytes(data) end local datasize = data:size() local dataaddr = data:caddr() local result, errors = lz4._compress(dataaddr, datasize) if not result then return nil, errors or string.format("compress frame data failed, %s", errors or "unknown") end return bytes(result) end -- decompres frame data -- -- @param data the data -- @param opt the options -- -- @return the result data -- function lz4.decompress(data, opt) if type(data) == "string" then data = bytes(data) end local datasize = data:size() local dataaddr = data:caddr() local result, errors = lz4._decompress(dataaddr, datasize) if not result then return nil, string.format("decompress frame data failed, %s", errors or "unknown") end return bytes(result) end -- compress file data function lz4.compress_file(srcpath, dstpath, opt) local ok, errors = lz4._compress_file(tostring(srcpath), tostring(dstpath)) if not ok then errors = string.format("compress file %s failed!", srcpath, errors or os.strerror() or "unknown") end return ok, errors end -- decompress file data function lz4.decompress_file(srcpath, dstpath, opt) local ok, errors = lz4._decompress_file(tostring(srcpath), tostring(dstpath)) if not ok then errors = string.format("decompress file %s failed!", srcpath, errors or os.strerror() or "unknown") end return ok, errors end -- compress block data -- -- @param data the data -- @param opt the options -- -- @return the result data -- function lz4.block_compress(data, opt) if type(data) == "string" then data = bytes(data) end local datasize = data:size() local dataaddr = data:caddr() local result, errors = lz4._block_compress(dataaddr, datasize) if not result then return nil, errors or string.format("compress block data failed, %s", errors or "unknown") end return bytes(result) end -- decompres block data -- -- @param data the data -- @param realsize the decompressed real size -- @param opt the options -- -- @return the result data -- function lz4.block_decompress(data, realsize, opt) local datasize = data:size() local dataaddr = data:caddr() local result, errors = lz4._block_decompress(dataaddr, datasize, realsize) if not result then return nil, string.format("decompress block data failed, %s", errors or "unknown") end return bytes(result) end -- return module: lz4 return lz4
0
repos/xmake/xmake/core
repos/xmake/xmake/core/platform/menu.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 menu.lua -- -- define module local menu = menu or {} -- load modules local os = require("base/os") local path = require("base/path") local utils = require("base/utils") local table = require("base/table") local config = require("project/config") local platform = require("platform/platform") -- the remote build client is connected? -- -- this implementation is from remote_build_client.is_connected(), but we can not call it by module/import -- -- @see https://github.com/xmake-io/xmake/issues/3187 function _remote_build_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(config.directory(), "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 -- get the option menu for action: xmake config or global function menu.options(action) assert(action) -- get all platforms local plats = platform.plats() assert(plats) -- load and merge all platform options local exist = {} local results = {} for _, plat in ipairs(plats) do -- load platform local instance, errors = platform.load(plat) if not instance then return nil, errors end -- get menu of the supported platform on the current host local menu = instance:menu() if menu and (os.is_host(table.unpack(table.wrap(instance:hosts()))) or _remote_build_is_connected()) then -- get the options for this action local options = menu[action] if options then -- get the language option for _, option in ipairs(options) do -- merge it and remove repeat local name = option[2] if name then if not exist[name] then table.insert(results, option) exist[name] = true end else table.insert(results, option) end end end end end return results end -- return module return menu
0
repos/xmake/xmake/core
repos/xmake/xmake/core/platform/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 -- -- define module local environment = environment or {} -- load modules local os = require("base/os") local table = require("base/table") local global = require("base/global") local sandbox = require("sandbox/sandbox") local package = require("package/package") local import = require("sandbox/modules/import") -- enter the toolchains environment function environment._enter_toolchains() return true end -- leave the toolchains environment function environment._leave_toolchains() return true end -- enter the environment for the current platform function environment.enter(name) -- need enter? local entered = environment._ENTERED or {} environment._ENTERED = entered if entered[name] then entered[name] = entered[name] + 1 return true else entered[name] = 1 end -- do enter local maps = {toolchains = environment._enter_toolchains} local func = maps[name] if func then local ok, errors = func() if not ok then return false, errors end end return true end -- leave the environment for the current platform function environment.leave(name) -- need leave? local entered = environment._ENTERED or {} if entered[name] then entered[name] = entered[name] - 1 end if entered[name] == 0 then entered[name] = nil else return true end -- do leave local maps = {toolchains = environment._leave_toolchains} local func = maps[name] if func then local ok, errors = func() if not ok then return false, errors end end return true end -- return module return environment
0
repos/xmake/xmake/core
repos/xmake/xmake/core/platform/platform.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 platform.lua -- -- define module local platform = platform or {} local _instance = _instance or {} -- load modules local os = require("base/os") local path = require("base/path") local utils = require("base/utils") local table = require("base/table") local interpreter = require("base/interpreter") local toolchain = require("tool/toolchain") local memcache = require("cache/memcache") local sandbox = require("sandbox/sandbox") local config = require("project/config") local global = require("base/global") local scheduler = require("sandbox/modules/import/core/base/scheduler") -- new an instance function _instance.new(name, arch, info) local instance = table.inherit(_instance) instance._NAME = name instance._ARCH = arch instance._INFO = info return instance end -- get memcache function _instance:_memcache() local cache = self._MEMCACHE if not cache then cache = memcache.cache("core.platform.platform." .. tostring(self)) self._MEMCACHE = cache end return cache end -- get platform name function _instance:name() return self._NAME end -- get platform architecture function _instance:arch() return self._ARCH or config.get("arch") end -- set platform architecture function _instance:arch_set(arch) if self:arch() ~= arch then -- we need to clean the dirty cache if architecture has been changed platform._PLATFORMS[self:name() .. "_" .. self:arch()] = nil platform._PLATFORMS[self:name() .. "_" .. arch] = self self._ARCH = arch end end -- set the value to the platform configuration function _instance:set(name, ...) self._INFO:apival_set(name, ...) end -- add the value to the platform configuration function _instance:add(name, ...) self._INFO:apival_add(name, ...) end -- get the platform configuration function _instance:get(name) -- attempt to get the static configure value local value = self._INFO:get(name) if value ~= nil then return value end -- lazy loading platform if get other configuration if not self._LOADED and not self:_is_builtin_conf(name) then local on_load = self._INFO:get("load") if on_load then local ok, errors = sandbox.load(on_load, self) if not ok then os.raise(errors) end end self._LOADED = true end -- get other platform info return self._INFO:get(name) end -- get the platform os function _instance:os() return self._INFO:get("os") end -- get the platform menu function _instance:menu() -- @note do not use self:get("menu") to avoid loading platform early return self._INFO:get("menu") end -- get the platform hosts function _instance:hosts() return self._INFO:get("hosts") end -- get the platform archs function _instance:archs() return self._INFO:get("archs") end -- get runenvs of toolchains function _instance:runenvs() local runenvs = self._RUNENVS if not runenvs then runenvs = {} for _, toolchain_inst in ipairs(self:toolchains()) do local toolchain_runenvs = toolchain_inst:get("runenvs") if toolchain_runenvs then for name, values in pairs(toolchain_runenvs) do runenvs[name] = table.join2(table.wrap(runenvs[name]), values) end end end self._RUNENVS = runenvs end return runenvs end -- get the toolchains function _instance:toolchains(opt) local toolchains = self:_memcache():get("toolchains") if not toolchains then -- get current valid toolchains from configuration cache local names = nil toolchains = {} if not (opt and opt.all) then names = config.get("__toolchains_" .. self:name() .. "_" .. self:arch()) end if not names then -- get the given toolchain local toolchain_given = config.get("toolchain") if toolchain_given then local toolchain_inst, errors = toolchain.load(toolchain_given, { plat = self:name(), arch = self:arch()}) -- attempt to load toolchain from project if not toolchain_inst and platform._project() then toolchain_inst = platform._project().toolchain(toolchain_given) end if not toolchain_inst then os.raise(errors) end table.insert(toolchains, toolchain_inst) toolchain_given = toolchain_inst end -- get the platform toolchains if (not toolchain_given or not toolchain_given:is_standalone()) and self._INFO:get("toolchains") then names = self._INFO:get("toolchains") end end if names then for _, name in ipairs(table.wrap(names)) do local toolchain_inst, errors = toolchain.load(name, { plat = self:name(), arch = self:arch()}) -- attempt to load toolchain from project if not toolchain_inst and platform._project() then toolchain_inst = platform._project().toolchain(name) end if not toolchain_inst then os.raise(errors) end table.insert(toolchains, toolchain_inst) end end self:_memcache():set("toolchains", toolchains) end return toolchains end -- get the program and name of the given tool kind function _instance:tool(toolkind) return toolchain.tool(self:toolchains(), toolkind, {cachekey = "platform", plat = self:name(), arch = self:arch(), before_get = function () return config.get(toolkind) end}) end -- get tool configuration from the toolchains function _instance:toolconfig(name) return toolchain.toolconfig(self:toolchains(), name, {cachekey = "platform", plat = self:name(), arch = self:arch()}) end -- get the platform script function _instance:script(name) return self._INFO:get(name) end -- get user private data function _instance:data(name) return self._DATA and self._DATA[name] or nil end -- set user private data function _instance:data_set(name, data) self._DATA = self._DATA or {} self._DATA[name] = data end -- add user private data function _instance:data_add(name, data) self._DATA = self._DATA or {} self._DATA[name] = table.unwrap(table.join(self._DATA[name] or {}, data)) end -- do check function _instance:check() -- @see https://github.com/xmake-io/xmake/issues/4645#issuecomment-2201036943 -- @note avoid check it in the same time leading to deadlock if running in the coroutine local lockname = tostring(self) scheduler.co_lock(lockname) -- this platform has been check? local checked = self:_memcache():get("checked") if checked ~= nil then scheduler.co_unlock(lockname) return checked end -- check toolchains local toolchains = self:toolchains({all = true}) local idx = 1 local num = #toolchains local standalone = false local toolchains_valid = {} while idx <= num do local toolchain = toolchains[idx] -- we need to remove other standalone toolchains if standalone toolchain found if (standalone and toolchain:is_standalone()) or not toolchain:check() then table.remove(toolchains, idx) num = num - 1 else if toolchain:is_standalone() then standalone = true end idx = idx + 1 table.insert(toolchains_valid, toolchain:name()) end end if #toolchains == 0 then self:_memcache():set("checked", false) scheduler.co_unlock(lockname) return false, "toolchains not found!" end -- save valid toolchains config.set("__toolchains_" .. self:name() .. "_" .. self:arch(), toolchains_valid) self:_memcache():set("checked", true) scheduler.co_unlock(lockname) return true end -- get formats function _instance:formats() local formats = self._FORMATS if not formats then for _, toolchain_inst in ipairs(self:toolchains()) do formats = toolchain_inst:get("formats") if formats then break end end if not formats then formats = self._INFO:get("formats") end self._FORMATS = formats end return formats end -- is builtin configuration? function _instance:_is_builtin_conf(name) local builtin_configs = self._BUILTIN_CONFIGS if not builtin_configs then builtin_configs = {} for apiname, _ in pairs(platform._interpreter():apis("platform")) do local pos = apiname:find('_', 1, true) if pos then builtin_configs[apiname:sub(pos + 1)] = true end end self._BUILTIN_CONFIGS = builtin_configs end return builtin_configs[name] end -- the interpreter function platform._interpreter() -- the interpreter has been initialized? return it directly if platform._INTERPRETER then return platform._INTERPRETER end -- init interpreter local interp = interpreter.new() assert(interp) -- define apis interp:api_define(platform._apis()) -- save interpreter platform._INTERPRETER = interp -- ok? return interp end -- get project function platform._project() return platform._PROJECT end -- get platform apis function platform._apis() return { values = { -- platform.set_xxx "platform.set_os" , "platform.set_hosts" , "platform.set_archs" , "platform.set_installdir" , "platform.set_toolchains" } , script = { -- platform.on_xxx "platform.on_load" } , keyvalues = { "platform.set_formats" } , dictionary = { -- platform.set_xxx "platform.set_menu" } } end -- get memcache function platform._memcache() return memcache.cache("core.platform.platform") end -- get platform directories function platform.directories() -- init directories local dirs = platform._DIRS or { path.join(global.directory(), "platforms") , path.join(os.programdir(), "platforms") } -- save directories to cache platform._DIRS = dirs return dirs end -- add platform directories function platform.add_directories(...) -- add directories local dirs = platform.directories() for _, dir in ipairs({...}) do table.insert(dirs, 1, dir) end -- remove unique directories platform._DIRS = table.unique(dirs) end -- load the given platform function platform.load(plat, arch) -- get platform name plat = plat or config.get("plat") or os.host() arch = arch or config.get("arch") or os.arch() -- get cache key local cachekey = plat .. "_" .. arch -- get it directly from cache dirst platform._PLATFORMS = platform._PLATFORMS or {} if platform._PLATFORMS[cachekey] then return platform._PLATFORMS[cachekey] end -- find the platform script path local scriptpath = nil for _, dir in ipairs(platform.directories()) do -- find this directory scriptpath = path.join(dir, plat, "xmake.lua") if os.isfile(scriptpath) then break end end -- unknown platform? switch to cross compilation platform local cross = false if not scriptpath or not os.isfile(scriptpath) then scriptpath = path.join(os.programdir(), "platforms", "cross", "xmake.lua") cross = true end -- not exists? if not scriptpath or not os.isfile(scriptpath) then return nil, string.format("the platform %s not found!", plat) end -- get interpreter local interp = platform._interpreter() -- load script local ok, errors = interp:load(scriptpath) if not ok then return nil, errors end -- load platform local results, errors = interp:make("platform", true, false) if not results and os.isfile(scriptpath) then return nil, errors end -- get result local result = cross and results["cross"] or results[plat] -- check the platform name if not result then return nil, string.format("the platform %s not found!", plat) end -- save instance to the cache local instance = _instance.new(plat, arch, result) platform._PLATFORMS[cachekey] = instance return instance end -- get the given platform configuration function platform.get(name, plat, arch) local instance, errors = platform.load(plat, arch) if instance then return instance:get(name) else os.raise(errors) end end -- get the platform tool from the kind -- -- e.g. cc, cxx, mm, mxx, as, ar, ld, sh, .. -- function platform.tool(toolkind, plat, arch) local instance, errors = platform.load(plat, arch) if instance then return instance:tool(toolkind) else os.raise(errors) end end -- get the given tool configuration function platform.toolconfig(name, plat, arch) local instance, errors = platform.load(plat, arch) if instance then return instance:toolconfig(name) else os.raise(errors) end end -- get the all platforms function platform.plats() -- return it directly if exists if platform._PLATS then return platform._PLATS end -- get all platforms local plats = {} local dirs = platform.directories() for _, dir in ipairs(dirs) do local platpathes = os.dirs(path.join(dir, "*")) if platpathes then for _, platpath in ipairs(platpathes) do if os.isfile(path.join(platpath, "xmake.lua")) then table.insert(plats, path.basename(platpath)) end end end end platform._PLATS = plats return plats end -- get the all toolchains function platform.toolchains() local toolchains = platform._memcache():get("toolchains") if not toolchains then toolchains = {} local dirs = toolchain.directories() for _, dir in ipairs(dirs) do local dirs = os.dirs(path.join(dir, "*")) if dirs then for _, dir in ipairs(dirs) do if os.isfile(path.join(dir, "xmake.lua")) then table.insert(toolchains, path.filename(dir)) end end end end platform._memcache():set("toolchains", toolchains) end return toolchains end -- get the platform os function platform.os(plat, arch) return platform.get("os", plat, arch) or config.get("target_os") end -- get the platform archs function platform.archs(plat, arch) return platform.get("archs", plat, arch) end -- get the format of the given kind for platform function platform.format(kind, plat, arch) -- get platform instance local instance, errors = platform.load(plat, arch) if not instance then os.raise(errors) end -- get formats local formats = instance:formats() if formats then return formats[kind] end end -- return module return platform
0
repos/xmake/xmake/core
repos/xmake/xmake/core/package/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 -- -- define module local repository = repository or {} local _instance = _instance or {} -- load modules local utils = require("base/utils") local string = require("base/string") local global = require("base/global") local config = require("project/config") local interpreter = require("base/interpreter") local localcache = require("cache/localcache") local globalcache = require("cache/globalcache") -- new an instance function _instance.new(name, url, branch, directory, is_global) -- new an instance local instance = table.inherit(_instance) -- init instance instance._NAME = name instance._URL = url instance._BRANCH = branch instance._DIRECTORY = directory instance._IS_GLOBAL = is_global return instance end -- get the repository configure function _instance:get(name) -- load info local info = self:load() -- get if from info local value = info and info[name] or nil if value ~= nil then return value end end -- get the repository name function _instance:name() return self._NAME end -- get the repository url function _instance:url() return self._URL end -- get the repository branch function _instance:branch() return self._BRANCH end -- get the current commit function _instance:commit() return self._COMMIT end -- set the commit function _instance:commit_set(commit) self._COMMIT = commit end -- is global repository? function _instance:is_global() return self._IS_GLOBAL end -- get the repository directory function _instance:directory() return self._DIRECTORY end -- load the repository info in xmake.lua function _instance:load() -- do not loaded? if not self._INFO then -- attempt to load info from the repository script (xmake.lua) local scriptpath = path.join(self:directory(), "xmake.lua") if os.isfile(scriptpath) then -- get interpreter local interp = repository._interpreter() -- load script local ok, errors = interp:load(scriptpath) if not ok then os.raise("load repo(%s) failed, " .. errors, self:name()) end -- load repository and disable filter local results, errors = interp:make(nil, true, false) if not results then os.raise("load repo(%s) failed, " .. errors, self:name()) end -- save repository info self._INFO = results end end return self._INFO end -- get cache function repository._cache(is_global) if is_global then return globalcache.cache("repository") else return localcache.cache("repository") end end -- the interpreter function repository._interpreter() -- the interpreter has been initialized? return it directly if repository._INTERPRETER then return repository._INTERPRETER end -- init interpreter local interp = interpreter.new() assert(interp) -- define apis interp:api_define(repository.apis()) -- save interpreter repository._INTERPRETER = interp return interp end -- get repository apis function repository.apis() return { values = { -- set_xxx "set_description" } } end -- get the local or global repository directory function repository.directory(is_global) -- get directory if is_global then return path.join(global.directory(), "repositories") else return path.join(config.directory(), "repositories") end end -- load the repository function repository.load(name, url, branch, is_global) -- check url if not url then return nil, string.format("invalid repo(%s): url not found!", name) end -- get it directly from cache first repository._REPOS = repository._REPOS or {} if repository._REPOS[name] then return repository._REPOS[name] end -- the repository directory local repodir = os.isdir(url) and path.absolute(url) or path.join(repository.directory(is_global), name) -- new an instance local instance, errors = _instance.new(name, url, branch, repodir, is_global) if not instance then return nil, errors end -- save instance to the cache repository._REPOS[name] = instance return instance end -- get repository url from the given name function repository.get(name, is_global) -- get it local repositories = repository.repositories(is_global) if repositories then local repoinfo = repositories[name] if type(repoinfo) == "table" then return repoinfo[1], repoinfo[2] else return repoinfo end end end -- add repository url to the given name function repository.add(name, url, branch, is_global) -- no name? if not name then return false, string.format("please set name to repository: %s", url) end -- get repositories local repositories = repository.repositories(is_global) or {} -- set it repositories[name] = {url, branch} -- save repositories repository._cache(is_global):set("repositories", repositories) repository._cache(is_global):save() return true end -- remove repository from gobal or local directory function repository.remove(name, is_global) -- get repositories local repositories = repository.repositories(is_global) or {} if not repositories[name] then return false, string.format("repository(%s): not found!", name) end -- remove it repositories[name] = nil -- save repositories repository._cache(is_global):set("repositories", repositories) repository._cache(is_global):save() return true end -- clear all repositories function repository.clear(is_global) repository._cache(is_global):set("repositories", {}) repository._cache(is_global):save() return true end -- get all repositories from global or local directory function repository.repositories(is_global) return repository._cache(is_global):get("repositories") end -- return module return repository
0
repos/xmake/xmake/core
repos/xmake/xmake/core/package/component.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 component.lua -- -- define module local component = component or {} local _instance = _instance or {} -- load modules local os = require("base/os") local io = require("base/io") local path = require("base/path") local utils = require("base/utils") local table = require("base/table") local option = require("base/option") local hashset = require("base/hashset") local scopeinfo = require("base/scopeinfo") local interpreter = require("base/interpreter") local language = require("language/language") local sandbox = require("sandbox/sandbox") -- new an instance function _instance.new(name, opt) opt = opt or {} local instance = table.inherit(_instance) instance._NAME = name instance._INFO = scopeinfo.new("component", {}, {interpreter = component._interpreter()}) instance._PACKAGE = opt.package return instance end -- get the component name function _instance:name() return self._NAME end -- get the type: component function _instance:type() return "component" end -- get the it's package function _instance:package() return self._PACKAGE end -- get the component configuration function _instance:get(name) return self._INFO:get(name) end -- set the value to the component info function _instance:set(name, ...) self._INFO:apival_set(name, ...) end -- add the value to the component info function _instance:add(name, ...) self._INFO:apival_add(name, ...) end -- get the extra configuration function _instance:extraconf(name, item, key) local conf = self._INFO:extraconf(name, item, key) if conf == nil and self:base() then conf = self:base():extraconf(name, item, key) end return conf end -- set the extra configuration function _instance:extraconf_set(name, item, key, value) return self._INFO:extraconf_set(name, item, key, value) end -- get on_component script function _instance:_on_component() local script = self:package():get("component") local result = nil if type(script) == "function" then result = script elseif type(script) == "table" then result = script[self:name()] result = result or script["__generic__"] end return result end -- load this component function _instance:_load() local loaded = self._LOADED if not loaded then local script = self:_on_component() if script then local ok, errors = sandbox.load(script, self:package(), self) if not ok then os.raise("load component(%s) failed, %s", self:name(), errors or "unknown errors") end end self._LOADED = true end end -- the interpreter function component._interpreter() local interp = component._INTERPRETER if not interp then interp = interpreter.new() interp:api_define(component.apis()) interp:api_define(language.apis()) component._INTERPRETER = interp end return interp end -- get component apis function component.apis() return { values = { -- component.add_xxx "component.add_extsources" } } end -- new component function component.new(name, opt) return _instance.new(name, opt) end -- return module return component
0
repos/xmake/xmake/core
repos/xmake/xmake/core/package/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 -- -- define module local package = {} local _instance = {} -- load modules local os = require("base/os") local io = require("base/io") local path = require("base/path") local utils = require("base/utils") local table = require("base/table") local global = require("base/global") local semver = require("base/semver") local option = require("base/option") local hashset = require("base/hashset") local scopeinfo = require("base/scopeinfo") local interpreter = require("base/interpreter") local select_script = require("base/private/select_script") local is_cross = require("base/private/is_cross") local memcache = require("cache/memcache") local toolchain = require("tool/toolchain") local compiler = require("tool/compiler") local linker = require("tool/linker") local sandbox = require("sandbox/sandbox") local config = require("project/config") local policy = require("project/policy") local platform = require("platform/platform") local platform_menu = require("platform/menu") local component = require("package/component") local language = require("language/language") local language_menu = require("language/menu") local sandbox = require("sandbox/sandbox") local sandbox_os = require("sandbox/modules/os") local sandbox_module = require("sandbox/modules/import/core/sandbox/module") -- new an instance function _instance.new(name, info, opt) opt = opt or {} local instance = table.inherit(_instance) instance._NAME = name instance._INFO = info instance._REPO = opt.repo instance._SCRIPTDIR = opt.scriptdir and path.absolute(opt.scriptdir) return instance end -- get memcache function _instance:_memcache() local cache = self._MEMCACHE if not cache then cache = memcache.cache("core.package.package." .. tostring(self)) self._MEMCACHE = cache end return cache end -- get the package name function _instance:name() return self._NAME end -- get the type: package function _instance:type() return "package" end -- get the base package function _instance:base() return self._BASE end -- get the package configuration function _instance:get(name) local value = self._INFO:get(name) if name == "configs" then -- we need to merge it, because current builtin configs always exists if self:base() then local configs_base = self:base():get("configs") if configs_base then value = table.unique(table.join(value or {}, configs_base)) end end elseif value == nil and self:base() then value = self:base():get(name) end if value ~= nil then return value end end -- set the value to the package info function _instance:set(name, ...) if self._SOURCE_INITED then -- we can use set/add to modify urls, .. in on_load() if urls have been inited. -- but we cannot init urls, ... in on_load() if it has been not inited -- -- @see https://github.com/xmake-io/xmake/issues/5148 -- https://github.com/xmake-io/xmake-repo/pull/4204 if self:_sourceset():has(name) and self:get(name) == nil then os.raise("'%s' can only be initied in on_source() or the description scope.", name) end end self._INFO:apival_set(name, ...) end -- add the value to the package info function _instance:add(name, ...) if self._SOURCE_INITED then if self:_sourceset():has(name) and self:get(name) == nil then os.raise("'%s' can only be initied in on_source() or the description scope.", name) end end self._INFO:apival_add(name, ...) end -- get the extra configuration function _instance:extraconf(name, item, key) local conf = self._INFO:extraconf(name, item, key) if conf == nil and self:base() then conf = self:base():extraconf(name, item, key) end return conf end -- set the extra configuration function _instance:extraconf_set(name, item, key, value) return self._INFO:extraconf_set(name, item, key, value) end -- get configuration source information of the given api item function _instance:sourceinfo(name, item) return self._INFO:sourceinfo(name, item) end -- get the package license function _instance:license() return self:get("license") end -- get the package description function _instance:description() return self:get("description") end -- get the platform of package function _instance:plat() if self._PLAT then return self._PLAT end -- @note we uses os.host() instead of them for the binary package if self:is_binary() then return os.subhost() end local requireinfo = self:requireinfo() if requireinfo and requireinfo.plat then return requireinfo.plat end return package.targetplat() end -- get the architecture of package function _instance:arch() if self._ARCH then return self._ARCH end -- @note we uses os.arch() instead of them for the binary package if self:is_binary() then return os.subarch() end return self:targetarch() end -- set the package platform function _instance:plat_set(plat) self._PLAT = plat end -- set the package architecture function _instance:arch_set(arch) self._ARCH = arch end -- get the target os function _instance:targetos() local requireinfo = self:requireinfo() if requireinfo and requireinfo.targetos then return requireinfo.targetos end return config.get("target_os") or platform.os() end -- get the target architecture function _instance:targetarch() local requireinfo = self:requireinfo() if requireinfo and requireinfo.arch then return requireinfo.arch end return package.targetarch() end -- get the build mode function _instance:mode() return self:is_debug() and "debug" or "release" end -- get the repository of this package function _instance:repo() return self._REPO end -- the current platform is belong to the given platforms? function _instance:is_plat(...) local plat = self:plat() for _, v in ipairs(table.pack(...)) do if v and plat == v then return true end end end -- the current architecture is belong to the given architectures? function _instance:is_arch(...) local arch = self:arch() for _, v in ipairs(table.pack(...)) do if v and arch:find("^" .. v:gsub("%-", "%%-") .. "$") then return true end end end -- is 64bits architecture? function _instance:is_arch64() return self:is_arch(".+64.*") end -- the current platform is belong to the given target os? function _instance:is_targetos(...) local targetos = self:targetos() for _, v in ipairs(table.join(...)) do if v and targetos == v then return true end end end -- the current architecture is belong to the given target architectures? function _instance:is_targetarch(...) local targetarch = self:targetarch() for _, v in ipairs(table.pack(...)) do if v and targetarch:find("^" .. v:gsub("%-", "%%-") .. "$") then return true end end end -- get the package alias function _instance:alias() local requireinfo = self:requireinfo() if requireinfo then return requireinfo.alias end end -- get external package sources, e.g. pkgconfig::xxx, system::xxx, conan::xxx -- we can use it to improve self:fetch() for find_package function _instance:extsources() return self:get("extsources") end -- get urls function _instance:urls() local urls = self._URLS if urls == nil then urls = table.wrap(self:get("urls")) if #urls == 1 and urls[1] == "" then urls = {} end end return urls end -- get urls function _instance:urls_set(urls) self._URLS = urls end -- get the alias of url, @note need raw url function _instance:url_alias(url) return self:extraconf("urls", url, "alias") end -- get the version filter of url, @note need raw url function _instance:url_version(url) return self:extraconf("urls", url, "version") end -- get the excludes list of url for the archive extractor, @note need raw url function _instance:url_excludes(url) return self:extraconf("urls", url, "excludes") end -- get the http headers of url, @note need raw url function _instance:url_http_headers(url) return self:extraconf("urls", url, "http_headers") end -- set artifacts info function _instance:artifacts_set(artifacts_info) local versions = self:_versions_list() if versions then -- backup previous package configuration self._ARTIFACTS_BACKUP = { urls = table.copy(self:urls()), versions = table.copy(versions), install = self:script("install")} -- self:get() will get a table, it will be broken when call self:set() -- we switch to urls of the precompiled artifacts self:urls_set(table.wrap(artifacts_info.urls)) versions[self:version_str()] = artifacts_info.sha256 self:set("install", function (package) sandbox_module.import("lib.detect.find_path") local rootdir = find_path("manifest.txt", path.join(os.curdir(), "*", "*", "*")) if not rootdir then os.raise("package(%s): manifest.txt not found when installing artifacts!", package:displayname()) end os.cp(path.join(rootdir, "*"), package:installdir(), {symlink = true}) local manifest = package:manifest_load() if not manifest then os.raise("package(%s): load manifest.txt failed when installing artifacts!", package:displayname()) end if manifest.vars then for k, v in pairs(manifest.vars) do package:set(k, v) end end if manifest.components then local vars = manifest.components.vars if vars then for component_name, component_vars in pairs(vars) do local comp = package:component(component_name) if comp then for k, v in pairs(component_vars) do comp:set(k, v) end end end end end if manifest.envs then local envs = self:_rawenvs() for k, v in pairs(manifest.envs) do envs[k] = v end end -- save the remote install directory to fix the install path in .cmake/.pc files for precompiled artifacts -- -- @see https://github.com/xmake-io/xmake/issues/2210 -- manifest.artifacts = manifest.artifacts or {} manifest.artifacts.remotedir = manifest.artifacts.installdir end) self._IS_PRECOMPILED = true end end -- is this package built? function _instance:is_built() return not self:is_precompiled() end -- is this package precompiled? function _instance:is_precompiled() return self._IS_PRECOMPILED end -- fallback to source code build function _instance:fallback_build() if self:is_precompiled() then local artifacts_backup = self._ARTIFACTS_BACKUP if artifacts_backup then if artifacts_backup.urls then self:urls_set(artifacts_backup.urls) end if artifacts_backup.versions then self._INFO:apival_set("versions", artifacts_backup.versions) end if artifacts_backup.install then self._INFO:apival_set("install", artifacts_backup.install) end self._MANIFEST = nil end self._IS_PRECOMPILED = false end end -- get the given dependent package function _instance:dep(name) local deps = self:deps() if deps then return deps[name] end end -- get deps function _instance:deps() return self._DEPS end -- get order deps function _instance:orderdeps() return self._ORDERDEPS end -- get plain deps function _instance:plaindeps() return self._PLAINDEPS end -- get library deps with correct link order function _instance:librarydeps(opt) if opt and opt.private then return self._LIBRARYDEPS_WITH_PRIVATE else return self._LIBRARYDEPS end end -- get parents function _instance:parents(packagename) local parents = self._PARENTS if parents then if packagename then return parents[packagename] else local results = self._PARENTS_PLAIN if not results then results = {} for _, parentpkgs in pairs(parents) do table.join2(results, parentpkgs) end results = table.unique(results) self._PARENTS_PLAIN = results end if #results > 0 then return results end end end end -- add parents function _instance:parents_add(...) self._PARENTS = self._PARENTS or {} for _, parent in ipairs({...}) do -- maybe multiple parents will depend on it -- @see https://github.com/xmake-io/xmake/issues/3065 local parentpkgs = self._PARENTS[parent:name()] if not parentpkgs then parentpkgs = {} self._PARENTS[parent:name()] = parentpkgs end table.insert(parentpkgs, parent) self._PARENTS_PLAIN = nil end end -- get hash of the source package for the url_alias@version_str function _instance:sourcehash(url_alias) local versions = self:_versions_list() local version_str = self:version_str() if versions and version_str then local sourcehash = nil if url_alias then sourcehash = versions[url_alias .. ":" ..version_str] end if not sourcehash then sourcehash = versions[version_str] end if sourcehash and #sourcehash == 40 then sourcehash = sourcehash:lower() end return sourcehash end end -- get revision(commit, tag, branch) of the url_alias@version_str, only for git url function _instance:revision(url_alias) local revision = self:sourcehash(url_alias) if revision and #revision <= 40 then -- it will be sha256 of tar/gz file, not commit number if longer than 40 characters return revision end end -- get the package policy function _instance:policy(name) local policies = self._POLICIES if not policies then policies = self:get("policy") self._POLICIES = policies if policies then local defined_policies = policy.policies() for name, _ in pairs(policies) do if not defined_policies[name] then utils.warning("unknown policy(%s), please run `xmake l core.project.policy.policies` if you want to all policies", name) end end end end return policy.check(name, policies and policies[name]) end -- get the package kind -- -- - binary -- - toolchain (is also binary) -- - library(default) -- function _instance:kind() local kind local requireinfo = self:requireinfo() if requireinfo then kind = requireinfo.kind end if not kind then kind = self:get("kind") end return kind end -- is binary package? function _instance:is_binary() return self:kind() == "binary" or self:kind() == "toolchain" end -- is toolchain package? function _instance:is_toolchain() return self:kind() == "toolchain" end -- is library package? function _instance:is_library() return self:kind() == nil or self:kind() == "library" end -- is template package? function _instance:is_template() return self:kind() == "template" end -- is header only? function _instance:is_headeronly() return self:is_library() and self:extraconf("kind", "library", "headeronly") end -- is module only? function _instance:is_moduleonly() return self:is_library() and self:extraconf("kind", "library", "moduleonly") end -- is top level? user top requires in xmake.lua function _instance:is_toplevel() local requireinfo = self:requireinfo() return requireinfo and requireinfo.is_toplevel end -- is the system package? function _instance:is_system() return self._is_system end -- is the third-party package? e.g. brew::pcre2/libpcre2-8, conan::OpenSSL/1.0.2n@conan/stable -- we need to install and find package by third-party package manager directly -- function _instance:is_thirdparty() return self._is_thirdparty end -- is fetch only? function _instance:is_fetchonly() local project = package._project() if project and project.policy("package.fetch_only") then return true end -- only fetch script if self:get("fetch") and not self:get("install") then return true end -- only from system local requireinfo = self:requireinfo() if requireinfo and requireinfo.system then return true end return false end -- is optional package? function _instance:is_optional() local requireinfo = self:requireinfo() return requireinfo and requireinfo.optional or false end -- is private package? function _instance:is_private() local requireinfo = self:requireinfo() return requireinfo and requireinfo.private or false end -- verify sha256sum and versions? function _instance:is_verify() local requireinfo = self:requireinfo() local verify = requireinfo and requireinfo.verify if verify == nil then verify = true end return verify end -- is debug package? function _instance:is_debug() return self:config("debug") or self:config("asan") end -- is the supported package? function _instance:is_supported() -- attempt to get the install script with the current plat/arch return self:script("install") ~= nil end -- support parallelize for installation? function _instance:is_parallelize() return self:get("parallelize") ~= false end -- is local embed source code package? -- we install directly from the local source code instead of downloading it remotely function _instance:is_source_embed() return self:get("sourcedir") and #self:urls() == 0 and self:script("install") end -- is local embed binary package? it's come from `xmake package` function _instance:is_binary_embed() return self:get("installdir") and #self:urls() == 0 and not self:script("install") and self:script("fetch") end -- is local package? -- we will use local installdir and cachedir in current project function _instance:is_local() return self._IS_LOCAL or self:is_source_embed() or self:is_binary_embed() or self:is_thirdparty() end -- mark it as local package function _instance:_mark_as_local(is_local) if self:is_local() ~= is_local then self._INSTALLDIR = nil self._IS_LOCAL = is_local end end -- use external includes? function _instance:use_external_includes() local external = self:requireinfo().external if external == nil then local project = package._project() if project then external = project.policy("package.include_external_headers") end end if external == nil then external = self:policy("package.include_external_headers") end -- disable -Isystem for external packages as it seems to break. e.g. assimp -- @see https://github.com/msys2/MINGW-packages/issues/10761 if external == nil and self:is_plat("mingw") and os.is_subhost("msys") then external = false end if external == nil then external = true end return external end -- is debug package? (deprecated) function _instance:debug() return self:is_debug() end -- is cross-compilation? function _instance:is_cross() return is_cross(self:plat(), self:arch()) end -- get the filelock of the whole package directory function _instance:filelock() local filelock = self._FILELOCK if filelock == nil then filelock = io.openlock(path.join(self:cachedir(), "package.lock")) if not filelock then os.raise("cannot create filelock for package(%s)!", self:name()) end self._FILELOCK = filelock end return filelock end -- lock the whole package function _instance:lock(opt) if self:filelock():trylock(opt) then return true else utils.cprint("${color.warning}package(%s) is being accessed by other processes, please wait!", self:name()) end local ok, errors = self:filelock():lock(opt) if not ok then os.raise(errors) end end -- unlock the whole package function _instance:unlock() local ok, errors = self:filelock():unlock() if not ok then os.raise(errors) end end -- get the source directory function _instance:sourcedir() return self:get("sourcedir") end -- get the build directory function _instance:buildir() local buildir = self._BUILDIR if not buildir then if self:is_local() then local name = self:name():lower():gsub("::", "_") local rootdir = path.join(config.buildir({absolute = true}), ".packages", name:sub(1, 1):lower(), name, self:version_str()) buildir = path.join(rootdir, "cache", "build_" .. self:buildhash():sub(1, 8)) else buildir = "build_" .. self:buildhash():sub(1, 8) end self._BUILDIR = buildir end return buildir end -- get the cached directory of this package function _instance:cachedir() local cachedir = self._CACHEDIR if not cachedir then cachedir = self:get("cachedir") if not cachedir then -- we need to use displayname (with package id) to avoid -- multiple processes accessing it at the same time. -- -- @see https://github.com/libbpf/libbpf-bootstrap/pull/259#issuecomment-1994914188 -- -- e.g. -- -- lock elfutils#1 /home/runner/.xmake/cache/packages/2403/e/elfutils/0.189 -- lock elfutils /home/runner/.xmake/cache/packages/2403/e/elfutils/0.189 -- package(elfutils) is being accessed by other processes, please wait! -- local name = self:displayname():lower():gsub("::", "_"):gsub("#", "_") local version_str = self:version_str() -- strip invalid characters on windows, e.g. `>= <=` if os.is_host("windows") then version_str = version_str:gsub("[>=<|%*]", "") end if self:is_local() then cachedir = path.join(config.buildir({absolute = true}), ".packages", name:sub(1, 1):lower(), name, version_str, "cache") else cachedir = path.join(package.cachedir(), name:sub(1, 1):lower(), name, version_str) end end self._CACHEDIR = cachedir end return cachedir end -- get the installed directory of this package function _instance:installdir(...) local installdir = self._INSTALLDIR if not installdir then installdir = self:get("installdir") if not installdir then local name = self:name():lower():gsub("::", "_") if self:is_local() then installdir = path.join(config.buildir({absolute = true}), ".packages", name:sub(1, 1):lower(), name) else installdir = path.join(package.installdir(), name:sub(1, 1):lower(), name) end local version_str = self:version_str() if version_str then -- strip invalid characters on windows, e.g. `>= <=` if os.is_host("windows") then version_str = version_str:gsub("[>=<|%*]", "") end installdir = path.join(installdir, version_str) end installdir = path.join(installdir, self:buildhash()) end self._INSTALLDIR = installdir end local dirs = table.pack(...) local opt = dirs[dirs.n] if table.is_dictionary(opt) then table.remove(dirs) else opt = nil end local dir = path.join(installdir, table.unpack(dirs)) if opt and opt.readonly then return dir end if not os.isdir(dir)then os.mkdir(dir) end return dir end -- get the script directory function _instance:scriptdir() return self._SCRIPTDIR end -- get the rules directory function _instance:rulesdir() local rulesdir = self._RULESDIR if rulesdir == nil then rulesdir = path.join(self:scriptdir(), "rules") if not os.isdir(rulesdir) and self:base() then rulesdir = self:base():rulesdir() end if rulesdir == nil or not os.isdir(rulesdir) then rulesdir = false end self._RULESDIR = rulesdir end return rulesdir or nil end -- get the references info of this package function _instance:references() local references_file = path.join(self:installdir({readonly = true}), "references.txt") if os.isfile(references_file) then local references, errors = io.load(references_file) if not references then os.raise(errors) end return references end end -- get the manifest file of this package function _instance:manifest_file() return path.join(self:installdir({readonly = true}), "manifest.txt") end -- load the manifest file of this package function _instance:manifest_load() local manifest = self._MANIFEST if not manifest then local manifest_file = self:manifest_file() if os.isfile(manifest_file) then local errors = nil manifest, errors = io.load(manifest_file) if not manifest then os.raise(errors) end self._MANIFEST = manifest end end return manifest end -- save the manifest file of this package function _instance:manifest_save() -- make manifest local manifest = {} manifest.name = self:name() manifest.license = self:license() manifest.description = self:description() manifest.version = self:version_str() manifest.kind = self:kind() manifest.plat = self:plat() manifest.arch = self:arch() manifest.mode = self:mode() manifest.configs = self:configs() manifest.envs = self:_rawenvs() manifest.pathenvs = self:_pathenvs():to_array() -- save enabled library deps if self:librarydeps() then manifest.librarydeps = {} for _, dep in ipairs(self:librarydeps()) do if dep:exists() then table.insert(manifest.librarydeps, dep:name()) end end end -- save deps if self:librarydeps() then manifest.deps = {} for _, dep in ipairs(self:librarydeps()) do manifest.deps[dep:name()] = { version = dep:version_str(), buildhash = dep:buildhash() } end end -- save global variables and component variables local vars local extras local components local apis = language.apis() for _, apiname in ipairs(table.join(apis.values, apis.paths, apis.groups)) do if apiname:startswith("package.add_") or apiname:startswith("package.set_") then local name = apiname:sub(13) local values = self:get(name) if values ~= nil then vars = vars or {} vars[name] = values local extra = self:extraconf(name) if extra then extras = extras or {} extras[name] = extra end end for _, component_name in ipairs(table.wrap(self:get("components"))) do local comp = self:component(component_name) if comp then local component_values = comp:get(name) if component_values ~= nil then components = components or {} components.vars = components.vars or {} components.vars[component_name] = components.vars[component_name] or {} components.vars[component_name][name] = component_values end end end end end manifest.vars = vars manifest.extras = extras manifest.components = components -- save repository local repo = self:repo() if repo then manifest.repo = {} manifest.repo.name = repo:name() manifest.repo.url = repo:url() manifest.repo.branch = repo:branch() manifest.repo.commit = repo:commit() end -- save artifacts information to fix the install path in .cmake/.pc files for precompiled artifacts -- -- @see https://github.com/xmake-io/xmake/issues/2210 -- manifest.artifacts = {} manifest.artifacts.installdir = self:installdir() local current_manifest = self:manifest_load() if current_manifest and current_manifest.artifacts then manifest.artifacts.remotedir = current_manifest.artifacts.remotedir end -- save manifest local ok, errors = io.save(self:manifest_file(), manifest, { orderkeys = true }) if not ok then os.raise(errors) end end -- get the source configuration set function _instance:_sourceset() local sourceset = self._SOURCESET if sourceset == nil then sourceset = hashset.of("urls", "versions", "versionfiles", "configs") self._SOURCESET = sourceset end return sourceset end -- init package source function _instance:_init_source() local inited = self._SOURCE_INITED if not inited then local on_source = self:script("source") if on_source then on_source(self) end end end -- load package function _instance:_load() self._SOURCE_INITED = true local loaded = self._LOADED if not loaded then local on_load = self:script("load") if on_load then on_load(self) end end end -- mark as loaded package function _instance:_mark_as_loaded() self._LOADED = true end -- get the raw environments function _instance:_rawenvs() local envs = self._RAWENVS if not envs then envs = {} -- add bin PATH local bindirs = self:get("bindirs") if bindirs then envs.PATH = table.wrap(bindirs) elseif self:is_binary() or self:is_plat("windows", "mingw") then -- bin/*.dll for windows envs.PATH = {"bin"} end -- add LD_LIBRARY_PATH to load *.so directory if os.host() ~= "windows" and self:is_plat(os.host()) and self:is_arch(os.arch()) then envs.LD_LIBRARY_PATH = {"lib"} if os.host() == "macosx" then envs.DYLD_LIBRARY_PATH = {"lib"} end end self._RAWENVS = envs end return envs end -- get path environment keys function _instance:_pathenvs() local pathenvs = self._PATHENVS if pathenvs == nil then pathenvs = hashset.from { "PATH", "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH", "PKG_CONFIG_PATH", "ACLOCAL_PATH", "CMAKE_PREFIX_PATH", "PYTHONPATH" } self._PATHENVS = pathenvs end return pathenvs end -- mark as path environments function _instance:mark_as_pathenv(name) self:_pathenvs():insert(name) end -- get the exported environments function _instance:envs() local envs = {} for name, values in pairs(self:_rawenvs()) do if self:_pathenvs():has(name) then local newvalues = {} for _, value in ipairs(values) do if path.is_absolute(value) then table.insert(newvalues, value) else table.insert(newvalues, path.normalize(path.join(self:installdir(), value))) end end values = newvalues end envs[name] = values end return envs end -- load the package environments from the manifest function _instance:envs_load() local manifest = self:manifest_load() if manifest then local envs = self:_rawenvs() for name, values in pairs(manifest.envs) do envs[name] = values end end end -- enter the package environments function _instance:envs_enter() local installdir = self:installdir({readonly = true}) for name, values in pairs(self:envs()) do os.addenv(name, table.unpack(table.wrap(values))) end end -- get the given environment variable function _instance:getenv(name) return self:_rawenvs()[name] end -- set the given environment variable function _instance:setenv(name, ...) self:_rawenvs()[name] = {...} end -- add the given environment variable function _instance:addenv(name, ...) self:_rawenvs()[name] = table.join(self:_rawenvs()[name] or {}, ...) end -- get the given build environment variable function _instance:build_getenv(name) return self:build_envs(true)[name] end -- set the given build environment variable function _instance:build_setenv(name, ...) self:build_envs(true)[name] = table.unwrap({...}) end -- add the given build environment variable function _instance:build_addenv(name, ...) self:build_envs(true)[name] = table.unwrap(table.join(table.wrap(self:build_envs()[name]), ...)) end -- get the build environments function _instance:build_envs(lazy_loading) local build_envs = self._BUILD_ENVS if build_envs == nil then -- lazy loading the given environment value and cache it build_envs = {} setmetatable(build_envs, { __index = function (tbl, key) local value = config.get(key) if value == nil then value = self:tool(key) end value = table.unique(table.join(table.wrap(value), table.wrap(self:config(key)), self:toolconfig(key))) if #value > 0 then value = table.unwrap(value) rawset(tbl, key, value) return value end return rawget(tbl, key) end}) -- save build environments self._BUILD_ENVS = build_envs end -- force to load all values if need if not lazy_loading then for _, opt in ipairs(table.join(language_menu.options("config"), platform_menu.options("config"))) do local optname = opt[2] if type(optname) == "string" then -- we only need to index it to force load it's value local value = build_envs[optname] end end end return build_envs end -- get runtimes function _instance:runtimes() local runtimes = self:_memcache():get("runtimes") if runtimes == nil then runtimes = self:config("runtimes") if runtimes then local runtimes_current = runtimes:split(",", {plain = true}) runtimes = table.unwrap(runtimes_current) end runtimes = runtimes or false self:_memcache():set("runtimes", runtimes) end return runtimes or nil end -- has the given runtime for the current toolchains? function _instance:has_runtime(...) local runtimes_set = self:_memcache():get("runtimes_set") if runtimes_set == nil then runtimes_set = hashset.from(table.wrap(self:runtimes())) self:_memcache():set("runtimes_set", runtimes_set) end for _, v in ipairs(table.pack(...)) do if runtimes_set:has(v) then return true end end end -- get the given toolchain function _instance:toolchain(name) local toolchains_map = self:_memcache():get("toolchains_map") if toolchains_map == nil then toolchains_map = {} local toolchains = self:toolchains() if toolchains then for _, toolchain_inst in ipairs(toolchains) do toolchains_map[toolchain_inst:name()] = toolchain_inst end end self:_memcache():set("toolchains_map", toolchains_map) end if not toolchains_map[name] then toolchains_map[name] = toolchain.load(name, {plat = self:plat(), arch = self:arch()}) end return toolchains_map[name] end -- get toolchains function _instance:toolchains() local toolchains = self._TOOLCHAINS if toolchains == nil then local project = package._project() for _, name in ipairs(table.wrap(self:config("toolchains"))) do local toolchain_opt = project and project.extraconf("target.toolchains", name) or {} toolchain_opt.plat = self:plat() toolchain_opt.arch = self:arch() local toolchain_inst, errors = toolchain.load(name, toolchain_opt) if not toolchain_inst and project then toolchain_inst = project.toolchain(name, toolchain_opt) end if not toolchain_inst then os.raise(errors) end toolchains = toolchains or {} table.insert(toolchains, toolchain_inst) end self._TOOLCHAINS = toolchains or false end return toolchains or nil end -- get the program and name of the given tool kind function _instance:tool(toolkind) if self:toolchains() then local cachekey = "package_" .. tostring(self) return toolchain.tool(self:toolchains(), toolkind, {cachekey = cachekey, plat = self:plat(), arch = self:arch()}) else return platform.tool(toolkind, self:plat(), self:arch()) end end -- get tool configuration from the toolchains function _instance:toolconfig(name) if self:toolchains() then local cachekey = "package_" .. tostring(self) return toolchain.toolconfig(self:toolchains(), name, {cachekey = cachekey, plat = self:plat(), arch = self:arch()}) else return platform.toolconfig(name, self:plat(), self:arch()) end end -- get the package compiler function _instance:compiler(sourcekind) local compilerinst = self:_memcache():get2("compiler", sourcekind) if not compilerinst then if not sourcekind then os.raise("please pass sourcekind to the first argument of package:compiler(), e.g. cc, cxx, as") end local instance, errors = compiler.load(sourcekind, self) if not instance then os.raise(errors) end compilerinst = instance self:_memcache():set2("compiler", sourcekind, compilerinst) end return compilerinst end -- get the package linker function _instance:linker(targetkind, sourcekinds) local linkerinst = self:_memcache():get3("linker", targetkind, sourcekinds) if not linkerinst then if not sourcekinds then os.raise("please pass sourcekinds to the second argument of package:linker(), e.g. cc, cxx, as") end local instance, errors = linker.load(targetkind, sourcekinds, self) if not instance then os.raise(errors) end linkerinst = instance self:_memcache():set3("linker", targetkind, sourcekinds, linkerinst) end return linkerinst end -- has the given tool for the current package? -- -- e.g. -- -- if package:has_tool("cc", "clang", "gcc") then -- ... -- end function _instance:has_tool(toolkind, ...) local _, toolname = self:tool(toolkind) if toolname then for _, v in ipairs(table.join(...)) do if v and toolname:find("^" .. v:gsub("%-", "%%-") .. "$") then return true end end end end -- get the user private data function _instance:data(name) return self._DATA and self._DATA[name] or nil end -- set user private data function _instance:data_set(name, data) self._DATA = self._DATA or {} self._DATA[name] = data end -- add user private data function _instance:data_add(name, data) self._DATA = self._DATA or {} self._DATA[name] = table.unwrap(table.join(self._DATA[name] or {}, data)) end -- get the downloaded original file function _instance:originfile() return self._ORIGINFILE end -- set the downloaded original file function _instance:originfile_set(filepath) self._ORIGINFILE = filepath end -- get versions list function _instance:_versions_list() if self._VERSIONS_LIST == nil then local versions = table.wrap(self:get("versions")) local versionfiles = self:get("versionfiles") if versionfiles then for _, versionfile in ipairs(table.wrap(versionfiles)) do if not path.is_absolute(versionfile) then local subpath = versionfile versionfile = path.join(self:scriptdir(), subpath) if not os.isfile(versionfile) then versionfile = path.join(self:base():scriptdir(), subpath) end end if os.isfile(versionfile) then local list = io.readfile(versionfile) for _, line in ipairs(list:split("\n")) do local splitinfo = line:split("%s+") if #splitinfo == 2 then local version = splitinfo[1] local shasum = splitinfo[2] versions[version] = shasum end end end end end self._VERSIONS_LIST = versions end return self._VERSIONS_LIST end -- get versions function _instance:versions() if self._VERSIONS == nil then local versions = {} for version, _ in pairs(self:_versions_list()) do -- remove the url alias prefix if exists local pos = version:find(':', 1, true) if pos then version = version:sub(pos + 1, -1) end table.insert(versions, version) end self._VERSIONS = table.unique(versions) end return self._VERSIONS end -- get the version function _instance:version() return self._VERSION end -- get the version string function _instance:version_str() if self:is_thirdparty() then local requireinfo = self:requireinfo() if requireinfo then return requireinfo.version end end return self._VERSION_STR end -- set the version, source: branch, tag, version function _instance:version_set(version, source) -- save the semver version local sv = semver.new(version) if sv then self._VERSION = sv end -- save branch and tag if source == "branch" then self._BRANCH = version elseif source == "tag" then self._TAG = version elseif source == "commit" then self._COMMIT = version end -- save version string if source == "commit" then -- we strip it to avoid long paths self._VERSION_STR = version:sub(1, 8) else self._VERSION_STR = version end end -- get branch version function _instance:branch() return self._BRANCH end -- get tag version function _instance:tag() return self._TAG end -- get commit version function _instance:commit() return self._COMMIT end -- is git ref? function _instance:gitref() return self:branch() or self:tag() or self:commit() end -- get the require info function _instance:requireinfo() return self._REQUIREINFO end -- set the require info function _instance:requireinfo_set(requireinfo) self._REQUIREINFO = requireinfo end -- get label function _instance:label() local requireinfo = self:requireinfo() return requireinfo and requireinfo.label end -- get the display name function _instance:displayname() return self._DISPLAYNAME end -- set the display name function _instance:displayname_set(displayname) self._DISPLAYNAME = displayname end -- invalidate configs function _instance:_invalidate_configs() self._CONFIGS = nil self._CONFIGS_FOR_BUILDHASH = nil end -- get the given configuration value of package function _instance:config(name) local value local configs = self:configs() if configs then value = configs[name] -- vs_runtime is deprecated now if name == "vs_runtime" then local runtimes = configs.runtimes if runtimes then for _, item in ipairs(runtimes:split(",")) do if item:startswith("MT") or item:startswith("MD") then value = item break end end end utils.warning("please use package:runtimes() or package:has_runtime() instead of package:config(\"vs_runtime\")") end end return value end -- set configuration value function _instance:config_set(name, value) local configs = self:configs() if configs then configs[name] = value end end -- get the configurations of package function _instance:configs() local configs = self._CONFIGS if configs == nil then local configs_defined = self:get("configs") if configs_defined then configs = {} local requireinfo = self:requireinfo() local configs_required = requireinfo and requireinfo.configs or {} local configs_overrided = requireinfo and requireinfo.configs_overrided or {} for _, name in ipairs(table.wrap(configs_defined)) do local value = configs_overrided[name] or configs_required[name] if value == nil then value = self:extraconf("configs", name, "default") -- support for the deprecated vs_runtime in add_configs if name == "runtimes" and value == nil then value = self:extraconf("configs", "vs_runtime", "default") end end configs[name] = value end else configs = false end self._CONFIGS = configs end return configs and configs or nil end -- get the given configuration value of package for buildhash function _instance:_config_for_buildhash(name) local value local configs = self:_configs_for_buildhash() if configs then value = configs[name] end return value end -- get the configurations of package for buildhash -- @note on_test still need these configs function _instance:_configs_for_buildhash() local configs = self._CONFIGS_FOR_BUILDHASH if configs == nil then local configs_defined = self:get("configs") if configs_defined then configs = {} local requireinfo = self:requireinfo() local configs_required = requireinfo and requireinfo.configs or {} local configs_overrided = requireinfo and requireinfo.configs_overrided or {} local ignored_configs_for_buildhash = hashset.from(requireinfo and requireinfo.ignored_configs_for_buildhash or {}) for _, name in ipairs(table.wrap(configs_defined)) do if not ignored_configs_for_buildhash:has(name) then local value = configs_overrided[name] or configs_required[name] if value == nil then value = self:extraconf("configs", name, "default") -- support for the deprecated vs_runtime in add_configs if name == "runtimes" and value == nil then value = self:extraconf("configs", "vs_runtime", "default") end end configs[name] = value end end else configs = false end self._CONFIGS_FOR_BUILDHASH = configs end return configs and configs or nil end -- compute the build hash function _instance:_compute_buildhash() self._BUILDHASH_PREPRARED = true self:buildhash() end -- get the build hash function _instance:buildhash() local buildhash = self._BUILDHASH if buildhash == nil then if not self._BUILDHASH_PREPRARED then os.raise("package:buildhash() must be called after loading package") end local function _get_buildhash(configs, opt) opt = opt or {} local str = self:plat() .. self:arch() local label = self:label() if label then str = str .. label end if configs then -- with old vs_runtime configs -- https://github.com/xmake-io/xmake/issues/4477 if opt.vs_runtime then configs = table.clone(configs) configs.vs_runtime = configs.runtimes configs.runtimes = nil end -- since luajit v2.1, the key order of the table is random and undefined. -- We cannot directly deserialize the table, so the result may be different each time local configs_order = {} for k, v in pairs(table.wrap(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) -- we need to be compatible with the hash value string for the previous luajit version local configs_str = string.serialize(configs_order, true) configs_str = configs_str:gsub("\"", "") str = str .. configs_str end if opt.sourcehash ~= false then local sourcehashs = hashset.new() for _, url in ipairs(self:urls()) do local url_alias = self:url_alias(url) local sourcehash = self:sourcehash(url_alias) if sourcehash then sourcehashs:insert(sourcehash) end end if not sourcehashs:empty() then local hashs = sourcehashs:to_array() table.sort(hashs) str = str .. "_" .. table.concat(hashs, "_") end end local toolchains = self:_config_for_buildhash("toolchains") if opt.toolchains ~= false and toolchains then toolchains = table.copy(table.wrap(toolchains)) table.sort(toolchains) str = str .. "_" .. table.concat(toolchains, "_") end return hash.uuid4(str):gsub('-', ''):lower() end local function _get_installdir(...) local name = self:name():lower():gsub("::", "_") local dir = path.join(package.installdir(), name:sub(1, 1):lower(), name) if self:version_str() then dir = path.join(dir, self:version_str()) end return path.join(dir, ...) end -- we need to be compatible with the hash value string for the previous xmake version -- without builtin pic configuration (< 2.5.1). if self:_config_for_buildhash("pic") then local configs = table.copy(self:_configs_for_buildhash()) configs.pic = nil buildhash = _get_buildhash(configs, {sourcehash = false, toolchains = false}) if not os.isdir(_get_installdir(buildhash)) then buildhash = nil end end -- we need to be compatible with the hash value string for the previous xmake version -- without sourcehash (< 2.5.2) if not buildhash then buildhash = _get_buildhash(self:_configs_for_buildhash(), {sourcehash = false, toolchains = false}) if not os.isdir(_get_installdir(buildhash)) then buildhash = nil end end -- we need to be compatible with the previous xmake version -- without toolchains (< 2.6.4) if not buildhash then buildhash = _get_buildhash(self:_configs_for_buildhash(), {toolchains = false}) if not os.isdir(_get_installdir(buildhash)) then buildhash = nil end end -- we need to be compatible with the previous xmake version -- with deprecated vs_runtime (< 2.8.7) -- @see https://github.com/xmake-io/xmake/issues/4477 if not buildhash then buildhash = _get_buildhash(self:_configs_for_buildhash(), {vs_runtime = true}) if not os.isdir(_get_installdir(buildhash)) then buildhash = nil end end -- get build hash for current version if not buildhash then buildhash = _get_buildhash(self:_configs_for_buildhash()) end self._BUILDHASH = buildhash end return buildhash end -- get the group name function _instance:group() local requireinfo = self:requireinfo() if requireinfo then return requireinfo.group end end -- get xxx_script function _instance:script(name, generic) -- get script local script = self:get(name) local result = select_script(script, {plat = self:plat(), arch = self:arch()}) or generic -- imports some modules first if result and result ~= generic then local scope = getfenv(result) if scope then for _, modulename in ipairs(table.wrap(self:get("imports"))) do scope[sandbox_module.name(modulename)] = sandbox_module.import(modulename, {anonymous = true}) end end end return result end -- do fetch tool function _instance:_fetch_tool(opt) opt = opt or {} local fetchinfo local on_fetch = self:script("fetch") if on_fetch then fetchinfo = on_fetch(self, {force = opt.force, system = opt.system, require_version = opt.require_version}) if fetchinfo and opt.require_version and opt.require_version:find(".", 1, true) then local version = type(fetchinfo) == "table" and fetchinfo.version if not (version and (version == opt.require_version or semver.satisfies(version, opt.require_version))) then fetchinfo = nil end end end -- we can disable to fallback fetch if on_fetch return false if fetchinfo == nil then self._find_tool = self._find_tool or sandbox_module.import("lib.detect.find_tool", {anonymous = true}) if opt.system then local fetchnames = {} if not self:is_thirdparty() then table.join2(fetchnames, self:extsources()) end table.insert(fetchnames, self:name()) for _, fetchname in ipairs(fetchnames) do fetchinfo = self:find_tool(fetchname, opt) if fetchinfo then break end end else fetchinfo = self:find_tool(self:name(), {require_version = opt.require_version, cachekey = "fetch_package_xmake", norun = true, -- we don't need to run it to check for xmake/packages, @see https://github.com/xmake-io/xmake-repo/issues/66 system = false, -- we only find it from xmake/packages, @see https://github.com/xmake-io/xmake-repo/pull/2085 force = opt.force}) -- may be toolset, not single tool if not fetchinfo then fetchinfo = self:manifest_load() end end end return fetchinfo or nil end -- do fetch library -- -- @param opt the options, e.g. {force, system, external, require_version} -- function _instance:_fetch_library(opt) opt = opt or {} local fetchinfo local on_fetch = self:script("fetch") if on_fetch then -- we cannot fetch it from system if it's cross-compilation package if not opt.system or (opt.system and not self:is_cross()) then fetchinfo = on_fetch(self, {force = opt.force, system = opt.system, external = opt.external, require_version = opt.require_version}) end if fetchinfo and opt.require_version and opt.require_version:find(".", 1, true) then local version = fetchinfo.version if not (version and (version == opt.require_version or semver.satisfies(version, opt.require_version))) then fetchinfo = nil end end if fetchinfo then local components_base = fetchinfo.components and fetchinfo.components.__base if opt.external then fetchinfo.sysincludedirs = fetchinfo.sysincludedirs or fetchinfo.includedirs fetchinfo.includedirs = nil if components_base then components_base.sysincludedirs = components_base.sysincludedirs or components_base.includedirs components_base.includedirs = nil end else fetchinfo.includedirs = fetchinfo.includedirs or fetchinfo.sysincludedirs fetchinfo.sysincludedirs = nil if components_base then components_base.includedirs = components_base.includedirs or components_base.sysincludedirs components_base.sysincludedirs = nil end end end if fetchinfo and option.get("verbose") then local reponame = self:repo() and self:repo():name() or "" utils.cprint("checking for %s::%s ... ${color.success}%s %s", reponame, self:name(), self:name(), fetchinfo.version and fetchinfo.version or "") end end if fetchinfo == nil then if opt.system then local fetchnames = {} if not self:is_thirdparty() then table.join2(fetchnames, self:extsources()) end table.insert(fetchnames, self:name()) for _, fetchname in ipairs(fetchnames) do local components_extsources = {} for name, comp in pairs(self:components()) do for _, extsource in ipairs(table.wrap(comp:get("extsources"))) do local extsource_info = extsource:split("::") if fetchname:split("::")[1] == extsource_info[1] then components_extsources[name] = extsource_info[2] break end end end fetchinfo = self:find_package(fetchname, table.join(opt, {components_extsources = components_extsources})) if fetchinfo then break end end else fetchinfo = self:find_package("xmake::" .. self:name(), { require_version = opt.require_version, cachekey = "fetch_package_xmake", external = opt.external, force = opt.force}) end end return fetchinfo or nil end -- find tool function _instance:find_tool(name, opt) opt = opt or {} self._find_tool = self._find_tool or sandbox_module.import("lib.detect.find_tool", {anonymous = true}) return self._find_tool(name, {cachekey = opt.cachekey or "fetch_package_system", installdir = self:installdir({readonly = true}), bindirs = self:get("bindirs"), version = true, -- we alway check version require_version = opt.require_version, norun = opt.norun, system = opt.system, force = opt.force}) end -- find package function _instance:find_package(name, opt) opt = opt or {} self._find_package = self._find_package or sandbox_module.import("lib.detect.find_package", {anonymous = true}) local system = opt.system if system == nil and not name:startswith("xmake::") then system = true -- find system package by default end local configs = table.clone(self:configs()) or {} if opt.configs then table.join2(configs, opt.configs) end if configs.runtimes then configs.runtimes = self:runtimes() end return self._find_package(name, { force = opt.force, installdir = self:installdir({readonly = true}), bindirs = self:get("bindirs"), version = true, -- we alway check version require_version = opt.require_version, mode = self:mode(), plat = self:plat(), arch = self:arch(), configs = configs, components = self:components_orderlist(), components_extsources = opt.components_extsources, buildhash = self:buildhash(), -- for xmake package or 3rd package manager, e.g. go:: .. cachekey = opt.cachekey or "fetch_package_system", external = opt.external, system = system, -- the following options is only for system::find_package sourcekind = opt.sourcekind, package = self, funcs = opt.funcs, snippets = opt.snippets, includes = opt.includes}) end -- fetch the local package info -- -- @param opt the fetch option, e.g. {force = true, external = false, system = true} -- -- @return {packageinfo}, fetchfrom (e.g. xmake/system) -- function _instance:fetch(opt) -- init options opt = opt or {} -- attempt to get it from cache local fetchinfo = self._FETCHINFO local usecache = opt.external == nil and opt.system == nil if not opt.force and usecache and fetchinfo then return fetchinfo end -- fetch the require version local require_ver = opt.version or self:requireinfo().version if not self:is_thirdparty() and not require_ver:find('.', 1, true) then -- strip branch version only system package require_ver = nil end -- nil: find xmake or system packages -- true: only find system package -- false: only find xmake packages local system = opt.system if system == nil then system = self:requireinfo().system end if self:is_thirdparty() then -- we need ignore `{system = true/false}` argument if be 3rd package -- @see https://github.com/xmake-io/xmake/issues/726 system = nil end -- install only? local project = package._project() if project and project.policy("package.install_only") then system = false end -- use sysincludedirs/-isystem instead of -I? local external if opt.external ~= nil then external = opt.external else external = self:use_external_includes() end -- always install to the local project directory? -- @see https://github.com/xmake-io/xmake/pull/4376 local install_locally if project and project.policy("package.install_locally") then install_locally = true end if install_locally == nil and self:policy("package.install_locally") then install_locally = true end if not self:is_local() and install_locally and system ~= true then local has_global = os.isfile(self:manifest_file()) self:_mark_as_local(true) if has_global and not os.isfile(self:manifest_file()) then self:_mark_as_local(false) end end -- fetch binary tool? fetchinfo = nil local is_system = nil if self:is_binary() then -- only fetch it from the xmake repository first if not fetchinfo and system ~= true and not self:is_thirdparty() then fetchinfo = self:_fetch_tool({require_version = self:version_str(), force = opt.force}) if fetchinfo then is_system = self._is_system end end -- fetch it from the system directories (disabled for cross-compilation) if not fetchinfo and system ~= false and not self:is_cross() then fetchinfo = self:_fetch_tool({system = true, require_version = require_ver, force = opt.force}) if fetchinfo then is_system = true end end else -- only fetch it from the xmake repository first if not fetchinfo and system ~= true and not self:is_thirdparty() then fetchinfo = self:_fetch_library({require_version = self:version_str(), external = external, force = opt.force}) if fetchinfo then is_system = self._is_system end end -- fetch it from the system and external package sources if not fetchinfo and system ~= false then fetchinfo = self:_fetch_library({system = true, require_version = require_ver, external = external, force = opt.force}) if fetchinfo then is_system = true end end end -- save to cache if usecache then self._FETCHINFO = fetchinfo end -- we need to update the real version if it's system package -- @see https://github.com/xmake-io/xmake/issues/3333 if is_system and fetchinfo and fetchinfo.version then local fetch_version = semver.new(fetchinfo.version) if fetch_version then self._VERSION = fetch_version self._VERSION_STR = fetchinfo.version end end -- mark as system package? if is_system ~= nil then self._is_system = is_system end return fetchinfo end -- exists this package? function _instance:exists() return self._FETCHINFO ~= nil end -- fetch library dependencies function _instance:fetch_librarydeps() local fetchinfo = self:fetch() if not fetchinfo then return end fetchinfo = table.copy(fetchinfo) -- avoid the cached fetchinfo be modified local librarydeps = self:librarydeps() if librarydeps then for _, dep in ipairs(librarydeps) do local depinfo = dep:fetch() if depinfo then for name, values in pairs(depinfo) do if name ~= "license" and name ~= "version" then fetchinfo[name] = table.wrap(fetchinfo[name]) table.join2(fetchinfo[name], values) end end end end end if fetchinfo then for name, values in pairs(fetchinfo) do if name == "links" or name == "syslinks" or name == "frameworks" then fetchinfo[name] = table.unwrap(table.reverse_unique(table.wrap(values))) else fetchinfo[name] = table.unwrap(table.unique(table.wrap(values))) end end end return fetchinfo end -- get the patches of the current version -- -- @code -- add_patches("6.7.6", "https://cdn.kernel.org/pub/linux/kernel/v6.x/patch-6.7.6.xz", -- "a394326aa325f8a930a4ce33c69ba7b8b454aef1107a4d3c2a8ae12908615fc4", {reverse = true}) -- @endcode -- function _instance:patches() local patches = self._PATCHES if patches == nil then local patchinfos = self:get("patches") if patchinfos then local version_str = self:version_str() local patchinfo = patchinfos[version_str] if patchinfo then patches = {} patchinfo = table.wrap(patchinfo) for idx = 1, #patchinfo, 2 do local extra = self:extraconf("patches." .. version_str, patchinfo[idx]) table.insert(patches , {url = patchinfo[idx], sha256 = patchinfo[idx + 1], extra = extra}) end else -- match semver, e.g add_patches(">=1.0.0", url, sha256) for range, patchinfo in pairs(patchinfos) do if semver.satisfies(version_str, range) then patches = patches or {} patchinfo = table.wrap(patchinfo) for idx = 1, #patchinfo, 2 do local extra = self:extraconf("patches." .. range, patchinfo[idx]) table.insert(patches , {url = patchinfo[idx], sha256 = patchinfo[idx + 1], extra = extra}) end end end end end self._PATCHES = patches or false end return patches and patches or nil end -- get the resources of the current version function _instance:resources() local resources = self._RESOURCES if resources == nil then local resourceinfos = self:get("resources") if resourceinfos then local version_str = self:version_str() local resourceinfo = resourceinfos[version_str] if resourceinfo then resources = {} resourceinfo = table.wrap(resourceinfo) for idx = 1, #resourceinfo, 3 do local name = resourceinfo[idx] resources[name] = {url = resourceinfo[idx + 1], sha256 = resourceinfo[idx + 2]} end else -- match semver, e.g add_resources(">=1.0.0", name, url, sha256) for range, resourceinfo in pairs(resourceinfos) do if semver.satisfies(version_str, range) then resources = resources or {} resourceinfo = table.wrap(resourceinfo) for idx = 1, #resourceinfo, 3 do local name = resourceinfo[idx] resources[name] = {url = resourceinfo[idx + 1], sha256 = resourceinfo[idx + 2]} end end end end end self._RESOURCES = resources or false end return resources and resources or nil end -- get the the given resource function _instance:resource(name) local resources = self:resources() return resources and resources[name] or nil end -- get the the given resource file function _instance:resourcefile(name) local resource = self:resource(name) if resource and resource.url then return path.join(self:cachedir(), "resources", name, (path.filename(resource.url):gsub("%?.+$", ""))) end end -- get the the given resource directory function _instance:resourcedir(name) local resource = self:resource(name) if resource and resource.url then return path.join(self:cachedir(), "resources", name, (path.filename(resource.url):gsub("%?.+$", "")) .. ".dir") end end -- get the given package component function _instance:component(name) return self:components()[name] end -- get package components -- -- .e.g. add_components("graphics", "windows") -- function _instance:components() local components = self._COMPONENTS if not components then components = {} for _, name in ipairs(table.wrap(self:get("components"))) do components[name] = component.new(name, {package = self}) end self._COMPONENTS = components end return components end -- get package dependencies of components -- -- @see https://github.com/xmake-io/xmake/issues/2636#issuecomment-1284787681 -- -- @code -- add_components("graphics", {deps = "window"}) -- @endcode -- -- or -- -- @code -- on_component(function (package, component)) -- component:add("deps", "window") -- end) -- @endcode -- function _instance:components_deps() local components_deps = self._COMPONENTS_DEPS if not components_deps then components_deps = {} for _, name in ipairs(table.wrap(self:get("components"))) do components_deps[name] = self:extraconf("components", name, "deps") or self:component(name):get("deps") end self._COMPONENTS_DEPS = component_deps end return components_deps end -- get default components -- -- @see https://github.com/xmake-io/xmake/issues/3164 -- -- @code -- add_components("graphics", {default = true}) -- @endcode -- -- or -- -- @code -- on_component(function (package, component)) -- component:set("default", true) -- end) -- @endcode -- function _instance:components_default() local components_default = self._COMPONENTS_DEFAULT if not components_default then for _, name in ipairs(table.wrap(self:get("components"))) do if self:extraconf("components", name, "default") or self:component(name):get("default") then components_default = components_default or {} table.insert(components_default, name) end end self._COMPONENTS_DEFAULT = components_default or false end return components_default or nil end -- get package components list with dependencies order function _instance:components_orderlist() local components_orderlist = self._COMPONENTS_ORDERLIST if not components_orderlist then components_orderlist = {} for _, name in ipairs(table.wrap(self:get("components"))) do table.insert(components_orderlist, name) table.join2(components_orderlist, self:_sort_componentdeps(name)) end components_orderlist = table.reverse_unique(components_orderlist) self._COMPONENTS_ORDERLIST = components_orderlist end return components_orderlist end -- sort component deps function _instance:_sort_componentdeps(name) local orderdeps = {} local plaindeps = self:components_deps() and self:components_deps()[name] for _, dep in ipairs(table.wrap(plaindeps)) do table.insert(orderdeps, dep) table.join2(orderdeps, self:_sort_componentdeps(dep)) end return orderdeps end -- generate lto configs function _instance:_generate_lto_configs(sourcekind) -- add cflags local configs = {} if sourcekind then local _, cc = self:tool(sourcekind) local cflag = sourcekind == "cxx" and "cxxflags" or "cflags" if cc == "cl" then configs[cflag] = "-GL" elseif cc == "clang" or cc == "clangxx" then configs[cflag] = "-flto=thin" elseif cc == "gcc" or cc == "gxx" then configs[cflag] = "-flto" end end -- add ldflags and shflags local _, ld = self:tool("ld") if ld == "link" then configs.ldflags = "-LTCG" configs.shflags = "-LTCG" elseif ld == "clang" or ld == "clangxx" then configs.ldflags = "-flto=thin" configs.shflags = "-flto=thin" elseif ld == "gcc" or ld == "gxx" then configs.ldflags = "-flto" configs.shflags = "-flto" end return configs end -- generate sanitizer configs function _instance:_generate_sanitizer_configs(checkmode, sourcekind) -- add cflags local configs = {} if sourcekind and self:has_tool(sourcekind, "cl", "clang", "clangxx", "gcc", "gxx") then local cflag = sourcekind == "cxx" and "cxxflags" or "cflags" configs[cflag] = "-fsanitize=" .. checkmode end -- add ldflags and shflags if self:has_tool("ld", "link", "clang", "clangxx", "gcc", "gxx") then configs.ldflags = "-fsanitize=" .. checkmode configs.shflags = "-fsanitize=" .. checkmode end return configs end -- generate building configs for has_xxx/check_xxx function _instance:_generate_build_configs(configs, opt) opt = opt or {} configs = table.join(self:fetch_librarydeps() or {}, configs) -- since we are ignoring the runtimes of the headeronly library, -- we can only get the runtimes from the dependency library to detect the link. local runtimes = self:runtimes() if self:is_headeronly() and not runtimes and self:librarydeps() then for _, dep in ipairs(self:librarydeps()) do if dep:is_plat("windows") and dep:runtimes() then runtimes = dep:runtimes() break end end end if runtimes then -- @note we need to patch package:sourcekinds(), because it wiil be called nf_runtime for gcc/clang local sourcekind = opt.sourcekind or "cxx" self.sourcekinds = function (self) return sourcekind end local compiler = self:compiler(sourcekind) local cxflags = compiler:map_flags("runtime", runtimes, {target = self}) configs.cxflags = table.wrap(configs.cxflags) table.join2(configs.cxflags, cxflags) local ldflags = self:linker("binary", sourcekind):map_flags("runtime", runtimes, {target = self}) configs.ldflags = table.wrap(configs.ldflags) table.join2(configs.ldflags, ldflags) local shflags = self:linker("shared", sourcekind):map_flags("runtime", runtimes, {target = self}) configs.shflags = table.wrap(configs.shflags) table.join2(configs.shflags, shflags) self.sourcekinds = nil end if self:config("lto") then local configs_lto = self:_generate_lto_configs(opt.sourcekind or "cxx") if configs_lto then for k, v in pairs(configs_lto) do configs[k] = table.wrap(configs[k] or {}) table.join2(configs[k], v) end end end if self:config("asan") then local configs_asan = self:_generate_sanitizer_configs("address", opt.sourcekind or "cxx") if configs_asan then for k, v in pairs(configs_asan) do configs[k] = table.wrap(configs[k] or {}) table.join2(configs[k], v) end end end -- enable exceptions for msvc by default if opt.sourcekind == "cxx" and configs.exceptions == nil and self:has_tool("cxx", "cl") then configs.exceptions = "cxx" end -- pass user flags to on_test, because some flags need be passed to ldflags in on_test -- e.g. add_requireconfs("**", {configs = {cxflags = "/fsanitize=address", ldflags = "/fsanitize=address"}}) -- -- @see https://github.com/xmake-io/xmake/issues/4046 -- for name, flags in pairs(self:configs()) do if name:endswith("flags") and self:extraconf("configs", name, "builtin") then configs[name] = table.wrap(configs[name] or {}) table.join2(configs[name], flags) end end if configs and (configs.ldflags or configs.shflags) then configs.force = {ldflags = configs.ldflags, shflags = configs.shflags} configs.ldflags = nil configs.shflags = nil end -- check links for library if self:is_library() and not self:is_headeronly() and not self:is_moduleonly() and self:exists() then -- we need to skip it if it's in on_check, @see https://github.com/xmake-io/xmake-repo/pull/4834 local links = table.wrap(configs.links) local ldflags = table.wrap(configs.ldflags) local frameworks = table.wrap(configs.frameworks) if #links == 0 and #ldflags == 0 and #frameworks == 0 then os.raise("package(%s): links not found!", self:name()) end end return configs end -- has the given c funcs? -- -- @param funcs the funcs -- @param opt the argument options, e.g. {includes = "xxx.h", configs = {defines = ""}} -- -- @return true or false, errors -- function _instance:has_cfuncs(funcs, opt) opt = opt or {} opt.target = self opt.configs = self:_generate_build_configs(opt.configs, {sourcekind = "cc"}) return sandbox_module.import("lib.detect.has_cfuncs", {anonymous = true})(funcs, opt) end -- has the given c++ funcs? -- -- @param funcs the funcs -- @param opt the argument options, e.g. {includes = "xxx.h", configs = {defines = ""}} -- -- @return true or false, errors -- function _instance:has_cxxfuncs(funcs, opt) opt = opt or {} opt.target = self opt.configs = self:_generate_build_configs(opt.configs, {sourcekind = "cxx"}) return sandbox_module.import("lib.detect.has_cxxfuncs", {anonymous = true})(funcs, opt) end -- has the given c types? -- -- @param types the types -- @param opt the argument options, e.g. {configs = {defines = ""}} -- -- @return true or false, errors -- function _instance:has_ctypes(types, opt) opt = opt or {} opt.target = self opt.configs = self:_generate_build_configs(opt.configs, {sourcekind = "cc"}) return sandbox_module.import("lib.detect.has_ctypes", {anonymous = true})(types, opt) end -- has the given c++ types? -- -- @param types the types -- @param opt the argument options, e.g. {configs = {defines = ""}} -- -- @return true or false, errors -- function _instance:has_cxxtypes(types, opt) opt = opt or {} opt.target = self opt.configs = self:_generate_build_configs(opt.configs, {sourcekind = "cxx"}) return sandbox_module.import("lib.detect.has_cxxtypes", {anonymous = true})(types, opt) end -- has the given c includes? -- -- @param includes the includes -- @param opt the argument options, e.g. {configs = {defines = ""}} -- -- @return true or false, errors -- function _instance:has_cincludes(includes, opt) opt = opt or {} opt.target = self opt.configs = self:_generate_build_configs(opt.configs, {sourcekind = "cc"}) return sandbox_module.import("lib.detect.has_cincludes", {anonymous = true})(includes, opt) end -- has the given c++ includes? -- -- @param includes the includes -- @param opt the argument options, e.g. {configs = {defines = ""}} -- -- @return true or false, errors -- function _instance:has_cxxincludes(includes, opt) opt = opt or {} opt.target = self opt.configs = self:_generate_build_configs(opt.configs, {sourcekind = "cxx"}) return sandbox_module.import("lib.detect.has_cxxincludes", {anonymous = true})(includes, opt) end -- has the given c flags? -- -- @param flags the flags -- @param opt the argument options, e.g. { flagskey = "xxx" } -- -- @return true or false, errors -- function _instance:has_cflags(flags, opt) local compinst = self:compiler("cc") return compinst:has_flags(flags, "cflags", opt) end -- has the given c++ flags? -- -- @param flags the flags -- @param opt the argument options, e.g. { flagskey = "xxx" } -- -- @return true or false, errors -- function _instance:has_cxxflags(flags, opt) local compinst = self:compiler("cxx") return compinst:has_flags(flags, "cxxflags", opt) end -- has the given features? -- -- @param features the features, e.g. {"c_static_assert", "cxx_constexpr"} -- @param opt the argument options, e.g. {flags = ""} -- -- @return true or false, errors -- function _instance:has_features(features, opt) opt = opt or {} opt.target = self return sandbox_module.import("core.tool.compiler", {anonymous = true}).has_features(features, opt) end -- check the size of type -- -- @param typename the typename -- @param opt the argument options, e.g. {includes = "xxx.h", configs = {defines = ""}} -- -- @return the type size -- function _instance:check_sizeof(typename, opt) opt = opt or {} opt.target = self return sandbox_module.import("lib.detect.check_sizeof", {anonymous = true})(typename, opt) end -- check the given c snippets? -- -- @param snippets the snippets -- @param opt the argument options, e.g. {includes = "xxx.h", configs = {defines = ""}} -- -- @return true or false, errors -- function _instance:check_csnippets(snippets, opt) opt = opt or {} opt.target = self opt.configs = self:_generate_build_configs(opt.configs, {sourcekind = "cc"}) return sandbox_module.import("lib.detect.check_csnippets", {anonymous = true})(snippets, opt) end -- check the given c++ snippets? -- -- @param snippets the snippets -- @param opt the argument options, e.g. {includes = "xxx.h", configs = {defines = ""}} -- -- @return true or false, errors -- function _instance:check_cxxsnippets(snippets, opt) opt = opt or {} opt.target = self opt.configs = self:_generate_build_configs(opt.configs, {sourcekind = "cxx"}) return sandbox_module.import("lib.detect.check_cxxsnippets", {anonymous = true})(snippets, opt) end -- check the given objc snippets? -- -- @param snippets the snippets -- @param opt the argument options, e.g. {includes = "xxx.h", configs = {defines = ""}} -- -- @return true or false, errors -- function _instance:check_msnippets(snippets, opt) opt = opt or {} opt.target = self opt.configs = self:_generate_build_configs(opt.configs, {sourcekind = "mm"}) return sandbox_module.import("lib.detect.check_msnippets", {anonymous = true})(snippets, opt) end -- check the given objc++ snippets? -- -- @param snippets the snippets -- @param opt the argument options, e.g. {includes = "xxx.h", configs = {defines = ""}} -- -- @return true or false, errors -- function _instance:check_mxxsnippets(snippets, opt) opt = opt or {} opt.target = self opt.configs = self:_generate_build_configs(opt.configs, {sourcekind = "mxx"}) return sandbox_module.import("lib.detect.check_mxxsnippets", {anonymous = true})(snippets, opt) end -- the current mode is belong to the given modes? function package._api_is_mode(interp, ...) return config.is_mode(...) end -- the current platform is belong to the given platforms? function package._api_is_plat(interp, ...) local plat = package.targetplat() for _, v in ipairs(table.join(...)) do if v and plat == v then return true end end end -- the current platform is belong to the given architectures? function package._api_is_arch(interp, ...) local arch = package.targetarch() for _, v in ipairs(table.join(...)) do if v and arch:find("^" .. v:gsub("%-", "%%-") .. "$") then return true end end end -- the current host is belong to the given hosts? function package._api_is_host(interp, ...) return os.is_host(...) end -- the interpreter function package._interpreter() local interp = package._INTERPRETER if not interp then interp = interpreter.new() interp:api_define(package.apis()) interp:api_define(language.apis()) package._INTERPRETER = interp end return interp end -- get package memcache function package._memcache() return memcache.cache("core.base.package") end -- get project function package._project() local project = package._PROJECT if not project then if os.isfile(os.projectfile()) then project = require("project/project") end end return project end -- get global target platform of package function package.targetplat() local plat = package._memcache():get("target_plat") if plat == nil then if not plat and package._project() then local targetplat_root = package._project().get("target.plat") if targetplat_root then plat = targetplat_root end end if not plat then plat = config.get("plat") or os.subhost() end package._memcache():set("target_plat", plat) end return plat end -- get global target architecture of pacakge function package.targetarch() local arch = package._memcache():get("target_arch") if arch == nil then if not arch and package._project() then local targetarch_root = package._project().get("target.arch") if targetarch_root then arch = targetarch_root end end if not arch then arch = config.get("arch") or os.subarch() end package._memcache():set("target_arch", arch) end return arch end -- get package apis function package.apis() return { values = { -- package.set_xxx "package.set_urls" , "package.set_kind" , "package.set_plat" -- deprecated , "package.set_arch" -- deprecated , "package.set_base" , "package.set_license" , "package.set_homepage" , "package.set_description" , "package.set_parallelize" , "package.set_sourcedir" , "package.set_cachedir" , "package.set_installdir" , "package.add_bindirs" -- package.add_xxx , "package.add_deps" , "package.add_urls" , "package.add_imports" , "package.add_configs" , "package.add_extsources" , "package.add_components" } , script = { -- package.on_xxx "package.on_source" , "package.on_load" , "package.on_fetch" , "package.on_check" , "package.on_download" , "package.on_install" , "package.on_test" , "package.on_component" } , keyvalues = { -- package.set_xxx "package.set_policy" -- package.add_xxx , "package.add_patches" , "package.add_resources" } , paths = { -- package.add_xxx "package.add_versionfiles" } , dictionary = { -- package.add_xxx "package.add_versions" } , custom = { -- is_xxx { "is_host", package._api_is_host } , { "is_mode", package._api_is_mode } , { "is_plat", package._api_is_plat } , { "is_arch", package._api_is_arch } } } end -- the cache directory function package.cachedir(opt) opt = opt or {} local cachedir = package._CACHEDIR if not cachedir then cachedir = os.getenv("XMAKE_PKG_CACHEDIR") or global.get("pkg_cachedir") or path.join(global.cachedir(), "packages") package._CACHEDIR = cachedir end if opt.rootonly then return cachedir end return path.join(cachedir, os.date("%y%m")) end -- the install directory function package.installdir() local installdir = package._INSTALLDIR if not installdir then installdir = os.getenv("XMAKE_PKG_INSTALLDIR") or global.get("pkg_installdir") or path.join(global.directory(), "packages") package._INSTALLDIR = installdir end return installdir end -- the search directories function package.searchdirs() local searchdirs = global.get("pkg_searchdirs") if searchdirs then return path.splitenv(searchdirs) end end -- load the package from the system directories function package.load_from_system(packagename) -- get it directly from cache first local instance = package._memcache():get2("packages", packagename) if instance then return instance end -- get package info local packageinfo = {} local is_thirdparty = false if packagename:find("::", 1, true) then -- get interpreter local interp = package._interpreter() -- on install script local on_install = function (pkg) local opt = {} local configs = table.clone(pkg:configs()) or {} opt.configs = configs opt.mode = pkg:is_debug() and "debug" or "release" opt.plat = pkg:plat() opt.arch = pkg:arch() opt.require_version = pkg:version_str() opt.buildhash = pkg:buildhash() opt.cachedir = pkg:cachedir() opt.installdir = pkg:installdir() if configs.runtimes then configs.runtimes = pkg:runtimes() end import("package.manager.install_package")(pkg:name(), opt) end -- make sandbox instance with the given script instance, errors = sandbox.new(on_install, interp:filter()) if not instance then return nil, errors end -- save the install script packageinfo.install = instance:script() -- is third-party package? if not packagename:startswith("xmake::") then is_thirdparty = true end end -- new an instance instance = _instance.new(packagename, scopeinfo.new("package", packageinfo)) -- mark as system or 3rd package instance._is_system = true instance._is_thirdparty = is_thirdparty if is_thirdparty then -- add configurations for the 3rd package local configurations = sandbox_module.import("package.manager." .. packagename:split("::")[1]:lower() .. ".configurations", {try = true, anonymous = true}) if configurations then for name, conf in pairs(configurations()) do instance:add("configs", name, conf) end end -- disable parallelize for installation instance:set("parallelize", false) end -- save instance to the cache package._memcache():set2("packages", instance) return instance end -- load the package from the project file function package.load_from_project(packagename, project) -- get it directly from cache first local instance = package._memcache():get2("packages", packagename) if instance then return instance end -- load packages (with cache) local packages, errors = project.packages() if not packages then return nil, errors end -- get package info local packageinfo = packages[packagename] if not packageinfo then return end -- new an instance instance = _instance.new(packagename, packageinfo) package._memcache():set2("packages", instance) return instance end -- load the package from the package directory or package description file function package.load_from_repository(packagename, packagedir, opt) -- get it directly from cache first opt = opt or {} local instance = package._memcache():get2("packages", packagename) if instance then return instance end -- load repository first for checking the xmake minimal version (deprecated) local repo = opt.repo if repo then repo:load() end -- find the package script path local scriptpath = opt.packagefile if not opt.packagefile and packagedir then scriptpath = path.join(packagedir, "xmake.lua") end if not scriptpath or not os.isfile(scriptpath) then return nil, string.format("package %s not found!", packagename) end -- get interpreter local interp = package._interpreter() -- we need to modify plat/arch in description scope at same time -- if plat/arch are passed to add_requires. -- -- @see https://github.com/orgs/xmake-io/discussions/3439 -- -- e.g. add_requires("zlib~mingw", {plat = "mingw", arch = "x86_64"}) -- if opt.plat then package._memcache():set("target_plat", opt.plat) end if opt.arch then package._memcache():set("target_arch", opt.arch) end -- load script local ok, errors = interp:load(scriptpath) if not ok then return nil, errors end -- load package and disable filter, we will process filter after a while local results, errors = interp:make("package", true, false) if not results then return nil, errors end -- get package info local packageinfo = results[packagename] if not packageinfo then return nil, string.format("%s: package(%s) not found!", scriptpath, packagename) end -- new an instance instance = _instance.new(packagename, packageinfo, {scriptdir = path.directory(scriptpath), repo = repo}) -- reset plat/arch if opt.plat then package._memcache():set("target_plat", nil) end if opt.arch then package._memcache():set("target_arch", nil) end -- save instance to the cache package._memcache():set2("packages", instance) return instance end -- new a package instance function package.new(...) return _instance.new(...) end -- return module return package
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/dialog.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 dialog.lua -- -- load modules local log = require("ui/log") local rect = require("ui/rect") local event = require("ui/event") local label = require("ui/label") local panel = require("ui/panel") local action = require("ui/action") local button = require("ui/button") local window = require("ui/window") local curses = require("ui/curses") -- define module local dialog = dialog or window() -- update the position of all buttons function dialog:_update_buttons_layout() -- update the position of all buttons local index = 1 local width = self:buttons():width() local count = self:buttons():count() local padding = math.floor(width / 8) for v in self:buttons():views() do local x = padding + index * math.floor((width - padding * 2) / (count + 1)) - math.floor(v:width() / 2) if x + v:width() > width then x = math.max(0, width - v:width()) end v:bounds():move2(x, 0) v:invalidate(true) index = index + 1 end end -- init dialog function dialog:init(name, bounds, title) -- init window window.init(self, name, bounds, title, true) -- insert buttons self:panel():insert(self:buttons()) self:panel():action_add(action.ac_on_resized, function (v) self:buttons():bounds_set(rect:new(0, v:height() - 1, v:width(), 1)) self:_update_buttons_layout() end) -- mark as block mouse self:option_set("blockmouse", true) end -- get buttons function dialog:buttons() if not self._BUTTONS then self._BUTTONS = panel:new("dialog.buttons", rect:new(0, self:panel():height() - 1, self:panel():width(), 1)) end return self._BUTTONS end -- get button from the given button name function dialog:button(name) return self:buttons():view(name) end -- add button function dialog:button_add(name, text, command) -- init button local btn = button:new(name, rect:new(0, 0, #text, 1), text, command) -- insert button self:buttons():insert(btn) -- update the position of all buttons self:_update_buttons_layout() -- invalidate self:invalidate() -- ok return btn end -- select button from the given button name function dialog:button_select(name) self:buttons():select(self:button(name)) return self end -- quit dialog function dialog:quit() local parent = self:parent() if parent then self:action_on(action.ac_on_exit) parent:remove(self) end end -- on event function dialog:on_event(e) if e.type == event.ev_keyboard and e.key_name == "Esc" then self:quit() return true end return window.on_event(self, e) end -- return module return dialog
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/textdialog.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 textdialog.lua -- -- load modules local log = require("ui/log") local rect = require("ui/rect") local event = require("ui/event") local dialog = require("ui/dialog") local curses = require("ui/curses") local textarea = require("ui/textarea") local scrollbar = require("ui/scrollbar") local action = require("ui/action") -- define module local textdialog = textdialog or dialog() -- init dialog function textdialog:init(name, bounds, title) -- init window dialog.init(self, name, bounds, title) -- mark as scrollable, disabled by default self:option_set("scrollable", false) -- insert text self:panel():insert(self:text()) -- insert scrollbar self:panel():insert(self:scrollbar()) -- select buttons by default self:panel():select(self:buttons()) -- on resize for panel self:panel():action_add(action.ac_on_resized, function (v) if self:option("scrollable") then self:text():bounds_set(rect:new(0, 0, v:width() - 1, v:height() - 1)) self:scrollbar():bounds_set(rect:new(v:width() - 1, 0, 1, v:height() - 1)) else self:text():bounds_set(rect:new(0, 0, v:width(), v:height() - 1)) end end) -- show scrollbar? self:text():action_add(action.ac_on_text_changed, function (v) if self:option("scrollable") then if v:scrollable() then self:scrollbar():show(true) else self:scrollbar():show(false) end end end) -- on scroll for text and scrollbar self:text():action_add(action.ac_on_scrolled, function (v, progress) if self:scrollbar():state("visible") then self:scrollbar():progress_set(progress) end end) end -- enable or disable scrollbar function textdialog:option_set(name, value) if name == "scrollable" then local oldvalue = self:option(name) if value ~= oldvalue then if value then self:text():bounds():resize(self:panel():width() - 1, self:panel():height() - 1) else self:text():bounds():resize(self:panel():width(), self:panel():height() - 1) end end end dialog.option_set(self, name, value) end -- get text function textdialog:text() if not self._TEXT then self._TEXT = textarea:new("textdialog.text", rect:new(0, 0, self:panel():width(), self:panel():height() - 1)) end return self._TEXT end -- get scrollbar function textdialog:scrollbar() if not self._SCROLLBAR then self._SCROLLBAR = scrollbar:new("textdialog.scrollbar", rect:new(self:panel():width() - 1, 0, 1, self:panel():height() - 1)) self._SCROLLBAR:show(false) end return self._SCROLLBAR end -- on event function textdialog:on_event(e) -- pass event to dialog if dialog.on_event(self, e) then return true end -- pass keyboard event to text area to scroll if e.type == event.ev_keyboard then return self:text():on_event(e) end end -- return module return textdialog
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/point.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 point.lua -- -- load modules local object = require("ui/object") -- define module local point = point or object { _init = {"x", "y"} } -- add delta x and y function point:addxy(dx, dy) self.x = self.x + dx self.y = self.y + dy return self end -- add point function point:add(p) return self:addxy(p.x, p.y) end -- sub delta x and y function point:subxy(dx, dy) return self:addxy(-dx, -dy) end -- sub point function point:sub(p) return self:addxy(-p.x, -p.y) end -- p1 + p2 function point:__add(p) local np = self() np.x = np.x + p.x np.y = np.y + p.y return np end -- p1 - p2 function point:__sub(p) local np = self() np.x = np.x - p.x np.y = np.y - p.y return np end -- -p function point:__unm() local p = self() p.x = -p.x p.y = -p.y return p end -- p1 == p2? function point:__eq(p) return self.x == p.x and self.y == p.y end -- tostring(p) function point:__tostring() return '(' .. self.x .. ', ' .. self.y .. ')' end -- p1 .. p2 function point.__concat(op1, op2) if type(op1) == 'string' then return op1 .. op2:__tostring() elseif type(op2) == 'string' then return op1:__tostring() .. op2 else return op1:__tostring() .. op2:__tostring() end end -- return module return point
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/button.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 button.lua -- -- load modules local log = require("ui/log") local view = require("ui/view") local event = require("ui/event") local label = require("ui/label") local action = require("ui/action") local curses = require("ui/curses") -- define module local button = button or label() -- init button function button:init(name, bounds, text, on_action) -- init label label.init(self, name, bounds, text) -- mark as selectable self:option_set("selectable", true) -- show cursor self:cursor_show(true) -- init actions self:option_set("mouseable", true) self:action_set(action.ac_on_enter, on_action) self:action_set(action.ac_on_clicked, function (v) v:action_on(action.ac_on_enter) return true end) end -- draw button function button:on_draw(transparent) -- draw background view.on_draw(self, transparent) -- strip text string local str = self:text() if str and #str > 0 then str = string.sub(str, 1, self:width()) end if not str or #str == 0 then return end -- get the text attribute value local textattr = self:textattr_val() -- selected? if self:state("selected") and self:state("focused") then textattr = {textattr, "reverse"} end -- draw text self:canvas():attr(textattr):move(0, 0):putstr(str) end -- on event function button:on_event(e) -- selected? if not self:state("selected") then return end -- enter this button? if e.type == event.ev_keyboard then if e.key_name == "Enter" then self:action_on(action.ac_on_enter) return true end end end -- set state function button:state_set(name, enable) if name == "focused" and self:state(name) ~= enable then self:invalidate() end return view.state_set(self, name, enable) end -- return module return button
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/rect.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 rect.lua -- -- load modules local point = require("ui/point") local object = require("ui/object") -- define module local rect = rect or object { _init = {"sx", "sy", "ex", "ey"} } -- make rect function rect:new(x, y, w, h) return rect { x, y, x + w, y + h } end -- get rect size function rect:size() return point { self.ex - self.sx, self.ey - self.sy } end -- get width function rect:width() return self.ex - self.sx end -- get height function rect:height() return self.ey - self.sy end -- resize rect function rect:resize(w, h) self.ex = self.sx + w self.ey = self.sy + h end -- move rect function rect:move(dx, dy) self.sx = self.sx + dx self.sy = self.sy + dy self.ex = self.ex + dx self.ey = self.ey + dy return self end -- move rect to the given position function rect:move2(x, y) local w = self.ex - self.sx local h = self.ey - self.sy self.sx = x self.sy = y self.ex = x + w self.ey = y + h return self end -- move top right corner of the rect function rect:moves(dx, dy) self.sx = self.sx + dx self.sy = self.sy + dy return self end -- move bottom left corner of the rect function rect:movee(dx, dy) self.ex = self.ex + dx self.ey = self.ey + dy return self end -- expand rect area function rect:grow(dx, dy) self.sx = self.sx - dx self.sy = self.sy - dy self.ex = self.ex + dx self.ey = self.ey + dy return self end -- is intersect? function rect:is_intersect(r) return not self():intersect(r):empty() end -- set rect with shared area between this rect and a given rect function rect:intersect(r) self.sx = math.max(self.sx, r.sx) self.sy = math.max(self.sy, r.sy) self.ex = math.min(self.ex, r.ex) self.ey = math.min(self.ey, r.ey) return self end -- get rect with shared area between two rects: local rect_new = r1 / r2 function rect:__div(r) return self():intersect(r) end -- set union rect function rect:union(r) self.sx = math.min(self.sx, r.sx) self.sy = math.min(self.sy, r.sy) self.ex = math.max(self.ex, r.ex) self.ey = math.max(self.ey, r.ey) return self end -- get union rect: local rect_new = r1 + r2 function rect:__add(r) return self():union(r) end -- r1 == r1? function rect:__eq(r) return self.sx == r.sx and self.sy == r.sy and self.ex == r.ex and self.ey == r.ey end -- contains the given point in rect? function rect:contains(x, y) return x >= self.sx and x < self.ex and y >= self.sy and y < self.ey end -- empty rect? function rect:empty() return self.sx >= self.ex or self.sy >= self.ey end -- tostring(r) function rect:__tostring() if self:empty() then return '[]' end return string.format("[%d, %d, %d, %d]", self.sx, self.sy, self.ex, self.ey) end -- r1 .. r2 function rect.__concat(op1, op2) if type(op1) == 'string' then return op1 .. op2:__tostring() elseif type(op2) == 'string' then return op1:__tostring() .. op2 else return op1:__tostring() .. op2:__tostring() end end -- return module return rect
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/application.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 application.lua -- -- load modules local os = require("base/os") local utils = require("base/utils") local log = require("ui/log") local rect = require("ui/rect") local event = require("ui/event") local curses = require("ui/curses") local program = require("ui/program") local desktop = require("ui/desktop") local menubar = require("ui/menubar") local statusbar = require("ui/statusbar") -- define module local application = application or program() -- init application function application:init(name, argv) -- init log log:clear() -- log:enable(false) -- trace log:print("<application: %s>: init ..", name) -- init program program.init(self, name, argv) -- trace log:print("<application: %s>: init ok", name) end -- exit application function application:exit() -- exit program program.exit(self) -- flush log log:flush() end -- get menubar function application:menubar() if not self._MENUBAR then self._MENUBAR = menubar:new("menubar", rect{0, 0, self:width(), 1}) end return self._MENUBAR end -- get desktop function application:desktop() if not self._DESKTOP then self._DESKTOP = desktop:new("desktop", rect{0, 1, self:width(), self:height() - 1}) end return self._DESKTOP end -- get statusbar function application:statusbar() if not self._STATUSBAR then self._STATUSBAR = statusbar:new("statusbar", rect{0, self:height() - 1, self:width(), self:height()}) end return self._STATUSBAR end -- on event function application:on_event(e) program.on_event(self, e) end -- on resize function application:on_resize() self:menubar():bounds_set(rect{0, 0, self:width(), 1}) self:desktop():bounds_set(rect{0, 1, self:width(), self:height() - 1}) self:statusbar():bounds_set(rect{0, self:height() - 1, self:width(), self:height()}) program.on_resize(self) end -- run application function application:run(...) assert(curses.done, "ncurses not found, please install it first.") -- init runner local argv = {...} local runner = function () -- new an application local app = self:new(argv) if app then app:loop() app:exit() end end -- run application local ok, errors = utils.trycall(runner) -- exit curses if not ok then if not curses.isdone() then curses.done() end log:flush() os.raise(errors) end end -- return module return application
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/canvas.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 canvas.lua -- -- load modules local log = require("ui/log") local point = require("ui/point") local object = require("ui/object") local curses = require("ui/curses") -- define module local line = line or object() local canvas = canvas or object() -- new canvas instance function canvas:new(view, window) -- create instance self = self() -- save view and window self._view = view self._window = window assert(view and window, "cannot new canvas instance without view and window!") -- set the default attributes self:attr() -- done return self end -- clear canvas function canvas:clear() self._window:clear() return self end -- move canvas to the given position function canvas:move(x, y) self._window:move(y, x) return self end -- get the current position function canvas:pos() local y, x = self._window:getyx() return x, y end -- get the canvas size function canvas:size() local y, x = self._window:getmaxyx() return point {x + 1, y + 1} end -- get the canvas width function canvas:width() local _, x = self._window:getmaxyx() return x + 1 end -- get the canvas height function canvas:height() local y, _ = self._window:getmaxyx() return y + 1 end -- put character to canvas function canvas:putchar(ch, n, vertical) -- acs character? if type(ch) == "string" and #ch > 1 then ch = curses.acs(ch) end -- draw characters n = n or 1 if vertical then local x, y = self:pos() while n > 0 do self:move(x, y) self._window:addch(ch) n = n - 1 y = y + 1 end else while n > 0 do self._window:addch(ch) n = n - 1 end end return self end -- put a string to canvas function canvas:putstr(str) self._window:addstr(str) return self end -- put strings to canvas function canvas:putstrs(strs, startline) -- draw strings local sy, sx = self._window:getyx() local ey, _ = self._window:getmaxyx() for idx = startline or 1, #strs do local _, y = self:pos() self._window:addstr(strs[idx]) if y + 1 < ey and idx < #strs then self:move(sx, y + 1) else break end end return self end -- set canvas attributes -- -- set attr: canvas:attr("bold") -- add attr: canvas:attr("bold", true) -- remove attr: canvas:attr("bold", false) -- function canvas:attr(attrs, modify) -- calculate the attributes local attr = curses.calc_attr(attrs) if modify == nil then self._window:attrset(attr) elseif modify == false then self._window:attroff(attr) else self._window:attron(attr) end return self end -- return module return canvas
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/curses.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 curses.lua -- -- define module: curses local curses = curses or {} -- load modules local os = require("base/os") local log = require("ui/log") -- get color from the given name function curses.color(name) if name == 'black' then return curses.COLOR_BLACK elseif name == 'red' then return curses.COLOR_RED elseif name == 'green' then return curses.COLOR_GREEN elseif name == 'yellow' then return curses.COLOR_YELLOW elseif name == 'blue' then return curses.COLOR_BLUE elseif name == 'magenta' then return curses.COLOR_MAGENTA elseif name == 'cyan' then return curses.COLOR_CYAN elseif name == 'white' then return curses.COLOR_WHITE else return curses.COLOR_BLACK end end -- is color? local colors = {black = true, red = true, green = true, yellow = true, blue = true, magenta = true, cyan = true, white = true} function curses.iscolor(name) return colors[name] or colors[name:sub(3) or ""] end -- get attr from the given name function curses.attr(name) if name == 'normal' then return curses.A_NORMAL elseif name == 'standout' then return curses.A_STANDOUT elseif name == 'underline' then return curses.A_UNDERLINE elseif name == 'reverse' then return curses.A_REVERSE elseif name == 'blink' then return curses.A_BLINK elseif name == 'dim' then return curses.A_DIM elseif name == 'bold' then return curses.A_BOLD elseif name == 'protect' then return curses.A_PROTECT elseif name == 'invis' then return curses.A_INVIS elseif name == 'alt' then return curses.A_ALTCHARSET else return curses.A_NORMAL end end -- get acs character from the given name function curses.acs(name) if name == 'block' then return curses.ACS_BLOCK elseif name == 'board' then return curses.ACS_BOARD elseif name == 'btee' then return curses.ACS_BTEE elseif name == 'bullet' then return curses.ACS_BULLET elseif name == 'ckboard' then return curses.ACS_CKBOARD elseif name == 'darrow' then return curses.ACS_DARROW elseif name == 'degree' then return curses.ACS_DEGREE elseif name == 'diamond' then return curses.ACS_DIAMOND elseif name == 'gequal' then return curses.ACS_GEQUAL elseif name == 'hline' then return curses.ACS_HLINE elseif name == 'lantern' then return curses.ACS_LANTERN elseif name == 'larrow' then return curses.ACS_LARROW elseif name == 'lequal' then return curses.ACS_LEQUAL elseif name == 'llcorner' then return curses.ACS_LLCORNER elseif name == 'lrcorner' then return curses.ACS_LRCORNER elseif name == 'ltee' then return curses.ACS_LTEE elseif name == 'nequal' then return curses.ACS_NEQUAL elseif name == 'pi' then return curses.ACS_PI elseif name == 'plminus' then return curses.ACS_PLMINUS elseif name == 'plus' then return curses.ACS_PLUS elseif name == 'rarrow' then return curses.ACS_RARROW elseif name == 'rtee' then return curses.ACS_RTEE elseif name == 's1' then return curses.ACS_S1 elseif name == 's3' then return curses.ACS_S3 elseif name == 's7' then return curses.ACS_S7 elseif name == 's9' then return curses.ACS_S9 elseif name == 'sterling' then return curses.ACS_STERLING elseif name == 'ttee' then return curses.ACS_TTEE elseif name == 'uarrow' then return curses.ACS_UARROW elseif name == 'ulcorner' then return curses.ACS_ULCORNER elseif name == 'urcorner' then return curses.ACS_URCORNER elseif name == 'vline' then return curses.ACS_VLINE elseif type(name) == 'string' and #name == 1 then return name else return ' ' end end -- calculate attr from the attributes list -- -- local attr = curses.calc_attr("bold") -- local attr = curses.calc_attr("yellow") -- local attr = curses.calc_attr{ "yellow", "ongreen" } -- local attr = curses.calc_attr{ "yellow", "ongreen", "bold" } -- local attr = curses.calc_attr{ curses.color_pair("yellow", "green"), "bold" } -- function curses.calc_attr(attrs) -- curses.calc_attr(curses.A_BOLD) -- curses.calc_attr(curses.color_pair("yellow", "green")) local atype = type(attrs) if atype == "number" then return attrs -- curses.calc_attr("bold") -- curses.calc_attr("yellow") elseif atype == "string" then if curses.iscolor(attrs) then local color = attrs if color:startswith("on") then color = color:sub(3) end return curses.color_pair(color, color) end return curses.attr(attrs) -- curses.calc_attr{ "yellow", "ongreen", "bold" } -- curses.calc_attr{ curses.color_pair("yellow", "green"), "bold" } elseif atype == "table" then local v = 0 local set = {} local fg = nil local bg = nil for _, a in ipairs(attrs) do if not set[a] and a then set[a] = true if type(a) == "number" then v = v + a elseif curses.iscolor(a) then if a:startswith("on") then bg = a:sub(3) else fg = a end else v = v + curses.attr(a) end end end if fg or bg then v = v + curses.color_pair(fg or bg, bg or fg) end return v else return 0 end end -- get attr from the color pair curses._color_pair = curses._color_pair or curses.color_pair function curses.color_pair(fg, bg) -- get foreground and backround color fg = curses.color(fg) bg = curses.color(bg) -- attempt to get color from the cache first local key = fg .. ':' .. bg local colors = curses._COLORS or {} if colors[key] then return colors[key] end -- no colors? if not curses.has_colors() then return 0 end -- update the colors count curses._NCOLORS = (curses._NCOLORS or 0) + 1 -- init the color pair if not curses.init_pair(curses._NCOLORS, fg, bg) then os.raise("failed to initialize color pair (%d, %s, %s)", curses._NCOLORS, fg, bg) end -- get the color attr local attr = curses._color_pair(curses._NCOLORS) -- save to cache colors[key] = attr curses._COLORS = colors -- ok return attr end -- set cursor state curses._cursor_set = curses._cursor_set or curses.cursor_set function curses.cursor_set(state) if curses._CURSOR_STATE ~= state then curses._CURSOR_STATE = state curses._cursor_set(state) end end -- has mouse? function curses.has_mouse() return curses.KEY_MOUSE and true or false end -- return module: curses return curses
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/inputdialog.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 inputdialog.lua -- -- load modules local log = require("ui/log") local rect = require("ui/rect") local view = require("ui/view") local event = require("ui/event") local action = require("ui/action") local curses = require("ui/curses") local window = require("ui/window") local textedit = require("ui/textedit") local textdialog = require("ui/textdialog") -- define module local inputdialog = inputdialog or textdialog() -- init dialog function inputdialog:init(name, bounds, title) -- init window textdialog.init(self, name, bounds, title) -- insert textedit self:panel():insert(self:textedit()) -- resize text self:text():bounds().ey = 1 self:text():invalidate(true) self:text():option_set("selectable", false) -- text changed self:text():action_set(action.ac_on_text_changed, function (v) if v:text() then local lines = #self:text():splitext(v:text()) + 1 if lines > 0 and lines < self:height() then self:text():bounds().ey = lines self:textedit():bounds().sy = lines self:text():invalidate(true) self:textedit():invalidate(true) end end end) -- on resize for panel self:panel():action_add(action.ac_on_resized, function (v) self:textedit():bounds_set(rect{0, 1, v:width(), v:height() - 1}) end) end -- get textedit function inputdialog:textedit() if not self._TEXTEDIT then self._TEXTEDIT = textedit:new("inputdialog.textedit", rect{0, 1, self:panel():width(), self:panel():height() - 1}) end return self._TEXTEDIT end -- return module return inputdialog
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/desktop.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 desktop.lua -- -- load modules local log = require("ui/log") local rect = require("ui/rect") local view = require("ui/view") local panel = require("ui/panel") local curses = require("ui/curses") -- define module local desktop = desktop or panel() -- init desktop function desktop:init(name, bounds) -- init panel panel.init(self, name, bounds) -- init background self:background_set("blue") end -- return module return desktop
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/mconfdialog.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 mconfdialog.lua -- -- load modules local table = require("base/table") local log = require("ui/log") local rect = require("ui/rect") local event = require("ui/event") local action = require("ui/action") local curses = require("ui/curses") local window = require("ui/window") local scrollbar = require("ui/scrollbar") local menuconf = require("ui/menuconf") local boxdialog = require("ui/boxdialog") local textdialog = require("ui/textdialog") local inputdialog = require("ui/inputdialog") local choicedialog = require("ui/choicedialog") -- define module local mconfdialog = mconfdialog or boxdialog() -- init dialog function mconfdialog:init(name, bounds, title) -- init window boxdialog.init(self, name, bounds, title) -- init text self:text():text_set([[Arrow keys navigate the menu. <Enter> selects submenus ---> (or empty submenus ----). Pressing <Y> includes, <N> excludes. Enter <Esc> or <Back> to go back, <?> for Help, </> for Search. Legend: [*] built-in [ ] excluded ]]) -- init buttons self:button_add("select", "< Select >", function (v, e) self:menuconf():on_event(event.command {"cm_enter"}) end) self:button_add("back", "< Back >", function (v, e) self:menuconf():on_event(event.command {"cm_back"}) self:buttons():select(self:button("select")) end) self:button_add("exit", "< Exit >", function (v, e) self:show_exit([[Did you wish to save your new configuration? (Pressing <Esc> to continue your configuration.)]]) end) self:button_add("help", "< Help >", function (v, e) self:show_help() end) self:button_add("save", "< Save >", function (v, e) self:action_on(action.ac_on_save) end) self:buttons():select(self:button("select")) -- insert scrollbar self:box():panel():insert(self:scrollbar_menuconf()) -- insert menu config self:box():panel():insert(self:menuconf()) self:box():panel():action_add(action.ac_on_resized, function (v) local bounds = self:box():panel():bounds() self:menuconf():bounds_set(rect:new(0, 0, bounds:width(), bounds:height())) end) -- disable to select to box (disable Tab switch and only response to buttons) self:box():option_set("selectable", false) -- on resize for panel self:box():panel():action_add(action.ac_on_resized, function (v) self:menuconf():bounds_set(rect:new(0, 0, v:width() - 1, v:height())) self:scrollbar_menuconf():bounds_set(rect:new(v:width() - 1, 0, 1, v:height())) if self:menuconf():scrollable() then self:scrollbar_menuconf():show(true) else self:scrollbar_menuconf():show(false) end end) -- on selected self:menuconf():action_set(action.ac_on_selected, function (v, config) -- show input dialog if config.kind == "string" or config.kind == "number" then local dialog_input = self:inputdialog() dialog_input:extra_set("config", config) dialog_input:title():text_set(config:prompt()) dialog_input:textedit():text_set(tostring(config.value)) dialog_input:panel():select(dialog_input:textedit()) if config.kind == "string" then dialog_input:text():text_set("Please enter a string value. Use the <TAB> key to move from the input fields to buttons below it.") else dialog_input:text():text_set("Please enter a decimal value. Fractions will not be accepted. Use the <TAB> key to move from the input field to the buttons below it.") end self:insert(dialog_input, {centerx = true, centery = true}) return true -- show choice dialog elseif config.kind == "choice" and config.values and #config.values > 0 then local dialog_choice = self:choicedialog() dialog_choice:title():text_set(config:prompt()) dialog_choice:choicebox():load(config.values, config.value) dialog_choice:choicebox():action_set(action.ac_on_selected, function (v, index, value) config.value = index end) self:insert(dialog_choice, {centerx = true, centery = true}) return true end end) -- show scrollbar? self:menuconf():action_add(action.ac_on_load, function (v) if v:scrollable() then self:scrollbar_menuconf():show(true) else self:scrollbar_menuconf():show(false) end end) -- on scroll self:menuconf():action_add(action.ac_on_scrolled, function (v, progress) if self:scrollbar_menuconf():state("visible") then self:scrollbar_menuconf():progress_set(progress) end end) end -- load configs function mconfdialog:load(configs) self._CONFIGS = configs return self:menuconf():load(configs) end -- get configs function mconfdialog:configs() return self._CONFIGS end -- get menu config function mconfdialog:menuconf() if not self._MENUCONF then local bounds = self:box():panel():bounds() self._MENUCONF = menuconf:new("mconfdialog.menuconf", rect:new(0, 0, bounds:width() - 1, bounds:height())) self._MENUCONF:state_set("focused", true) -- we can select and highlight selected item end return self._MENUCONF end -- get menu scrollbar function mconfdialog:scrollbar_menuconf() if not self._SCROLLBAR_MENUCONF then local bounds = self:box():panel():bounds() self._SCROLLBAR_MENUCONF = scrollbar:new("mconfdialog.scrollbar", rect:new(bounds:width() - 1, 0, 1, bounds:height())) self._SCROLLBAR_MENUCONF:show(false) end return self._SCROLLBAR_MENUCONF end -- get help dialog function mconfdialog:helpdialog() if not self._HELPDIALOG then local helpdialog = textdialog:new("mconfdialog.help", self:bounds(), "help") helpdialog:button_add("exit", "< Exit >", function (v) helpdialog:quit() end) helpdialog:option_set("scrollable", true) self._HELPDIALOG = helpdialog end return self._HELPDIALOG end -- get result dialog function mconfdialog:resultdialog() if not self._RESULTDIALOG then local resultdialog = textdialog:new("mconfdialog.result", self:bounds(), "result") resultdialog:button_add("exit", "< Exit >", function (v) resultdialog:quit() end) resultdialog:option_set("scrollable", true) self._RESULTDIALOG = resultdialog end return self._RESULTDIALOG end -- get input dialog function mconfdialog:inputdialog() if not self._INPUTDIALOG then local dialog_input = inputdialog:new("mconfdialog.input", rect{0, 0, math.min(80, self:width() - 8), math.min(8, self:height())}, "input dialog") dialog_input:background_set(self:frame():background()) dialog_input:frame():background_set("cyan") dialog_input:textedit():option_set("multiline", false) dialog_input:button_add("ok", "< Ok >", function (v) local config = dialog_input:extra("config") if config.kind == "string" then config.value = dialog_input:textedit():text() elseif config.kind == "number" then local value = tonumber(dialog_input:textedit():text()) if value ~= nil then config.value = value end end dialog_input:quit() end) dialog_input:button_add("cancel", "< Cancel >", function (v) dialog_input:quit() end) dialog_input:button_select("ok") self._INPUTDIALOG = dialog_input end return self._INPUTDIALOG end -- get choice dialog function mconfdialog:choicedialog() if not self._CHOICEDIALOG then local dialog_choice = choicedialog:new("mconfdialog.choice", rect{0, 0, math.min(80, self:width() - 8), math.min(20, self:height())}, "input dialog") dialog_choice:background_set(self:frame():background()) dialog_choice:frame():background_set("cyan") dialog_choice:box():frame():background_set("cyan") self._CHOICEDIALOG = dialog_choice end return self._CHOICEDIALOG end -- get search dialog function mconfdialog:searchdialog() if not self._SEARCHDIALOG then local dialog_search = inputdialog:new("mconfdialog.input", rect{0, 0, math.min(80, self:width() - 8), math.min(8, self:height())}, "Search Configuration Parameter") dialog_search:background_set(self:frame():background()) dialog_search:frame():background_set("cyan") dialog_search:textedit():option_set("multiline", false) dialog_search:text():text_set("Enter (sub)string or lua pattern string to search for configuration") dialog_search:button_add("ok", "< Ok >", function (v) local configs = self:search(self:configs(), dialog_search:textedit():text()) local results = "Search('" .. dialog_search:textedit():text() .. "') results:" for _, config in ipairs(configs) do results = results .. "\n" .. config:prompt() if config.kind then results = results .. "\nkind: " .. config.kind end if config.default then results = results .. "\ndefault: " .. tostring(config.default) end if config.path then results = results .. "\npath: " .. config.path end if config.sourceinfo then results = results .. "\nposition: " .. (config.sourceinfo.file or "") .. ":" .. (config.sourceinfo.line or "-1") end results = results .. "\n" end self:show_result(results) dialog_search:quit() end) dialog_search:button_add("cancel", "< Cancel >", function (v) dialog_search:quit() end) dialog_search:button_select("ok") self._SEARCHDIALOG = dialog_search end return self._SEARCHDIALOG end -- get exit dialog function mconfdialog:exitdialog() if not self._EXITDIALOG then local exitdialog = textdialog:new("mconfdialog.exit", rect{0, 0, math.min(60, self:width() - 8), math.min(7, self:height())}, "") exitdialog:background_set(self:frame():background()) exitdialog:frame():background_set("cyan") exitdialog:button_add("Yes", "< Yes >", function (v) self:action_on(action.ac_on_save) end) exitdialog:button_add("No", "< No >", function (v) self:quit() end) exitdialog:option_set("scrollable", false) exitdialog:button_select("Yes") self._EXITDIALOG = exitdialog end return self._EXITDIALOG end -- search configs via the given text function mconfdialog:search(configs, text) local results = {} for _, config in ipairs(configs) do local prompt = config:prompt() if prompt and prompt:find(text) then table.insert(results, config) end if config.kind == "menu" then table.join2(results, self:search(config.configs, text)) end end return results end -- show help dialog function mconfdialog:show_help() if self:parent() then -- get the current config item local item = self:menuconf():current() -- get the current config local config = item:extra("config") -- set help title self:helpdialog():title():text_set(config:prompt()) -- set help text local text = config.description if type(text) == "table" then text = table.concat(text, '\n') end if config.kind then text = text .. "\ntype: " .. config.kind end if config.kind == "choice" then if config.default and config.values[config.default] then text = text .. "\ndefault: " .. config.values[config.default] end text = text .. "\nvalues: " for _, value in ipairs(config.values) do text = text .. "\n - " .. value end elseif config.default then text = text .. "\ndefault: " .. tostring(config.default) end if config.path then text = text .. "\npath: " .. config.path end if config.sourceinfo then text = text .. "\nposition: " .. (config.sourceinfo.file or "") .. ":" .. (config.sourceinfo.line or "-1") end self:helpdialog():text():text_set(text) -- show help self:parent():insert(self:helpdialog()) end end -- show search dialog function mconfdialog:show_search() local dialog_search = self:searchdialog() dialog_search:panel():select(dialog_search:textedit()) self:insert(dialog_search, {centerx = true, centery = true}) end -- show result dialog function mconfdialog:show_result(text) local dialog_result = self:resultdialog() dialog_result:text():text_set(text) if not self:view("mconfdialog.result") then self:insert(dialog_result, {centerx = true, centery = true}) else self:select(dialog_result) end end -- show exit dialog function mconfdialog:show_exit(text) local dialog_exit = self:exitdialog() dialog_exit:text():text_set(text) if not self:view("mconfdialog.exit") then self:insert(dialog_exit, {centerx = true, centery = true}) else self:select(dialog_exit) end end -- on event function mconfdialog:on_event(e) -- select config if e.type == event.ev_keyboard then if e.key_name == "Down" or e.key_name == "Up" or e.key_name == " " or e.key_name == "Esc" or e.key_name:lower() == "y" or e.key_name:lower() == "n" then return self:menuconf():on_event(e) elseif e.key_name == "?" then self:show_help() return true elseif e.key_name == "/" then self:show_search() return true end end return boxdialog.on_event(self, e) end -- on resize function mconfdialog:on_resize() if self._HELPDIALOG then self:helpdialog():bounds_set(self:bounds()) end if self._RESULTDIALOG then self:resultdialog():bounds_set(self:bounds()) self:center(self:resultdialog(), {centerx = true, centery = true}) end if self._INPUTDIALOG then self:inputdialog():bounds_set(rect{0, 0, math.min(80, self:width() - 8), math.min(8, self:height())}) self:center(self:inputdialog(), {centerx = true, centery = true}) end if self._CHOICEDIALOG then self:choicedialog():bounds_set(rect{0, 0, math.min(80, self:width() - 8), math.min(20, self:height())}) self:center(self:choicedialog(), {centerx = true, centery = true}) end if self._SEARCHDIALOG then self:searchdialog():bounds_set(rect{0, 0, math.min(80, self:width() - 8), math.min(8, self:height())}) self:center(self:searchdialog(), {centerx = true, centery = true}) end boxdialog.on_resize(self) end -- return module return mconfdialog
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/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 -- -- return module: object return require("base/object")
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/log.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 log.lua -- -- get log local log = log or (function () -- load modules local os = require("base/os") local path = require("base/path") local table = require("base/table") -- get log directory local logdir = nil if os.isfile(os.projectfile()) then logdir = path.join(os.projectdir(), "." .. xmake._NAME) else logdir = os.tmpdir() end -- return module: log local instance = table.inherit(require("base/log")) if instance then instance._FILE = nil instance._LOGFILE = path.join(logdir, "ui.log") end return instance end)() return log
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/textedit.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 textedit.lua -- -- load modules local log = require("ui/log") local view = require("ui/view") local label = require("ui/label") local event = require("ui/event") local border = require("ui/border") local curses = require("ui/curses") local textarea = require("ui/textarea") local action = require("ui/action") local bit = require("base/bit") -- define module local textedit = textedit or textarea() -- init textedit function textedit:init(name, bounds, text) -- init label textarea.init(self, name, bounds, text) -- show cursor self:cursor_show(true) -- mark as selectable self:option_set("selectable", true) -- mark as mouseable self:option_set("mouseable", true) self:action_set(action.ac_on_clicked, function () return true end) -- enable multiple line self:option_set("multiline", true) end -- draw textedit function textedit:on_draw(transparent) -- draw label textarea.on_draw(self, transparent) -- move cursor if not self:text() or #self:text() == 0 then self:cursor_move(0, 0) else self:cursor_move(self:canvas():pos()) end end -- set text function textedit:text_set(text) textarea.text_set(self, text) self:scroll_to_end() return self end -- on event function textedit:on_event(e) -- update text if e.type == event.ev_keyboard then if e.key_name == "Enter" and self:option("multiline") then self:text_set(self:text() .. '\n') return true elseif e.key_name == "Backspace" then local text = self:text() if #text > 0 then local size = 1 -- while continuation byte while bit.band(text:byte(#text - size + 1), 0xc0) == 0x80 do size = size + 1 end self:text_set(text:sub(1, #text - size)) end return true elseif e.key_name == "CtrlV" then local pastetext = os.pbpaste() if pastetext then self:text_set(self:text() .. pastetext) end return true elseif e.key_code > 0x1f and e.key_code < 0xf8 then self:text_set(self:text() .. string.char(e.key_code)) return true end end -- do textarea event return textarea.on_event(self, e) end -- return module return textedit
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/menuconf.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 menuconf.lua -- -- load modules local log = require("ui/log") local view = require("ui/view") local rect = require("ui/rect") local panel = require("ui/panel") local event = require("ui/event") local action = require("ui/action") local curses = require("ui/curses") local button = require("ui/button") local object = require("ui/object") -- define module local menuconf = menuconf or panel() -- init menuconf function menuconf:init(name, bounds) -- init panel panel.init(self, name, bounds) -- init configs self._CONFIGS = {} -- init items self._ITEMS = {} -- init start index self._STARTINDEX = 1 end -- load configs function menuconf:load(configs) -- clear the views first self:clear() -- reset start index self._STARTINDEX = 1 -- detach the previous config and view local configs_prev = self._CONFIGS._PREV if configs_prev then for _, config in ipairs(configs_prev) do config._view = nil end end -- save configs self._CONFIGS = configs -- load items local items = {} for idx, config in ipairs(configs) do table.insert(items, self:_load_item(config, idx)) end self._ITEMS = items -- insert top-n items local startindex = self._STARTINDEX for idx = startindex, startindex + self:height() - 1 do local item = items[idx] if item then self:insert(item) else break end end -- select the first item self:select(self:first()) -- on loaded self:action_on(action.ac_on_load) -- invalidate self:invalidate() end -- is scrollable? function menuconf:scrollable() return #self:_items() > self:height() end -- scroll function menuconf:scroll(count) if self:scrollable() then local items = self:_items() local totalcount = #items local startindex = self._STARTINDEX + count if startindex > totalcount then return elseif startindex < 1 then startindex = 1 end self._STARTINDEX = startindex self:clear() for idx = startindex, startindex + self:height() - 1 do local item = items[idx] if item then item:bounds():move2(0, idx - startindex) self:insert(item) else break end end if count > 0 then self:select(self:first()) else self:select(self:last()) end self:invalidate() end end -- on resize function menuconf:on_resize() local items = self:_items() local totalcount = #items local startindex = self._STARTINDEX for idx = 1, totalcount do local item = items[idx] if item then if idx >= startindex and idx < startindex + self:height() then if not self:view(item:name()) then item:bounds():move2(0, idx - startindex) self:insert(item) end else if self:view(item:name()) then self:remove(item) end end end end panel.on_resize(self) end -- on event function menuconf:on_event(e) local back = false if e.type == event.ev_keyboard then if e.key_name == "Down" then if self:current() == self:last() then self:scroll(self:height()) else self:select_next() end self:_notify_scrolled() return true elseif e.key_name == "Up" then if self:current() == self:first() then self:scroll(-self:height()) else self:select_prev() end self:_notify_scrolled() return true elseif e.key_name == "PageDown" or e.key_name == "PageUp" then local direction = e.key_name == "PageDown" and 1 or -1 self:scroll(self:height() * direction) self:_notify_scrolled() return true elseif e.key_name == "Enter" or e.key_name == " " then self:_do_select() return true elseif e.key_name:lower() == "y" then self:_do_include(true) return true elseif e.key_name:lower() == "n" then self:_do_include(false) return true elseif e.key_name == "Esc" then back = true end elseif e.type == event.ev_command then if e.command == "cm_enter" then self:_do_select() return true elseif e.command == "cm_back" then back = true end end -- back? if back then -- load the previous menu configs local configs_prev = self._CONFIGS._PREV if configs_prev then self._CONFIGS._PREV = configs_prev._PREV self:load(configs_prev) return true end end end -- load a config item function menuconf:_load_item(config, index) -- init a config item view local item = button:new("menuconf.config." .. index, rect:new(0, index - 1, self:width(), 1), tostring(config), function (v, e) self:_do_select() end) -- attach this index and config item:extra_set("index", index) item:extra_set("config", config) -- attach this view config._view = item return item end -- notify scrolled function menuconf:_notify_scrolled() local totalcount = #self:_items() local startindex = self:current():extra("index") self:action_on(action.ac_on_scrolled, startindex / totalcount) end -- get all items function menuconf:_items() return self._ITEMS end -- do select the current config function menuconf:_do_select() -- get the current item local item = self:current() -- get the current config local config = item:extra("config") -- clear new state config.new = false -- do action: on selected if self:action_on(action.ac_on_selected, config) then return end -- select the boolean config if config.kind == "boolean" then config.value = not config.value -- show sub-menu configs elseif config.kind == "menu" and config.configs and #config.configs > 0 then local configs_prev = self._CONFIGS self:load(config.configs) self._CONFIGS._PREV = configs_prev end end -- do include function menuconf:_do_include(enabled) -- get the current item local item = self:current() -- get the current config local config = item:extra("config") -- clear new state config.new = false -- select the boolean config if config.kind == "boolean" then config.value = enabled end end -- init config object -- -- kind -- - {kind = "number/boolean/string/choice/menu"} -- -- description -- - {description = "config item description"} -- - {description = {"config item description", "line2", "line3", "more description ..."}} -- -- boolean config -- - {name = "...", kind = "boolean", value = true, default = true, description = "boolean config item", new = true/false} -- -- number config -- - {name = "...", kind = "number", value = 10, default = 0, description = "number config item", new = true/false} -- -- string config -- - {name = "...", kind = "string", value = "xmake", default = "", description = "string config item", new = true/false} -- -- choice config (value is index) -- - {name = "...", kind = "choice", value = 1, default = 1, description = "choice config item", values = {2, 2, 3, 4, 5}} -- -- menu config -- - {name = "...", kind = "menu", description = "menu config item", configs = {...}} -- local config = config or object{new = true, __index = function (tbl, key) if key == "value" then local val = rawget(tbl, "_value") if val == nil then val = rawget(tbl, "default") end return val end return rawget(tbl, key) end, __newindex = function (tbl, key, val) if key == "value" then key = "_value" end rawset(tbl, key, val) if key == "_value" then local v = rawget(tbl, "_view") -- update the config item text in view if v then v:text_set(tostring(tbl)) end end end} -- the prompt info function config:prompt() -- get text (first line in description) local text = self.description or "" if type(text) == "table" then text = text[1] or "" end return text end -- to string function config:__tostring() -- get text (first line in description) local text = self:prompt() -- get value local value = self.value -- update text if self.kind == "boolean" or (not self.kind and type(value) == "boolean") then -- boolean config? text = (value and "[*] " or "[ ] ") .. text elseif self.kind == "number" or (not self.kind and type(value) == "number") then -- number config? text = " " .. text .. " (" .. tostring(value or 0) .. ")" elseif self.kind == "string" or (not self.kind and type(value) == "string") then -- string config? text = " " .. text .. " (" .. tostring(value or "") .. ")" elseif self.kind == "choice" then -- choice config? if self.values and #self.values > 0 then text = " " .. text .. " (" .. tostring(self.values[value or 1]) .. ")" .. " --->" else text = " " .. text .. " () ----" end elseif self.kind == "menu" then -- menu config? text = " " .. text .. (self.configs and #self.configs > 0 and " --->" or " ----") end -- new config? if self.new and self.kind ~= "choice" and self.kind ~= "menu" then text = text .. " (NEW)" end -- ok return text end -- save config objects menuconf.config = menuconf.config or config menuconf.menu = menuconf.menu or config { kind = "menu", configs = {} } menuconf.number = menuconf.number or config { kind = "number", default = 0 } menuconf.string = menuconf.string or config { kind = "string", default = "" } menuconf.choice = menuconf.choice or config { kind = "choice", default = 1, values = {} } menuconf.boolean = menuconf.boolean or config { kind = "boolean", default = false } -- return module return menuconf
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/action.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 action.lua -- -- load modules local log = require("ui/log") local object = require("ui/object") -- define module local action = action or object { } -- register action types function action:register(tag, ...) local base = self[tag] or 0 local enums = {...} local n = #enums for i = 1, n do self[enums[i]] = i + base end self[tag] = base + n end -- register action enums action:register("ac_max", "ac_on_text_changed", "ac_on_selected", "ac_on_clicked", "ac_on_resized", "ac_on_scrolled", "ac_on_enter", "ac_on_load", "ac_on_save", "ac_on_exit") -- return module return action
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/statusbar.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 statusbar.lua -- -- load modules local log = require("ui/log") local rect = require("ui/rect") local panel = require("ui/panel") local label = require("ui/label") local event = require("ui/event") local curses = require("ui/curses") -- define module local statusbar = statusbar or panel() -- init statusbar function statusbar:init(name, bounds) -- init panel panel.init(self, name, bounds) -- init info self._INFO = label:new("statusbar.info", rect{0, 0, self:width(), self:height()}) self:insert(self:info()) self:info():text_set("Status Bar") self:info():textattr_set("blue") -- init background self:background_set("white") end -- get status info function statusbar:info() return self._INFO end -- return module return statusbar
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/view.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 view.lua -- -- load modules local table = require("base/table") local log = require("ui/log") local rect = require("ui/rect") local point = require("ui/point") local object = require("ui/object") local canvas = require("ui/canvas") local curses = require("ui/curses") local action = require("ui/action") -- define module local view = view or object() -- new view instance function view:new(name, bounds, ...) -- create instance self = self() -- init view self:init(name, bounds, ...) -- done return self end -- init view function view:init(name, bounds) -- check assert(name and type(bounds) == 'table') -- init type self._TYPE = "view" -- init state local state = object() state.visible = true -- view visibility state.cursor_visible = false -- cursor visibility state.block_cursor = false -- block cursor state.selected = false -- is selected? state.focused = false -- is focused? state.redraw = true -- need redraw state.on_refresh = true -- need refresh state.on_resize = true -- need resize self._STATE = state -- init options local options = object() options.selectable = false -- true if window can be selected options.mouseable = false -- false by default self._OPTIONS = options -- init attributes self._ATTRS = object() -- init actions self._ACTIONS = object() -- init extras self._EXTRAS = object() -- init name self._NAME = name -- init cursor self._CURSOR = point{0, 0} -- init bounds and window self:bounds_set(bounds) end -- exit view function view:exit() -- close window if self._WINDOW then self._WINDOW:close() self._WINDOW = nil end end -- get view name function view:name() return self._NAME end -- get view bounds function view:bounds() return self._BOUNDS end -- set window bounds function view:bounds_set(bounds) if bounds and self:bounds() ~= bounds then self._BOUNDS = bounds() self:invalidate(true) end end -- get view width function view:width() return self:bounds():width() end -- get view height function view:height() return self:bounds():height() end -- get view size function view:size() return self:bounds():size() end -- get the parent view function view:parent() return self._PARENT end -- set the parent view function view:parent_set(parent) self._PARENT = parent end -- get the application function view:application() if not self._APPLICATION then local app = self while app:parent() do app = app:parent() end self._APPLICATION = app end return self._APPLICATION end -- get the view window function view:window() if not self._WINDOW then -- create window self._WINDOW = curses.new_pad(self:height() > 0 and self:height() or 1, self:width() > 0 and self:width() or 1) assert(self._WINDOW, "cannot create window!") -- disable cursor self._WINDOW:leaveok(true) end return self._WINDOW end -- get the view canvas function view:canvas() if not self._CANVAS then self._CANVAS = canvas:new(self, self:window()) end return self._CANVAS end -- draw view function view:on_draw(transparent) -- trace log:print("%s: draw (transparent: %s) ..", self, tostring(transparent)) -- draw background if not transparent then local background = self:background() if background then background = curses.color_pair(background, background) self:canvas():attr(background):move(0, 0):putchar(' ', self:width() * self:height()) else self:canvas():clear() end end -- clear mark self:state_set("redraw", false) self:_mark_refresh() end -- refresh view function view:on_refresh() -- refresh to the parent view local parent = self:parent() if parent and self:state("visible") then -- clip bounds with the parent view local bounds = self:bounds() local r = bounds():intersect(rect{0, 0, parent:width(), parent:height()}) if not r:empty() then -- trace log:print("%s: refresh to %s(%d, %d, %d, %d) ..", self, parent:name(), r.sx, r.sy, r.ex, r.ey) -- copy this view to parent view self:window():copy(parent:window(), 0, 0, r.sy, r.sx, r.ey - 1, r.ex - 1) end end end -- resize bounds of inner child views (abstract) function view:on_resize() -- trace log:print("%s: resize ..", self) -- close the previous windows first if self._WINDOW then self._WINDOW:close() self._WINDOW = nil end -- need renew canvas self._CANVAS = nil -- clear mark self:state_set("resize", false) -- do action self:action_on(action.ac_on_resized) end -- show view? -- -- .e.g -- v:show(false) -- v:show(true, {focused = true}) -- function view:show(visible, opt) if self:state("visible") ~= visible then local parent = self:parent() if parent and parent:current() == self and not visible then parent:select_next(nil, true) elseif parent and visible and opt and opt.focused then parent:select(self) end self:state_set("visible", visible) self:invalidate() end end -- invalidate view to redraw it function view:invalidate(bounds) if bounds then self:_mark_resize() end self:_mark_redraw() end -- on event (abstract) -- -- @return true: done and break dispatching, false/nil: continous to dispatch to other views -- function view:on_event(e) end -- get the current event function view:event() return self:parent() and self:parent():event() end -- put an event to view function view:put_event(e) return self:parent() and self:parent():put_event(e) end -- get type function view:type() return self._TYPE end -- set type function view:type_set(t) self._TYPE = t or "view" return self end -- get state function view:state(name) return self._STATE[name] end -- set state function view:state_set(name, enable) -- state not changed? enable = enable or false if self:state(name) == enable then return self end -- change state self._STATE[name] = enable return self end -- get option function view:option(name) return self._OPTIONS[name] end -- set option function view:option_set(name, enable) -- state not changed? enable = enable or false if self:option(name) == enable then return end -- set option self._OPTIONS[name] = enable end -- get attribute function view:attr(name) return self._ATTRS[name] end -- set attribute function view:attr_set(name, value) self._ATTRS[name] = value self:invalidate() return self end -- get extra data function view:extra(name) return self._EXTRAS[name] end -- set extra data function view:extra_set(name, value) self._EXTRAS[name] = value return self end -- set action function view:action_set(name, on_action) self._ACTIONS[name] = on_action return self end -- add action function view:action_add(name, on_action) self._ACTIONS[name] = table.join(table.wrap(self._ACTIONS[name]), on_action) return self end -- do action function view:action_on(name, ...) local on_action = self._ACTIONS[name] if on_action then if type(on_action) == "string" then -- send command if self:application() then self:application():send(on_action) end elseif type(on_action) == "function" then -- do action script return on_action(self, ...) elseif type(on_action) == "table" then for _, on_action_val in ipairs(on_action) do -- we cannot uses the return value of action for multi-actions if type(on_action_val) == "function" then on_action_val(self, ...) end end end end end -- get cursor position function view:cursor() return self._CURSOR end -- move cursor to the given position function view:cursor_move(x, y) self._CURSOR = point{ self:_limit(x, 0, self:width() - 1), self:_limit(y, 0, self:height() - 1) } return self end -- show cursor? function view:cursor_show(visible) if self:state("cursor_visible") ~= visible then self:state_set("cursor_visible", visible) end return self end -- get background function view:background() local background = self:attr("background") if not background and self:parent() then background = self:parent():background() end return background end -- set background, .e.g background_set("blue") function view:background_set(color) return self:attr_set("background", color) end -- limit value range function view:_limit(value, minval, maxval) return math.min(maxval, math.max(value, minval)) end -- need resize view function view:_mark_resize() -- have been marked? if self:state("resize") then return end -- trace log:print("%s: mark as resize", self) -- need resize it self:state_set("resize", true) -- @note we need to trigger on_resize() of the root view and pass it to this subview if self:parent() then self:parent():invalidate(true) end end -- need redraw view function view:_mark_redraw() -- have been marked? if self:state("redraw") then return end -- trace log:print("%s: mark as redraw", self) -- need redraw it self:state_set("redraw", true) -- need redraw it's parent view if this view is invisible if not self:state("visible") and self:parent() then self:parent():_mark_redraw() end end -- need refresh view function view:_mark_refresh() -- have been marked? if self:state("refresh") then return end -- need refresh it if self:state("visible") then self:state_set("refresh", true) end -- need refresh it's parent view if self:parent() then self:parent():_mark_refresh() end end -- tostring(view) function view:__tostring() return string.format("<view(%s) %s>", self:name(), tostring(self:bounds())) end -- return module return view
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/choicebox.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 choicebox.lua -- -- load modules local log = require("ui/log") local view = require("ui/view") local rect = require("ui/rect") local panel = require("ui/panel") local event = require("ui/event") local action = require("ui/action") local curses = require("ui/curses") local button = require("ui/button") local object = require("ui/object") -- define module local choicebox = choicebox or panel() -- init choicebox function choicebox:init(name, bounds) -- init panel panel.init(self, name, bounds) -- init items self._ITEMS = {} -- init start index self._STARTINDEX = 1 end -- load values function choicebox:load(values, selected) -- clear the views first self:clear() -- reset start index self._STARTINDEX = 1 -- load items local items = {} for idx, value in ipairs(values) do table.insert(items, self:_load_item(value, idx, idx == selected)) end self._ITEMS = items -- insert top-n items local startindex = self._STARTINDEX for idx = startindex, startindex + self:height() - 1 do local item = items[idx] if item then self:insert(item) else break end end -- select the first item self:select(self:first()) -- on loaded self:action_on(action.ac_on_load) -- invalidate self:invalidate() end -- is scrollable? function choicebox:scrollable() return #self:_items() > self:height() end -- scroll function choicebox:scroll(count) if self:scrollable() then local items = self:_items() local totalcount = #items local startindex = self._STARTINDEX + count if startindex > totalcount then return elseif startindex < 1 then startindex = 1 end self._STARTINDEX = startindex self:clear() for idx = startindex, startindex + self:height() - 1 do local item = items[idx] if item then item:bounds():move2(0, idx - startindex) self:insert(item) else break end end if count > 0 then self:select(self:first()) else self:select(self:last()) end self:invalidate() end end -- on resize function choicebox:on_resize() local items = self:_items() local totalcount = #items local startindex = self._STARTINDEX for idx = 1, totalcount do local item = items[idx] if item then if idx >= startindex and idx < startindex + self:height() then if not self:view(item:name()) then item:bounds():move2(0, idx - startindex) self:insert(item) end else if self:view(item:name()) then self:remove(item) end end end end panel.on_resize(self) end -- on event function choicebox:on_event(e) if e.type == event.ev_keyboard then if e.key_name == "Down" then if self:current() == self:last() then self:scroll(self:height()) else self:select_next() end self:_notify_scrolled() return true elseif e.key_name == "Up" then if self:current() == self:first() then self:scroll(-self:height()) else self:select_prev() end self:_notify_scrolled() return true elseif e.key_name == "PageDown" or e.key_name == "PageUp" then local direction = e.key_name == "PageDown" and 1 or -1 self:scroll(self:height() * direction) self:_notify_scrolled() return true elseif e.key_name == "Enter" or e.key_name == " " then self:_do_select() return true end elseif e.type == event.ev_command and e.command == "cm_enter" then self:_do_select() return true end end -- load a item with value function choicebox:_load_item(value, index, selected) -- init text local text = (selected and "(X) " or "( ) ") .. tostring(value) -- init a value item view local item = button:new("choicebox.value." .. index, rect:new(0, index - 1, self:width(), 1), text, function (v, e) self:_do_select() end) -- attach index and value item:extra_set("index", index) item:extra_set("value", value) return item end -- notify scrolled function choicebox:_notify_scrolled() local totalcount = #self:_items() local startindex = self:current():extra("index") self:action_on(action.ac_on_scrolled, startindex / totalcount) end -- get all items function choicebox:_items() return self._ITEMS end -- do select the current config function choicebox:_do_select() -- clear selected text for v in self:views() do local text = v:text() if text and text:startswith("(X) ") then local t = v:extra("value") v:text_set("( ) " .. tostring(t)) end end -- get the current item local item = self:current() -- do action: on selected local index = item:extra("index") local value = item:extra("value") self:action_on(action.ac_on_selected, index, value) -- update text item:text_set("(X) " .. tostring(value)) end -- return module return choicebox
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/label.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 label.lua -- -- load modules local log = require("ui/log") local view = require("ui/view") local event = require("ui/event") local action = require("ui/action") local curses = require("ui/curses") local bit = require("base/bit") -- define module local label = label or view() -- init label function label:init(name, bounds, text) -- init view view.init(self, name, bounds) -- init text self:text_set(text) -- init text attribute self:textattr_set("black") end -- draw view function label:on_draw(transparent) -- draw background view.on_draw(self, transparent) -- get the text attribute value local textattr = self:textattr_val() -- draw text string local str = self:text() if str and #str > 0 and textattr then self:canvas():attr(textattr):move(0, 0):putstrs(self:splitext(str)) end end -- get text function label:text() return self._TEXT end -- set text function label:text_set(text) -- set text text = text or "" local changed = self._TEXT ~= text self._TEXT = text -- do action if changed then self:action_on(action.ac_on_text_changed) end self:invalidate() return self end -- get text attribute function label:textattr() return self:attr("textattr") end -- set text attribute, e.g. textattr_set("yellow onblue bold") function label:textattr_set(attr) return self:attr_set("textattr", attr) end -- get the current text attribute value function label:textattr_val() -- get text attribute local textattr = self:textattr() if not textattr then return end -- no text background? use view's background if self:background() and not textattr:find("on") then textattr = textattr .. " on" .. self:background() end -- attempt to get the attribute value from the cache first self._TEXTATTR = self._TEXTATTR or {} local value = self._TEXTATTR[textattr] if value then return value end -- update the cache value = curses.calc_attr(textattr:split("%s")) self._TEXTATTR[textattr] = value return value end -- split text by width function label:splitext(text, width) -- get width width = width or self:width() -- split text first local result = {} local lines = text:split('\n', {strict = true}) for idx = 1, #lines do local line = lines[idx] while #line > width do local size = 0 for i = 1, #line do if bit.band(line:byte(i), 0xc0) ~= 0x80 then size = size + line:wcwidth(i) if size > width then table.insert(result, line:sub(1, i - 1)) line = line:sub(i) break end end end if size <= width then break end end table.insert(result, line) end return result end -- return module return label
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/scrollbar.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 scrollbar.lua -- -- load modules local log = require("ui/log") local view = require("ui/view") local event = require("ui/event") local curses = require("ui/curses") local action = require("ui/action") -- define module local scrollbar = scrollbar or view() -- init scrollbar function scrollbar:init(name, bounds, vertical) -- init view view.init(self, name, bounds) -- init bar attribute self:charattr_set("black on black") -- init bar vertical self:vertical_set(vertical) -- init progress self:progress_set(0) -- init character self:char_set(' ') end -- get bar attribute function scrollbar:charattr() return self:attr("charattr") end -- set bar attribute, .e.g charattr_set("yellow onblue bold") function scrollbar:charattr_set(attr) return self:attr_set("charattr", attr) end -- get the current char attribute value function scrollbar:charattr_val() -- get text attribute local charattr = self:charattr() if not charattr then return end -- no text background? use view's background if self:background() and not charattr:find("on") then charattr = charattr .. " on" .. self:background() end -- attempt to get the attribute value from the cache first self._charattr = self._charattr or {} local value = self._charattr[charattr] if value then return value end -- update the cache value = curses.calc_attr(charattr:split("%s+")) self._charattr[charattr] = value return value end -- get bar character function scrollbar:char() return self:attr("char") or ' ' end -- set bar character function scrollbar:char_set(char) if char ~= self:char() then self:invalidate() end return self:attr_set("char", char) end -- is vertical bar? function scrollbar:vertical() return self:attr("vertical") or true end -- set bar vertical function scrollbar:vertical_set(vertical) return self:attr_set("vertical", vertical) end -- get bar progress function scrollbar:progress() return self:attr("progress") or 0 end -- set bar progress, [0, 1] function scrollbar:progress_set(progress) if progress > 1 then progress = 1 elseif progress < 0 then progress = 0 end if progress ~= self:progress() then self:invalidate() end return self:attr_set("progress", progress) end -- get bar step width function scrollbar:stepwidth() return self:attr("stepwidth") or 0.1 end -- set bar step width, [0, 1] function scrollbar:stepwidth_set(stepwidth) if stepwidth > 1 then stepwidth = 1 elseif stepwidth < 0 then stepwidth = 0 end if stepwidth ~= self:stepwidth() then self:invalidate() end return self:attr_set("stepwidth", stepwidth) end -- draw scrollbar function scrollbar:on_draw(transparent) -- draw background view.on_draw(self, transparent) -- draw bar local char = self:char() local charattr = self:charattr_val() if self:vertical() then local sn = math.ceil(self:height() * self:stepwidth()) local sb = math.floor(self:height() * self:progress()) local se = sb + sn if se > self:height() then sb = self:height() - sn se = self:height() end if se > sb and se - sb <= self:height() then for x = 0, self:width() - 1 do self:canvas():attr(charattr):move(x, sb):putchar(char, se - sb, true) end end else local sn = math.ceil(self:width() * self:stepwidth()) local sb = math.floor(self:width() * self:progress()) local se = sb + sn if se > self:width() then sb = self:width() - sn se = self:width() end if se > sb and se - sb <= self:width() then for y = 0, self:height() - 1 do self:canvas():attr(charattr):move(sb, y):putchar(char, se - sb) end end end end -- scroll bar, e.g. -1 * 0.1, 1 * 0.1 function scrollbar:scroll(steps) steps = steps or 1 self:progress_set(self:progress() + steps * self:stepwidth()) self:action_on(action.ac_on_scrolled, self:progress()) end -- on event function scrollbar:on_event(e) if e.type == event.ev_keyboard then if self:vertical() then if e.key_name == "Up" then self:scroll(-1) return true elseif e.key_name == "Down" then self:scroll(1) return true end else if e.key_name == "Left" then self:scroll(-1) return true elseif e.key_name == "Right" then self:scroll(1) return true end end end end -- return module return scrollbar
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/textarea.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 textarea.lua -- -- load modules local log = require("ui/log") local view = require("ui/view") local label = require("ui/label") local event = require("ui/event") local curses = require("ui/curses") local action = require("ui/action") -- define module local textarea = textarea or label() -- init textarea function textarea:init(name, bounds, text) -- init label label.init(self, name, bounds, text) -- mark as selectable self:option_set("selectable", true) -- init start line self._STARTLINE = 0 self._LINECOUNT = 0 end -- draw textarea function textarea:on_draw(transparent) -- draw background view.on_draw(self, transparent) -- get the text attribute value local textattr = self:textattr_val() -- draw text string local strs = self._SPLITTEXT if strs and #strs > 0 and textattr then self:canvas():attr(textattr):move(0, 0):putstrs(strs, self._STARTLINE + 1) end end -- set text function textarea:text_set(text) self._STARTLINE = 0 self._SPLITTEXT = text and self:splitext(text) or {} self._LINECOUNT = #self._SPLITTEXT return label.text_set(self, text) end -- is scrollable? function textarea:scrollable() return self._LINECOUNT > self:height() end -- scroll function textarea:scroll(lines) if self:scrollable() then self._STARTLINE = self._STARTLINE + lines if self._STARTLINE < 0 then self._STARTLINE = 0 end local startline_end = self._LINECOUNT > self:height() and self._LINECOUNT - self:height() or self._LINECOUNT if self._STARTLINE > startline_end then self._STARTLINE = startline_end end self:action_on(action.ac_on_scrolled, self._STARTLINE / startline_end) self:invalidate() end end -- scroll to end function textarea:scroll_to_end() if self:scrollable() then local startline_end = self._LINECOUNT > self:height() and self._LINECOUNT - self:height() or self._LINECOUNT self._STARTLINE = startline_end self:action_on(action.ac_on_scrolled, self._STARTLINE / startline_end) self:invalidate() end end -- on event function textarea:on_event(e) if e.type == event.ev_keyboard then if e.key_name == "Up" then self:scroll(-5) return true elseif e.key_name == "Down" then self:scroll(5) return true end end end -- return module return textarea
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/window.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 window.lua -- -- load modules local log = require("ui/log") local rect = require("ui/rect") local view = require("ui/view") local label = require("ui/label") local panel = require("ui/panel") local event = require("ui/event") local border = require("ui/border") local curses = require("ui/curses") local action = require("ui/action") -- define module local window = window or panel() -- init window function window:init(name, bounds, title, shadow) -- init panel panel.init(self, name, bounds) -- check bounds assert(self:width() > 4 and self:height() > 3, string.format("%s: too small!", tostring(self))) -- insert shadow if shadow then self._SHADOW = view:new("window.shadow", rect{2, 1, self:width(), self:height()}):background_set("black") self:insert(self:shadow()) self:frame():bounds():movee(-2, -1) self:frame():invalidate(true) end -- insert border self:frame():insert(self:border()) -- insert title if title then self._TITLE = label:new("window.title", rect{0, 0, #title, 1}, title) self:title():textattr_set("blue bold") self:title():action_set(action.ac_on_text_changed, function (v) if v:text() then local bounds = v:bounds() v:bounds():resize(#v:text(), v:height()) bounds:move2(math.max(0, math.floor((self:frame():width() - v:width()) / 2)), bounds.sy) v:invalidate(true) end end) self:frame():insert(self:title(), {centerx = true}) end -- insert panel self:frame():insert(self:panel()) -- insert frame self:insert(self:frame()) end -- get frame function window:frame() if not self._FRAME then self._FRAME = panel:new("window.frame", rect{0, 0, self:width(), self:height()}):background_set("white") end return self._FRAME end -- get panel function window:panel() if not self._PANEL then self._PANEL = panel:new("window.panel", self:frame():bounds()) self._PANEL:bounds():grow(-1, -1) self._PANEL:invalidate(true) end return self._PANEL end -- get title function window:title() return self._TITLE end -- get shadow function window:shadow() return self._SHADOW end -- get border function window:border() if not self._BORDER then self._BORDER = border:new("window.border", self:frame():bounds()) end return self._BORDER end -- on event function window:on_event(e) -- select panel? if e.type == event.ev_keyboard then if e.key_name == "Tab" then return self:panel():select_next() end end end -- on resize function window:on_resize() self:frame():bounds_set(rect{0, 0, self:width(), self:height()}) if self:shadow() then self:shadow():bounds_set(rect{2, 1, self:width(), self:height()}) self:frame():bounds():movee(-2, -1) end self:border():bounds_set(self:frame():bounds()) if self:title() then self:frame():center(self:title(), {centerx = true}) end self:panel():bounds_set(self:frame():bounds()) self:panel():bounds():grow(-1, -1) panel.on_resize(self) end -- return module return window
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/panel.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 panel.lua -- -- load modules local log = require("ui/log") local view = require("ui/view") local rect = require("ui/rect") local event = require("ui/event") local point = require("ui/point") local curses = require("ui/curses") local action = require("ui/action") local list = require("base/list") -- define module local panel = panel or view() -- init panel function panel:init(name, bounds) -- init view view.init(self, name, bounds) -- mark as panel self:type_set("panel") -- mark as selectable self:option_set("selectable", true) -- init child views self._VIEWS = list.new() -- init views cache self._VIEWS_CACHE = {} -- on click action self:option_set("mouseable", true) self:action_set(action.ac_on_clicked, function (v, x, y) -- get relative coordinates x, y = x - v:bounds().sx, y - v:bounds().sy -- try focused first local current = v:current() if current and current:option("mouseable") and (current:option("blockmouse") or current:bounds():contains(x, y)) then return current:action_on(action.ac_on_clicked, x, y) end local p = v:last() while p do if p:option("selectable") and p:bounds():contains(x, y) then if p:option("mouseable") then v:select(p) return p:action_on(action.ac_on_clicked, x, y) end return true end p = v:prev(p) end end) end -- get all child views function panel:views() return self._VIEWS:items() end -- get views count function panel:count() return self._VIEWS:size() end -- is empty? function panel:empty() return self._VIEWS:empty() end -- get the first view function panel:first() return self._VIEWS:first() end -- get the last view function panel:last() return self._VIEWS:last() end -- get the next view function panel:next(v) return self._VIEWS:next(v) end -- get the previous view function panel:prev(v) return self._VIEWS:prev(v) end -- get the current selected child view function panel:current() return self._CURRENT end -- get view from the given name function panel:view(name) return self._VIEWS_CACHE[name] end -- center view function panel:center(v, opt) -- center this view if centerx or centery are set local bounds = v:bounds() local center = false local org = point {bounds.sx, bounds.sy} if opt and opt.centerx then org.x = math.floor((self:width() - v:width()) / 2) center = true end if opt and opt.centery then org.y = math.floor((self:height() - v:height()) / 2) center = true end if center then bounds:move(org.x - bounds.sx, org.y - bounds.sy) v:invalidate(true) end end -- insert view function panel:insert(v, opt) -- check assert(not v:parent() or v:parent() == self) assert(not self:view(v:name()), v:name() .. " has been in this panel!") -- this view has been inserted into this panel? remove it first if v:parent() == self then self:remove(v) end -- center this view if centerx or centery are set self:center(v, opt) -- insert this view self._VIEWS:push(v) -- cache this view self._VIEWS_CACHE[v:name()] = v -- set it's parent view v:parent_set(self) -- select this view if v:option("selectable") then self:select(v) end -- invalidate it self:invalidate() end -- remove view function panel:remove(v, opt) -- check assert(v:parent() == self) -- remove view self._VIEWS:remove(v) self._VIEWS_CACHE[v:name()] = nil -- clear parent v:parent_set(nil) -- select next view if self:current() == v then if opt and opt.select_prev then self:select_prev(nil, true) else self:select_next(nil, true) end end -- invalidate it self:invalidate() end -- clear views function panel:clear() -- clear parents for v in self:views() do v:parent_set(nil) end -- clear views and cache self._VIEWS:clear() self._VIEWS_CACHE = {} -- reset the current view self._CURRENT = nil -- invalidate self:invalidate() end -- select the child view function panel:select(v) -- check assert(v == nil or (v:parent() == self and v:option("selectable"))) -- get the current selected view local current = self:current() if v == current then return end -- undo the previous selected view if current then -- undo the current view first if self:state("focused") then current:state_set("focused", false) end current:state_set("selected", false) end -- update the current selected view self._CURRENT = v -- update the new selected view if v then -- select and focus this view v:state_set("selected", true) if self:state("focused") then v:state_set("focused", true) end end -- ok return v end -- select the next view function panel:select_next(start, reset) -- is empty? if self:empty() then return end -- reset? if reset then self._CURRENT = nil end -- get current view local current = start or self:current() -- select the next view local next = self:next(current) while next ~= current do if next and next:option("selectable") and next:state("visible") then return self:select(next) end next = self:next(next) end end -- select the previous view function panel:select_prev(start, reset) -- is empty? if self:empty() then return end -- reset? if reset then self._CURRENT = nil end -- get current view local current = start or self:current() -- select the previous view local prev = self:prev(current) while prev ~= current do if prev and prev:option("selectable") and prev:state("visible") then return self:select(prev) end prev = self:prev(prev) end end -- on event function panel:on_event(e) -- select view? if e.type == event.ev_keyboard then -- @note we also use '-' to switch them on termux without right/left and -- we cannot use tab, because we still need swith views on windows. e.g. inputdialog -- @see https://github.com/tboox/ltui/issues/11 if e.key_name == "Right" or e.key_name == "-" then return self:select_next() elseif e.key_name == "Left" then return self:select_prev() end end end -- set state function panel:state_set(name, enable) view.state_set(self, name, enable) if name == "focused" and self:current() then self:current():state_set(name, enable) end return self end -- draw panel function panel:on_draw(transparent) -- redraw panel? local redraw = self:state("redraw") -- draw panel background first if redraw then view.on_draw(self, transparent) end -- draw all child views for v in self:views() do if redraw then v:state_set("redraw", true) end if v:state("visible") and (v:state("redraw") or v:type() == "panel") then v:on_draw(transparent) end end end -- resize panel function panel:on_resize() -- resize panel view.on_resize(self) -- resize all child views for v in self:views() do v:state_set("resize", true) if v:state("visible") then v:on_resize() end end end -- refresh panel function panel:on_refresh() -- need not refresh? do not refresh it if not self:state("refresh") or not self:state("visible") then return end -- refresh all child views for v in self:views() do if v:state("refresh") then v:on_refresh() v:state_set("refresh", false) end end -- refresh it view.on_refresh(self) -- clear mark self:state_set("refresh", false) end -- dump all views function panel:dump() log:print("%s", self:_tostring(1)) end -- tostring(panel, level) function panel:_tostring(level) local str = "" if self.views then str = str .. string.format("<%s %s>", self:name(), tostring(self:bounds())) if not self:empty() then str = str .. "\n" end for v in self:views() do for l = 1, level do str = str .. " " end str = str .. panel._tostring(v, level + 1) .. "\n" end else str = tostring(self) end return str end -- tostring(panel) function panel:__tostring() return string.format("<panel(%s) %s>", self:name(), tostring(self:bounds())) end -- return module return panel
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/menubar.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 menubar.lua -- -- load modules local log = require("ui/log") local rect = require("ui/rect") local label = require("ui/label") local panel = require("ui/panel") local curses = require("ui/curses") -- define module local menubar = menubar or panel() -- init menubar function menubar:init(name, bounds) -- init panel panel.init(self, name, bounds) -- init title self._TITLE = label:new("menubar.title", rect{0, 0, self:width(), self:height()}, "Menu Bar") self:insert(self:title()) self:title():textattr_set("red") -- init background self:background_set("white") end -- get title function menubar:title() return self._TITLE end -- return module return menubar
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/boxdialog.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 boxdialog.lua -- -- load modules local log = require("ui/log") local rect = require("ui/rect") local action = require("ui/action") local curses = require("ui/curses") local window = require("ui/window") local textdialog = require("ui/textdialog") -- define module local boxdialog = boxdialog or textdialog() -- init dialog function boxdialog:init(name, bounds, title) -- init window textdialog.init(self, name, bounds, title) -- resize text self._TEXT_EY = 3 self:text():bounds().ey = self._TEXT_EY self:text():invalidate(true) self:text():option_set("selectable", false) -- insert box self:panel():insert(self:box()) -- text changed self:text():action_set(action.ac_on_text_changed, function (v) if v:text() then local lines = #self:text():splitext(v:text()) if lines > 0 and lines < self:height() then self._TEXT_EY = lines self:panel():invalidate(true) end end end) -- select buttons by default self:panel():select(self:buttons()) -- on resize for panel self:panel():action_add(action.ac_on_resized, function (v) self:text():bounds().ey = self._TEXT_EY self:box():bounds_set(rect{0, self._TEXT_EY, v:width(), v:height() - 1}) end) -- on click for frame self:frame():action_set(action.ac_on_clicked, function (v, x, y) -- get relative coordinates x, y = x - v:bounds().sx, y - v:bounds().sy local panel, box = v:parent():panel(), v:parent():box() local px, py = x - panel:bounds().sx, y - panel:bounds().sy -- if coordinates don't match any view try box if panel:option("mouseable") then if panel:action_on(action.ac_on_clicked, x, y) then return true elseif box:option("mouseable") and not box:option("selectable") and box:bounds():contains(px, py) then return box:action_on(action.ac_on_clicked, px, py) end end end) end -- get box function boxdialog:box() if not self._BOX then self._BOX = window:new("boxdialog.box", rect{0, self._TEXT_EY, self:panel():width(), self:panel():height() - 1}) self._BOX:border():cornerattr_set("black", "white") end return self._BOX end -- on resize function boxdialog:on_resize() self:text():text_set(self:text():text()) textdialog.on_resize(self) end -- return module return boxdialog
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/border.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 border.lua -- -- load modules local log = require("ui/log") local rect = require("ui/rect") local view = require("ui/view") local label = require("ui/label") local curses = require("ui/curses") -- define module local border = border or view() -- init border function border:init(name, bounds) -- init view view.init(self, name, bounds) -- check bounds assert(self:width() > 2 and self:height() > 2, string.format("%s: too small!", tostring(self))) end -- draw border function border:on_draw(transparent) -- draw background (transparent) view.on_draw(self, true) -- get corner attribute local cornerattr = self:cornerattr() -- the left-upper attribute local attr_ul = curses.color_pair(cornerattr[1], self:background()) if self:background() == cornerattr[1] then attr_ul = {attr_ul, "bold"} end -- the right-lower attribute local attr_rl = curses.color_pair(cornerattr[2], self:background()) if self:background() == cornerattr[2] then attr_rl = {attr_rl, "bold"} end -- the border characters -- @note acs character will use 2 width on borders (pdcurses), so we use acsii characters instead of them. local iswin = os.host() == "windows" local hline = iswin and '-' or "hline" local vline = iswin and '|' or "vline" local ulcorner = iswin and ' ' or "ulcorner" local llcorner = iswin and ' ' or "llcorner" local urcorner = iswin and ' ' or "urcorner" local lrcorner = iswin and ' ' or "lrcorner" -- draw left and top border self:canvas():attr(attr_ul) self:canvas():move(0, 0):putchar(hline, self:width()) self:canvas():move(0, 0):putchar(ulcorner) self:canvas():move(0, 1):putchar(vline, self:height() - 1, true) self:canvas():move(0, self:height() - 1):putchar(llcorner) -- draw bottom and right border self:canvas():attr(attr_rl) self:canvas():move(1, self:height() - 1):putchar(hline, self:width() - 1) self:canvas():move(self:width() - 1, 0):putchar(urcorner) self:canvas():move(self:width() - 1, 1):putchar(vline, self:height() - 1, true) self:canvas():move(self:width() - 1, self:height() - 1):putchar(lrcorner) end -- get border corner attribute function border:cornerattr() return self._CORNERATTR or {"white", "black"} end -- set border corner attribute function border:cornerattr_set(attr_ul, attr_rl) self._CORNERATTR = {attr_ul or "white", attr_rl or attr_ul or "black"} self:invalidate() end -- swap border corner attribute function border:cornerattr_swap() local cornerattr = self:cornerattr() self:cornerattr_set(cornerattr[2], cornerattr[1]) end -- return module return border
0
repos/xmake/xmake/core
repos/xmake/xmake/core/ui/choicedialog.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 choicedialog.lua -- -- load modules local log = require("ui/log") local rect = require("ui/rect") local event = require("ui/event") local action = require("ui/action") local curses = require("ui/curses") local window = require("ui/window") local scrollbar = require("ui/scrollbar") local choicebox = require("ui/choicebox") local boxdialog = require("ui/boxdialog") -- define module local choicedialog = choicedialog or boxdialog() -- init dialog function choicedialog:init(name, bounds, title) -- init window boxdialog.init(self, name, bounds, title) -- init text self:text():text_set("Use the arrow keys to navigate this window or press the hotkey of the item you wish to select followed by the <SPACEBAR>. Press <?> for additional information about this") -- init buttons self:button_add("select", "< Select >", function (v, e) self:choicebox():on_event(event.command {"cm_enter"}) self:quit() end) self:button_add("cancel", "< Cancel >", function (v, e) self:quit() end) self:buttons():select(self:button("select")) -- insert scrollbar self:box():panel():insert(self:scrollbar_box()) -- insert choice box self:box():panel():insert(self:choicebox()) -- disable to select to box (disable Tab switch and only response to buttons) self:box():option_set("selectable", false) -- on resize for panel self:box():panel():action_add(action.ac_on_resized, function (v) self:choicebox():bounds_set(rect:new(0, 0, v:width() - 1, v:height())) self:scrollbar_box():bounds_set(rect:new(v:width() - 1, 0, 1, v:height())) if self:choicebox():scrollable() then self:scrollbar_box():show(true) else self:scrollbar_box():show(false) end end) -- show scrollbar? self:choicebox():action_add(action.ac_on_load, function (v) if v:scrollable() then self:scrollbar_box():show(true) else self:scrollbar_box():show(false) end end) -- on scroll self:choicebox():action_add(action.ac_on_scrolled, function (v, progress) if self:scrollbar_box():state("visible") then self:scrollbar_box():progress_set(progress) end end) end -- get choice box function choicedialog:choicebox() if not self._CHOICEBOX then local bounds = self:box():panel():bounds() self._CHOICEBOX = choicebox:new("choicedialog.choicebox", rect:new(0, 0, bounds:width() - 1, bounds:height())) self._CHOICEBOX:state_set("focused", true) -- we can select and highlight selected item end return self._CHOICEBOX end -- get box scrollbar function choicedialog:scrollbar_box() if not self._SCROLLBAR_BOX then local bounds = self:box():panel():bounds() self._SCROLLBAR_BOX = scrollbar:new("choicedialog.scrollbar", rect:new(bounds:width() - 1, 0, 1, bounds:height())) self._SCROLLBAR_BOX:show(false) end return self._SCROLLBAR_BOX end -- on event function choicedialog:on_event(e) -- load values first if e.type == event.ev_idle then if not self._LOADED then self:action_on(action.ac_on_load) self._LOADED = true end -- select value elseif e.type == event.ev_keyboard then if e.key_name == "Down" or e.key_name == "Up" or e.key_name == " " then return self:choicebox():on_event(e) end end return boxdialog.on_event(self, e) end -- return module return choicedialog