Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/doxygen/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 doxygen.lua -- -- define task task("doxygen") -- set category set_category("plugin") -- on run on_run("main") -- set menu set_menu { -- usage usage = "xmake doxygen [options] [arguments]" -- description , description = "Generate the doxygen document." -- options , options = { {'o', "outputdir", "kv", nil, "Set the output directory." } , {} , {nil, "srcdir", "v", "src", "Set the source code directory." } } }
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/check/main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.base.text") import("core.project.config") import("private.check.checker") -- show checkers list function _show_list() local tbl = {align = 'l', sep = " "} local checkers = checker.checkers() local groups = {} for name, info in table.orderpairs(checkers) do local groupname = name:split(".", {plain = true})[1] if not groups[groupname] then table.insert(tbl, {}) table.insert(tbl, {groupname:sub(1, 1):upper() .. groupname:sub(2) .. " checkers:"}) groups[groupname] = true end table.insert(tbl, {{" " .. name, style = "${color.dump.string_quote}"}, info.description}) end cprint(text.table(tbl)) end -- show checker information function _show_info(name) local checkers = checker.checkers() local info = checkers[name] if info then cprint("${color.dump.string}checker${clear}(%s):", name) cprint(" -> ${color.dump.string_quote}description${clear}: %s", info.description) else raise("checker(%s) not found!", name) end end -- do check function _check(group_or_name, arguments) -- load config config.load() -- get checkers local checked_checkers = {} local checkers = checker.checkers() if checkers[group_or_name] then table.insert(checked_checkers, group_or_name) else for name, _ in table.orderpairs(checkers) do if name:startswith(group_or_name .. ".") then table.insert(checked_checkers, name) end end end assert(#checked_checkers > 0, "checker(%s) not found!", group_or_name) -- do checkers local showstats for _, name in ipairs(checked_checkers) do local info = checkers[name] if showstats == nil and info and info.showstats ~= nil then showstats = info.showstats end import("private.check.checkers." .. name, {anonymous = true})(arguments) end if showstats ~= false then checker.show_stats() end end function main() if option.get("list") then _show_list() elseif option.get("info") then _show_info(option.get("info")) elseif option.get("checkers") then _check(option.get("checkers"), option.get("arguments")) end end
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/check/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 -- task("check") set_category("plugin") on_run("main") set_menu { usage = "xmake check [options] [arguments]", description = "Check the project sourcecode and configuration.", options = { {'l', "list", "k", nil, "Show all supported checkers list."}, {nil, "info", "kv", nil, "Show the given checker information."}, {nil, "checkers", "v", "api", "Use the given checkers to check project.", "e.g.", " - xmake check api", " - xmake check -v api.target", " - xmake check api.target.languages", "", "The supported checkers list:", values = function (complete, opt) return import("private.check.checker").complete(complete, opt) end}, {nil, "arguments", "vs", nil, "Set the checker arguments.", "e.g.", " - xmake check clang.tidy [arguments]"} } }
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/repo/main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.project.config") import("core.project.project") import("core.platform.platform") import("core.package.repository") import("devel.git") import("net.proxy") import("async.runjobs") import("private.action.require.impl.environment") import("private.service.remote_build.action", {alias = "remote_build_action"}) function _clear_quick_search_cache(is_global) if is_global then import("private.xrepo.quick_search.cache") cache.clear() end end -- add repository url function _add(name, url, branch, is_global) -- remove previous repository if exists local repodir = path.join(repository.directory(is_global), name) if os.isdir(repodir) then os.rmdir(repodir) end -- enter environment environment.enter() -- clone repository if not os.isdir(url) then local remoteurl = proxy.mirror(url) or url git.clone(remoteurl, {verbose = option.get("verbose"), branch = branch, outputdir = repodir, autocrlf = false}) end -- add url repository.add(name, url, branch, is_global) -- trace cprint("${color.success}add %s repository(%s): %s%s ok!", (is_global and "global" or "local"), name, url, branch and (" " .. branch) or "") -- leave environment environment.leave() -- clear quick search cache _clear_quick_search_cache(is_global) end -- remove repository url function _remove(name, is_global) -- remove url repository.remove(name, is_global) -- remove repository local repodir = path.join(repository.directory(is_global), name) if os.isdir(repodir) then os.rmdir(repodir) end -- clear quick search cache _clear_quick_search_cache(is_global) -- trace cprint("${bright}remove %s repository(%s): ok!", (is_global and "global" or "local"), name) end -- update repositories function _update() -- enter environment environment.enter() -- trace printf("updating repositories .. ") if option.get("verbose") then print("") end -- create a pull task local task = function () -- get all repositories (local first) local repos = table.join(repository.repositories(false), repository.repositories(true)) -- pull all repositories local pulled = {} for _, repo in ipairs(repos) do local repodir = repo:directory() if not pulled[repodir] then if os.isdir(repodir) then -- only update the local repository with the remote url if not os.isdir(repo:url()) then vprint("pulling repository(%s): %s to %s ..", repo:name(), repo:url(), repodir) git.pull({verbose = option.get("verbose"), branch = repo:branch(), repodir = repodir, force = true}) io.save(path.join(repodir, "updated"), {}) end else vprint("cloning repository(%s): %s to %s ..", repo:name(), repo:url(), repodir) local remoteurl = proxy.mirror(repo:url()) or repo:url() git.clone(remoteurl, {verbose = option.get("verbose"), branch = repo:branch(), outputdir = repodir, autocrlf = false}) io.save(path.join(repodir, "updated"), {}) end pulled[repodir] = true end end -- clear quick search cache _clear_quick_search_cache(true) end -- pull repositories if option.get("verbose") then task() else runjobs("update repo", task, {progress = true, isolate = true}) end -- leave environment environment.leave() -- trace cprint("${green}ok") end -- clear all repositories function _clear(is_global) -- clear all urls repository.clear(is_global) -- remove all repositories local repodir = repository.directory(is_global) if os.isdir(repodir) then os.rmdir(repodir) end -- clear quick search cache _clear_quick_search_cache(is_global) -- trace cprint("${color.success}clear %s repositories: ok!", (is_global and "global" or "local")) end -- list all repositories function _list(is_global) -- list all repositories local count = 0 for _, position in ipairs(is_global and "global" or {"local", "global"}) do -- trace print("%s repositories:", position) -- list all for _, repo in pairs(repository.repositories(position == "global")) do -- trace local description = repo:get("description") print(" %s %s%s %s", repo:name(), repo:url(), repo:branch() and (" " .. repo:branch()) or "", description and ("(" .. description .. ")") or "") -- update count count = count + 1 end -- trace print("") end -- trace print("%d repositories were found!", count) end -- get the repository directory function _directory(is_global) print(repository.directory(is_global)) end -- load project function _load_project() -- enter project directory os.cd(project.directory()) -- load config config.load() -- load platform platform.load(config.plat()) end -- main function main() -- do action for remote? if remote_build_action.enabled() then return remote_build_action() end -- load project if operate local repositories if not option.get("global") then _load_project() end -- add repository url if option.get("add") then _add(option.get("name"), option.get("url"), option.get("branch"), option.get("global")) -- remove repository url elseif option.get("remove") then _remove(option.get("name"), option.get("global")) -- update repository url elseif option.get("update") then _update() -- clear all repositories elseif option.get("clear") then _clear(option.get("global")) -- list all repositories elseif option.get("list") then _list(option.get("global")) -- show repo directory else _directory(option.get("global")) end end
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/repo/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 repo.lua -- -- define task task("repo") -- set category set_category("plugin") -- on run on_run("main") -- set menu set_menu { -- usage usage = "xmake repo [options] [name] [url] [branch]" -- description , description = "Manage package repositories." -- options , options = { {'a', "add", "k", nil, "Add the given remote repository url." } , {'r', "remove", "k", nil, "Remove the given remote repository url." } , {'u', "update", "k", nil, "Update all local repositories from the remote." } , {'c', "clear", "k", nil, "Clear all added repositories." } , { } , {'l', "list", "k", nil, "List all added repositories." } , {'g', "global", "k", nil, "Save repository to global. (default: local)" } , { } , {nil, "name", "v", nil, "The repository name." } , {nil, "url", "v", nil, "The repository url" } , {nil, "branch", "v", nil, "The repository branch" } } }
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/show/main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") -- show list function _show_list(name) assert(#name > 0 and import("lists." .. name, {try = true, anonymous = true}), "unknown list name(%s)", name)() end function main() -- show list? local listname = option.get("list") if listname then return _show_list(listname) else -- show the information of the given object for _, filepath in ipairs(os.files(path.join(os.scriptdir(), "info", "*.lua"))) do local name = path.basename(filepath) if option.get(name) then local show_info = assert(import("info." .. name, {try = true, anonymous = true}), "unknown option name(%s)", name) return show_info(option.get(name)) end end end -- show the basic information of xmake and the current project assert(import("info.basic", {try = true, anonymous = true}))() end
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/show/showlist.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file showlist.lua -- -- imports import("core.base.option") import("core.base.text") import("core.base.json") function _show_text(values) local tbl = {align = 'l', sep = " "} local row = {} for _, value in ipairs(values) do table.insert(row, value) if #row > 2 then table.insert(tbl, row) row = {} end end if #row > 0 then table.insert(tbl, row) end print(text.table(tbl)) end function _show_json(values) print(json.encode(values)) end function main(values) if option.get("json") then _show_json(values) else if table.is_dictionary(values) then for k, v in pairs(values) do cprint("${bright}%s:", k) _show_text(v) end else _show_text(values) end end end
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/show/list.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file list.lua -- -- imports import("core.base.option") -- get all list values function lists() local values = {} for _, filepath in ipairs(os.files(path.join(os.scriptdir(), "lists", "*.lua"))) do table.insert(values, path.basename(filepath)) end return values end
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/show/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 -- task("show") set_category("plugin") on_run("main") set_menu { usage = "xmake show [options] [arguments]", description = "Show the given project information.", options = { {'l', "list", "kv", nil, "Show the values list of the given name.", values = function (complete, opt) return import("list").lists() end}, {nil, "json", "k", false, "Show information with json format."}, {'t', "target", "kv", nil, "Show the information of the given target.", values = function (complete, opt) return import("private.utils.complete_helper.targets")(complete, opt) end} } }
0
repos/xmake/xmake/plugins/show
repos/xmake/xmake/plugins/show/info/target.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file target.lua -- -- imports import("core.base.option") import("core.base.hashset") import("core.project.config") import("core.project.project") import("core.language.language") -- get source info string function _get_sourceinfo_str(target, name, item, opt) opt = opt or {} local sourceinfo = target:sourceinfo(name, item) if sourceinfo then local tips = opt.tips if tips then tips = tips .. " -> " end return string.format(" ${dim}-> %s%s:%s${clear}", tips or "", sourceinfo.file or "", sourceinfo.line or -1) elseif opt.tips then return string.format(" ${dim}-> %s${clear}", opt.tips) end return "" end -- get values from target options function _get_values_from_opts(target, name) local values = {} for _, opt_ in ipairs(target:orderopts()) do for _, value in ipairs(opt_:get(name)) do local tips = string.format("option(%s)", opt_:name()) values[value] = _get_sourceinfo_str(opt_, name, value, {tips = tips}) end end return values end -- get values from target packages function _get_values_from_pkgs(target, name) local values = {} for _, pkg in ipairs(target:orderpkgs()) do local configinfo = target:pkgconfig(pkg:name()) -- get values from package components -- e.g. `add_packages("sfml", {components = {"graphics", "window"}})` local selected_components = configinfo and configinfo.components or pkg:components_default() if selected_components and pkg:components() then local components_enabled = hashset.new() for _, comp in ipairs(table.wrap(selected_components)) do components_enabled:insert(comp) for _, dep in ipairs(table.wrap(pkg:component_orderdeps(comp))) do components_enabled:insert(dep) end end components_enabled:insert("__base") -- if we can't find the values from the component, we need to fall back to __base to find them. -- it contains some common values of all components local components = table.wrap(pkg:components()) for _, component_name in ipairs(table.join(pkg:components_orderlist(), "__base")) do if components_enabled:has(component_name) then local info = components[component_name] if info then for _, value in ipairs(info[name]) do values[value] = string.format(" -> package(%s)", pkg:name()) end else local components_str = table.concat(table.wrap(configinfo.components), ", ") utils.warning("unknown component(%s) in add_packages(%s, {components = {%s}})", component_name, pkg:name(), components_str) end end end -- get values instead of the builtin configs if exists extra package config -- e.g. `add_packages("xxx", {links = "xxx"})` elseif configinfo and configinfo[name] then for _, value in ipairs(configinfo[name]) do values[value] = _get_sourceinfo_str(target, "packages", pkg:name()) end else -- get values from the builtin package configs for _, value in ipairs(pkg:get(name)) do values[value] = string.format(" -> package(%s)", pkg:name()) end end end return values end -- get values from target dependencies function _get_values_from_deps(target, name) local values = {} local orderdeps = target:orderdeps() local total = #orderdeps for idx, _ in ipairs(orderdeps) do local dep = orderdeps[total + 1 - idx] local depinherit = target:extraconf("deps", dep:name(), "inherit") if depinherit == nil or depinherit then for _, value in ipairs(dep:get(name, {interface = true})) do values[value] = string.format(" -> dep(%s)", dep:name()) end local values_chunks = dep:get_from(name, "option::*", {interface = true}) for _, values_chunk in ipairs(values_chunks) do for _, value in ipairs(values_chunk) do values[value] = string.format(" -> dep(%s) -> options", dep:name()) end end values_chunks = dep:get_from(name, "package::*", {interface = true}) for _, values_chunk in ipairs(values_chunks) do for _, value in ipairs(values_chunk) do values[value] = string.format(" -> dep(%s) -> packages", dep:name()) end end end end return values end -- show target information function _show_target(target) print("The information of target(%s):", target:name()) cprint(" ${color.dump.string}at${clear}: %s", path.join(target:scriptdir(), "xmake.lua")) cprint(" ${color.dump.string}kind${clear}: %s", target:kind()) cprint(" ${color.dump.string}targetfile${clear}: %s", target:targetfile()) local deps = target:get("deps") if deps then cprint(" ${color.dump.string}deps${clear}:") for _, dep in ipairs(deps) do cprint(" ${color.dump.reference}->${clear} %s%s", dep, _get_sourceinfo_str(target, "deps", dep)) end end local rules = target:get("rules") if rules then cprint(" ${color.dump.string}rules${clear}:") for _, value in ipairs(rules) do cprint(" ${color.dump.reference}->${clear} %s%s", value, _get_sourceinfo_str(target, "rules", value)) end end local options = {} for _, opt in ipairs(target:get("options")) do if not opt:startswith("__") then table.insert(options, opt) end end if #options > 0 then cprint(" ${color.dump.string}options${clear}:") for _, value in ipairs(options) do cprint(" ${color.dump.reference}->${clear} %s%s", value, _get_sourceinfo_str(target, "options", value)) end end local packages = target:get("packages") if packages then cprint(" ${color.dump.string}packages${clear}:") for _, value in ipairs(packages) do cprint(" ${color.dump.reference}->${clear} %s%s", value, _get_sourceinfo_str(target, "packages", value)) end end for _, apiname in ipairs(table.join(language.apis().values, language.apis().paths)) do if apiname:startswith("target.") then local valuename = apiname:split('.add_', {plain = true})[2] if valuename then local results = {} local values = table.unique(table.wrap(target:get(valuename))) if #values > 0 then for _, value in ipairs(values) do table.insert(results, {value = value, sourceinfo = _get_sourceinfo_str(target, valuename, value)}) end end local values_from_opts = _get_values_from_opts(target, valuename) for value, sourceinfo in pairs(values_from_opts) do table.insert(results, {value = value, sourceinfo = sourceinfo}) end local values_from_pkgs = _get_values_from_pkgs(target, valuename) for value, sourceinfo in pairs(values_from_pkgs) do table.insert(results, {value = value, sourceinfo = sourceinfo}) end local values_from_deps = _get_values_from_deps(target, valuename) for value, sourceinfo in pairs(values_from_deps) do table.insert(results, {value = value, sourceinfo = sourceinfo}) end if #results > 0 then cprint(" ${color.dump.string}%s${clear}:", valuename) for _, result in ipairs(results) do cprint(" ${color.dump.reference}->${clear} %s%s", result.value, result.sourceinfo) end end end end end local files = target:get("files") if files then cprint(" ${color.dump.string}files${clear}:") for _, file in ipairs(files) do if not file:startswith("__remove_") then cprint(" ${color.dump.reference}->${clear} %s%s", file, _get_sourceinfo_str(target, "files", file)) end end end local sourcekinds = hashset.new() for _, sourcebatch in pairs(target:sourcebatches()) do if sourcebatch.sourcekind then sourcekinds:insert(sourcebatch.sourcekind) end end for _, sourcekind in sourcekinds:keys() do local compinst = target:compiler(sourcekind) if compinst then cprint(" ${color.dump.string}compiler (%s)${clear}: %s", sourcekind, compinst:program()) cprint(" ${color.dump.reference}->${clear} %s", os.args(compinst:compflags())) end end local linker = target:linker() if linker then cprint(" ${color.dump.string}linker (%s)${clear}: %s", linker:kind(), linker:program()) cprint(" ${color.dump.reference}->${clear} %s", os.args(linker:linkflags())) end for _, sourcekind in sourcekinds:keys() do local compinst = target:compiler(sourcekind) if compinst then cprint(" ${color.dump.string}compflags (%s)${clear}:", sourcekind) cprint(" ${color.dump.reference}->${clear} %s", os.args(compinst:compflags({target = target}))) end end local linker = target:linker() if linker then cprint(" ${color.dump.string}linkflags (%s)${clear}:", linker:kind()) cprint(" ${color.dump.reference}->${clear} %s", os.args(linker:linkflags({target = target}))) end end function main(name) -- get target config.load() local target = assert(project.target(name), "target(%s) not found!", name) -- show target information _show_target(target) end
0
repos/xmake/xmake/plugins/show
repos/xmake/xmake/plugins/show/info/basic.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file basic.lua -- -- imports import("core.base.option") import("core.base.global") import("core.project.config") import("core.project.project") import("core.package.package") -- show basic info function main() -- get target config.load() -- show xmake information print("The information of xmake:") cprint(" ${color.dump.string}version${clear}: %s", xmake.version()) cprint(" ${color.dump.string}host${clear}: %s/%s", os.host(), os.arch()) cprint(" ${color.dump.string}programdir${clear}: %s", xmake.programdir()) cprint(" ${color.dump.string}programfile${clear}: %s", xmake.programfile()) cprint(" ${color.dump.string}globaldir${clear}: %s", global.directory()) cprint(" ${color.dump.string}tmpdir${clear}: %s", os.tmpdir()) cprint(" ${color.dump.string}workingdir${clear}: %s", os.workingdir()) cprint(" ${color.dump.string}packagedir${clear}: %s", package.installdir()) cprint(" ${color.dump.string}packagedir(cache)${clear}: %s", package.cachedir()) print("") local projectfile = os.projectfile() if os.isfile(projectfile) then print("The information of project: %s", project.name() and project.name() or "") local version = project.version() if version then cprint(" ${color.dump.string}version${clear}: %s", version) end if config.plat() then cprint(" ${color.dump.string}plat${clear}: %s", config.plat()) end if config.arch() then cprint(" ${color.dump.string}arch${clear}: %s", config.arch()) end if config.mode() then cprint(" ${color.dump.string}mode${clear}: %s", config.mode()) end if config.buildir() then cprint(" ${color.dump.string}buildir${clear}: %s", config.buildir()) end cprint(" ${color.dump.string}configdir${clear}: %s", config.directory()) cprint(" ${color.dump.string}projectdir${clear}: %s", os.projectdir()) cprint(" ${color.dump.string}projectfile${clear}: %s", projectfile) print("") end end
0
repos/xmake/xmake/plugins/show
repos/xmake/xmake/plugins/show/lists/buildmodes.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file buildmodes.lua -- -- imports import("core.project.config") import("core.project.rule") import(".showlist") -- show all platforms function main() config.load() local modes = {} for _, r in pairs(rule.rules()) do local rulename = r:name() if rulename:startswith("mode.") then table.insert(modes, rulename) end end showlist(modes) end
0
repos/xmake/xmake/plugins/show
repos/xmake/xmake/plugins/show/lists/toolchains.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file toolchains.lua -- -- imports import("core.tool.toolchain") import("core.base.text") import("core.project.config") import("core.project.project") -- show all toolchains function main() config.load() local tbl = {align = 'l', sep = " "} for _, name in ipairs(toolchain.list()) do local t = os.isfile(os.projectfile()) and project.toolchain(name) or toolchain.load(name) table.insert(tbl, {name, t:get("description")}) end print(text.table(tbl)) end
0
repos/xmake/xmake/plugins/show
repos/xmake/xmake/plugins/show/lists/themes.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file themes.lua -- -- imports import("core.theme.theme") import(".showlist") -- show all themes function main() showlist(theme.names()) end
0
repos/xmake/xmake/plugins/show
repos/xmake/xmake/plugins/show/lists/architectures.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file platforms.lua -- -- imports import("core.project.project") import("core.platform.platform") import("core.base.text") import("core.base.option") import(".showlist") -- show all platforms function main() -- get all platforms local plats = try {function () return project.allowed_plats() end} if plats then plats = plats:to_array() end plats = plats or platform.plats() -- get all architectures local result = {align = 'l', sep = " "} local json_result = {} for i, plat in ipairs(plats) do local archs = try {function () return project.allowed_archs(plat) end} if archs then archs = archs:to_array() end if not archs then archs = platform.archs(plat) end if archs and #archs > 0 then table.insert(result, table.join(plat, archs)) json_result[plat] = archs end end if option.get("json") then showlist(json_result) else print(text.table(result)) end end
0
repos/xmake/xmake/plugins/show
repos/xmake/xmake/plugins/show/lists/apis.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file apis.lua -- -- imports import("core.project.config") import("core.project.rule") import("core.project.target") import("core.project.project") import("core.project.option") import("core.package.package") import("core.language.language") import("core.sandbox.sandbox") import("core.sandbox.module") import("core.tool.toolchain") import("core.base.interpreter") import(".showlist") function _is_callable(func) if type(func) == "function" then return true elseif type(func) == "table" then local meta = debug.getmetatable(func) if meta and meta.__call then return true end end end -- get target description scope apis function description_target_scope_apis() local result = {} for _, names in pairs(target.apis()) do for _, name in ipairs(names) do table.insert(result, name) end end return result end -- get language description scope apis function description_language_scope_apis() local result = {} for _, names in pairs(language.apis()) do for _, name in ipairs(names) do table.insert(result, name) end end return result end -- get option description scope apis function description_option_scope_apis() local result = {} for _, names in pairs(option.apis()) do for _, name in ipairs(names) do table.insert(result, name) end end return result end -- get rule description scope apis function description_rule_scope_apis() local result = {} for _, names in pairs(rule.apis()) do for _, name in ipairs(names) do table.insert(result, name) end end return result end -- get package description scope apis function description_package_scope_apis() local result = {} for _, names in pairs(package.apis()) do for _, name in ipairs(names) do if type(name) == "table" then name = "package." .. name[1] end table.insert(result, name) end end return result end -- get toolchain description scope apis function description_toolchain_scope_apis() local result = {} for _, names in pairs(toolchain.apis()) do for _, name in ipairs(names) do table.insert(result, name) end end return result end -- get description scope apis function description_scope_apis() local result = {} table.join2(result, description_target_scope_apis()) table.join2(result, description_option_scope_apis()) table.join2(result, description_language_scope_apis()) table.join2(result, description_rule_scope_apis()) table.join2(result, description_package_scope_apis()) table.join2(result, description_toolchain_scope_apis()) table.sort(result) return result end -- get description builtin apis function description_builtin_apis() -- add builtin interpreter apis local builtin_module_apis = table.clone(interpreter.builtin_modules()) builtin_module_apis.pairs = nil builtin_module_apis.ipairs = nil local result = {} for name, value in pairs(builtin_module_apis) do if type(value) == "function" then table.insert(result, name) end end table.insert(result, "ipairs") table.insert(result, "pairs") table.insert(result, "includes") table.insert(result, "set_xmakever") -- add root project apis for _, names in pairs(project.apis()) do for _, name in ipairs(names) do if type(name) == "table" then name = name[1] end table.insert(result, name) end end table.sort(result) return result end -- get description builtin module apis function description_builtin_module_apis() local builtin_module_apis = table.clone(interpreter.builtin_modules()) builtin_module_apis.pairs = nil builtin_module_apis.ipairs = nil local result = {} for name, value in pairs(builtin_module_apis) do if type(value) == "table" then for k, v in pairs(value) do if not k:startswith("_") and type(v) == "function" then table.insert(result, name .. "." .. k) end end end end table.sort(result) return result end -- get script target instance apis function script_target_instance_apis() local result = {} local instance = target.new() for k, v in pairs(instance) do if not k:startswith("_") and type(v) == "function" then table.insert(result, "target:" .. k) end end return result end -- get script option instance apis function script_option_instance_apis() local result = {} local instance = option.new() for k, v in pairs(instance) do if not k:startswith("_") and type(v) == "function" then table.insert(result, "option:" .. k) end end return result end -- get script rule instance apis function script_rule_instance_apis() local result = {} local instance = rule.new() for k, v in pairs(instance) do if not k:startswith("_") and type(v) == "function" then table.insert(result, "rule:" .. k) end end return result end -- get script toolchain instance apis function script_toolchain_instance_apis() local result = {} local instance = toolchain.load("clang") for k, v in pairs(instance) do if not k:startswith("_") and type(v) == "function" then table.insert(result, "toolchain:" .. k) end end return result end -- get script package instance apis function script_package_instance_apis() local result = {} local instance = package.new() for k, v in pairs(instance) do if not k:startswith("_") and type(v) == "function" then table.insert(result, "package:" .. k) end end return result end -- get script instance apis function script_instance_apis() local result = {} table.join2(result, script_target_instance_apis()) table.join2(result, script_option_instance_apis()) table.join2(result, script_rule_instance_apis()) table.join2(result, script_package_instance_apis()) table.join2(result, script_toolchain_instance_apis()) table.sort(result) return result end -- get script builtin apis function script_builtin_apis() local builtin_module_apis = table.clone(sandbox.builtin_modules()) builtin_module_apis.pairs = nil builtin_module_apis.ipairs = nil local result = {} for name, value in pairs(builtin_module_apis) do if type(value) == "function" then table.insert(result, name) end end table.insert(result, "ipairs") table.insert(result, "pairs") table.sort(result) return result end -- get script builtin module apis function script_builtin_module_apis() local builtin_module_apis = table.clone(sandbox.builtin_modules()) builtin_module_apis.pairs = nil builtin_module_apis.ipairs = nil local result = {} for name, value in pairs(builtin_module_apis) do if type(value) == "table" then for k, v in pairs(value) do if not k:startswith("_") and type(v) == "function" then table.insert(result, name .. "." .. k) end end end end table.sort(result) return result end -- get script extension modules function script_extension_module_apis() local result = {} local moduledirs = module.directories() for _, moduledir in ipairs(moduledirs) do moduledir = path.absolute(moduledir) local modulefiles = os.files(path.join(moduledir, "**.lua|**/xmake.lua|private/**.lua|core/tools/**.lua|detect/tools/**.lua")) if modulefiles then for _, modulefile in ipairs(modulefiles) do local modulename = path.relative(modulefile, moduledir) if path.filename(modulename) == "main.lua" then modulename = path.directory(modulename) end modulename = modulename:gsub("[\\/]", "."):gsub("%.lua", "") local instance = import(modulename, {try = true, anonymous = true}) if instance then if _is_callable(instance) then table.insert(result, modulename) elseif type(instance) == "table" then for k, v in pairs(instance) do if not k:startswith("_") and type(v) == "function" then table.insert(result, modulename .. "." .. k) end end end end end end end table.sort(result) return result end -- get all apis -- -- the api kind: -- - description -- - builtin api -- - builtin module api -- - scope api -- - script -- - builtin api -- - builtin module api -- - extension module api -- - instance api function apis() return {description_scope_apis = description_scope_apis(), description_builtin_apis = description_builtin_apis(), description_builtin_module_apis = description_builtin_module_apis(), script_builtin_apis = script_builtin_apis(), script_builtin_module_apis = script_builtin_module_apis(), script_extension_module_apis = script_extension_module_apis(), script_instance_apis = script_instance_apis() } end -- show all apis function main() config.load() local result = apis() if result then showlist(result) end end
0
repos/xmake/xmake/plugins/show
repos/xmake/xmake/plugins/show/lists/rules.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file rules.lua -- -- imports import("core.project.config") import("core.project.rule") import(".showlist") -- show all rules function main() config.load() local rules = {} for _, r in pairs(rule.rules()) do table.insert(rules, r:name()) end table.sort(rules) showlist(rules) end
0
repos/xmake/xmake/plugins/show
repos/xmake/xmake/plugins/show/lists/envs.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file envs.lua -- -- imports import("core.base.text") import("core.base.global") import("core.project.config") import("core.project.project") -- show all toolchains function main() local envs = { XMAKE_PROGRAM_DIR = {"Set the program scripts directory of xmake.", os.programdir()}, XMAKE_CONFIGDIR = {"Set the local config directory of project.", config.directory()}, XMAKE_GLOBALDIR = {"Set the global config directory of xmake.", global.directory()}, XMAKE_COLORTERM = {"Set the color terminal environment.", os.getenv("XMAKE_COLORTERM") or os.getenv("COLORTERM")}, XMAKE_LOGFILE = {"Set the log output file path.", os.getenv("XMAKE_LOGFILE")}, XMAKE_ROOT = {"Allow xmake to run under root.", os.getenv("XMAKE_ROOT")}, XMAKE_RAMDIR = {"Set the ramdisk directory.", os.getenv("XMAKE_RAMDIR")}, XMAKE_RCFILES = {"Set the runtime configuration files.", path.joinenv(project.rcfiles())}, XMAKE_TMPDIR = {"Set the temporary directory.", os.tmpdir()}, XMAKE_PROFILE = {"Start profiler, e.g. perf:call, perf:tag, trace, stuck.", os.getenv("XMAKE_PROFILE")}, XMAKE_PKG_CACHEDIR = {"Set the cache directory of packages.", os.getenv("XMAKE_PKG_CACHEDIR")}, XMAKE_PKG_INSTALLDIR = {"Set the install directory of packages.", os.getenv("XMAKE_PKG_INSTALLDIR")}} local width = 24 for name, env in pairs(envs) do cprint("${color.dump.string}%s${clear}%s%s", name, (" "):rep(width - #name), env[1]) cprint("%s${bright}%s", (" "):rep(width), env[2] or "<empty>") end end
0
repos/xmake/xmake/plugins/show
repos/xmake/xmake/plugins/show/lists/platforms.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file platforms.lua -- -- imports import("core.platform.platform") import(".showlist") -- show all platforms function main() showlist(platform.plats()) end
0
repos/xmake/xmake/plugins/show
repos/xmake/xmake/plugins/show/lists/policies.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author A2va -- @file policies.lua -- -- imports import("core.project.policy") -- show all policies function main() local width = 45 local policies = policy.policies() for name, policy in table.orderpairs(policies) do cprint("${color.dump.string}%s${clear}%s%s", name, (" "):rep(width - #name), policy["description"]) cprint("%s${bright}%s", (" "):rep(width), policy["default"] or "false") end end
0
repos/xmake/xmake/plugins/show
repos/xmake/xmake/plugins/show/lists/targets.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file targets.lua -- -- imports import("core.project.config") import("core.project.project") import("core.platform.platform") import(".showlist") -- show all platforms function main() config.load() local targets = {} for name, _ in pairs(project.targets()) do table.insert(targets, name) end showlist(targets) end
0
repos/xmake/xmake/plugins/show
repos/xmake/xmake/plugins/show/lists/packages.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file packages.lua -- -- imports import("core.project.config") import("private.action.require.list", { alias = "show_packages" }) import(".showlist") -- show all packages function main() config.load() show_packages() end
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/project/main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.base.task") import("core.project.config") import("make.makefile") import("make.xmakefile") import("cmake.cmakelists") import("xcode.xcodeproj") import("ninja.build_ninja") import("vstudio.vs") import("vsxmake.vsxmake") import("clang.compile_flags") import("clang.compile_commands") import("private.utils.statistics") import("private.service.remote_build.action", {alias = "remote_build_action"}) function makers() return { make = makefile.make , makefile = makefile.make , xmakefile = xmakefile.make , cmake = cmakelists.make , cmakelists = cmakelists.make , xcode = xcodeproj.make , ninja = build_ninja.make , vs2002 = vs.make(2002) , vs2003 = vs.make(2003) , vs2005 = vs.make(2005) , vs2008 = vs.make(2008) , vs2010 = vs.make(2010) , vs2012 = vs.make(2012) , vs2013 = vs.make(2013) , vs2015 = vs.make(2015) , vs2017 = vs.make(2017) , vs2019 = vs.make(2019) , vs2022 = vs.make(2022) , vs = vs.make() , vsxmake2010 = vsxmake.make(2010) , vsxmake2012 = vsxmake.make(2012) , vsxmake2013 = vsxmake.make(2013) , vsxmake2015 = vsxmake.make(2015) , vsxmake2017 = vsxmake.make(2017) , vsxmake2019 = vsxmake.make(2019) , vsxmake2022 = vsxmake.make(2022) , vsxmake = vsxmake.make() , compile_flags = compile_flags.make , compile_commands = compile_commands.make } end -- make project function _make(kind) local maps = makers() assert(maps[kind], "the project kind(%s) is not supported!", kind) maps[kind](option.get("outputdir")) end function main() -- do action for remote? if remote_build_action.enabled() then return remote_build_action() end -- in project generator? os.setenv("XMAKE_IN_PROJECT_GENERATOR", "true") -- config it first task.run("config") -- post statistics statistics.post() -- make project _make(option.get("kind")) -- trace cprint("${color.success}create ok!") os.setenv("XMAKE_IN_PROJECT_GENERATOR", nil) end
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/project/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 task task("project") -- set category set_category("plugin") -- on run on_run("main") -- set menu set_menu { -- usage usage = "xmake project [options] [target]" -- description , description = "Generate the project file." -- options , options = { {'k', "kind", "kv" , "makefile", "Set the project kind." , " - make" , " - xmakefile (makefile with xmake)" , " - cmake" , " - ninja" , " - xcode (need cmake)" , " - compile_flags" , " - compile_commands (clang compilation database with json format)" , " - vs (auto detect), vs2002 - vs2022" , " - vsxmake (auto detect), vsxmake2010 ~ vsxmake2022" , values = function (complete, opt) if not complete then return end local values = table.keys(import("main.makers")()) table.sort(values, function (a, b) return a > b end) return values end } , {'m', "modes", "kv" , nil , "Set the project modes." , " e.g. " , " - xmake project -k vsxmake -m \"release,debug\"" } , {'a', "archs", "kv" , nil , "Set the project archs." , " e.g. " , " - xmake project -k vsxmake -a \"x86,x64\"" } , {nil, "lsp", "kv" , nil , "Set the LSP backend for compile_commands." , " e.g. " , " - xmake project -k compile_commands --lsp=clangd" , values = {"clangd", "cpptools", "ccls"}} , {nil, "outputdir", "v" , "." , "Set the output directory." } } }
0
repos/xmake/xmake/plugins/project
repos/xmake/xmake/plugins/project/ninja/build_ninja.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file build_ninja.lua -- -- imports import("core.project.config") import("core.project.project") import("core.platform.platform") import("core.language.language") import("core.tool.linker") import("core.tool.compiler") import("lib.detect.find_tool") import("lib.detect.find_toolname") import("private.tools.cl.parse_include") -- this sourcebatch is built? function _sourcebatch_is_built(sourcebatch) -- we can only use rulename to filter them because sourcekind may be bound to multiple rules local rulename = sourcebatch.rulename if rulename == "c.build" or rulename == "c++.build" or rulename == "asm.build" or rulename == "cuda.build" or rulename == "objc.build" or rulename == "objc++.build" then return true end end -- escape path function _escape_path(filepath) if is_host("windows") then filepath = filepath:gsub('\\', '/') end return filepath end -- tranlate path function _translate_path(filepath, outputdir) filepath = path.translate(filepath) if filepath == "" then return "" end if path.is_absolute(filepath) then if filepath:startswith(project.directory()) then return path.relative(filepath, outputdir) end return filepath else return path.relative(path.absolute(filepath), outputdir) end end -- get relative unix path function _get_relative_unix_path(filepath, outputdir) filepath = _translate_path(filepath, outputdir) filepath = _escape_path(path.translate(filepath)) return os.args(filepath) end -- translate compiler flags function _translate_compflags(compflags, outputdir) local flags = {} local last_flag = nil; for _, flag in ipairs(compflags) do if flag == "-I" or flag == "-isystem" then last_flag = flag else if last_flag == "-I" or last_flag == "-isystem" then table.insert(flags, last_flag) flag = _get_relative_unix_path(flag, outputdir) else last_flag = flag for _, pattern in ipairs({"[%-](I)(.*)", "[%-](isystem)(.*)"}) do flag = flag:gsub(pattern, function (flag, dir) dir = _get_relative_unix_path(dir, outputdir) return "-" .. flag .. dir end) end end table.insert(flags, flag) end end return flags end -- translate linker flags function _translate_linkflags(linkflags, outputdir) local flags = {} for _, flag in ipairs(linkflags) do for _, pattern in ipairs({"[%-](L)(.*)", "[%-](F)(.*)"}) do flag = flag:gsub(pattern, function (flag, dir) dir = _get_relative_unix_path(dir, outputdir) return "-" .. flag .. dir end) end table.insert(flags, flag) end return flags end -- add header function _add_header(ninjafile) ninjafile:print([[# this is the build file for project %s # it is autogenerated by the xmake build system. # do not edit by hand. ]], project.name() or "") ninjafile:print("ninja_required_version = 1.5.1") ninjafile:print("") end -- add rules for generator function _add_rules_for_generator(ninjafile, outputdir) local projectdir = _get_relative_unix_path(os.projectdir(), outputdir) ninjafile:print("rule gen") ninjafile:print(" command = xmake project -P %s -k ninja", projectdir) ninjafile:print(" description = regenerating ninja files") ninjafile:print("") end -- add rules for complier (gcc) function _add_rules_for_compiler_gcc(ninjafile, sourcekind, program) local ccache = config.get("ccache") ~= false and find_tool("ccache") ninjafile:print("rule %s", sourcekind) ninjafile:print(" command = %s%s $ARGS -MMD -MF $out.d -o $out -c $in", ccache and (ccache.program .. " ") or "", program) ninjafile:print(" deps = gcc") ninjafile:print(" depfile = $out.d") ninjafile:print(" description = %scompiling.%s $in", ccache and "ccache " or "", config.mode()) ninjafile:print("") end -- add rules for complier (clang) function _add_rules_for_compiler_clang(ninjafile, sourcekind, program) return _add_rules_for_compiler_gcc(ninjafile, sourcekind, program) end -- add rules for complier (msvc/cl) function _add_rules_for_compiler_msvc_cl(ninjafile, sourcekind, program) ninjafile:print("rule %s", sourcekind) ninjafile:print(" command = %s -showIncludes -c $ARGS $in -Fo$out", program) ninjafile:print(" deps = msvc") ninjafile:print(" description = compiling.%s $in", config.mode()) ninjafile:print("") end -- add rules for complier (msvc/ml) function _add_rules_for_compiler_msvc_ml(ninjafile, sourcekind, program) ninjafile:print("rule %s", sourcekind) ninjafile:print(" command = %s -c $ARGS -Fo$out $in", program) ninjafile:print(" deps = msvc") ninjafile:print(" description = compiling.%s $in", config.mode()) ninjafile:print("") end -- add rules for resource complier (msvc/rc) function _add_rules_for_compiler_msvc_rc(ninjafile, sourcekind, program) ninjafile:print("rule %s", sourcekind) ninjafile:print(" command = %s $ARGS -Fo$out $in", program) ninjafile:print(" deps = msvc") ninjafile:print(" description = compiling.%s $in", config.mode()) ninjafile:print("") end -- add rules for resource complier (windres/rc) function _add_rules_for_compiler_windres(ninjafile, sourcekind, program) ninjafile:print("rule %s", sourcekind) ninjafile:print(" command = %s $ARGS $in $out", program) ninjafile:print(" description = compiling.%s $in", config.mode()) ninjafile:print("") end -- add rules for complier function _add_rules_for_compiler(ninjafile) ninjafile:print("# rules for compiler") if is_plat("windows") then -- @see https://github.com/ninja-build/ninja/issues/613 local note_include = parse_include.probe_include_note_from_cl() if not note_include then note_include = "Note: including file:" end ninjafile:print("msvc_deps_prefix = %s", note_include:trim()) end local add_compiler_rules = { gcc = _add_rules_for_compiler_gcc, gxx = _add_rules_for_compiler_gcc, clang = _add_rules_for_compiler_clang, clangxx = _add_rules_for_compiler_clang, cl = _add_rules_for_compiler_msvc_cl, ml = _add_rules_for_compiler_msvc_ml, ml64 = _add_rules_for_compiler_msvc_ml, rc = _add_rules_for_compiler_msvc_rc, windres = _add_rules_for_compiler_windres } for sourcekind, _ in pairs(language.sourcekinds()) do local program, toolname = platform.tool(sourcekind) if program then local add_rule = add_compiler_rules[toolname or find_toolname(program)] -- support of unknown compiler (xmake f --cc=gcc@my-cc) if not add_rule and toolname then add_rule = add_compiler_rules[find_toolname(toolname)] end if add_rule then add_rule(ninjafile, sourcekind, program) end end end ninjafile:print("") end -- add rules for linker (ar) function _add_rules_for_linker_ar(ninjafile, linkerkind, program) ninjafile:print("rule %s", linkerkind) ninjafile:print(" command = %s $ARGS $out $in", program) ninjafile:print(" description = archiving.%s $out", config.mode()) ninjafile:print("") end -- add rules for linker (gcc) function _add_rules_for_linker_gcc(ninjafile, linkerkind, program) ninjafile:print("rule %s", linkerkind) ninjafile:print(" command = %s -o $out $in $ARGS", program) ninjafile:print(" description = linking.%s $out", config.mode()) ninjafile:print("") end -- add rules for linker (clang) function _add_rules_for_linker_clang(ninjafile, linkerkind, program) return _add_rules_for_linker_gcc(ninjafile, linkerkind, program) end -- add rules for linker (msvc) function _add_rules_for_linker_msvc(ninjafile, linkerkind, program) if linkerkind == "ar" then program = program .. " -lib" elseif linkerkind == "sh" then program = program .. " -dll" end -- @note we use rspfile to handle long command limit on windows ninjafile:print("rule %s", linkerkind) ninjafile:print(" command = %s @$out.rsp", program) ninjafile:print(" rspfile = $out.rsp") ninjafile:print(" rspfile_content = $ARGS -out:$out $in_newline") ninjafile:print(" description = linking.%s $out", config.mode()) ninjafile:print("") end -- add rules for linker function _add_rules_for_linker(ninjafile) ninjafile:print("# rules for linker") local linkerkinds = {} for _, _linkerkinds in pairs(language.targetkinds()) do table.join2(linkerkinds, _linkerkinds) end local add_linker_rules = { ar = _add_rules_for_linker_ar, gcc = _add_rules_for_linker_gcc, gxx = _add_rules_for_linker_gcc, clang = _add_rules_for_linker_clang, clangxx = _add_rules_for_linker_clang, link = _add_rules_for_linker_msvc } for _, linkerkind in ipairs(table.unique(linkerkinds)) do local program, toolname = platform.tool(linkerkind) if program then local add_rule = add_linker_rules[toolname or find_toolname(program)] -- support of unknown linker (xmake f --ld=gcc@my-ld) if not add_rule and toolname then add_rule = add_linker_rules[find_toolname(toolname)] end if add_rule then add_rule(ninjafile, linkerkind, program) end end end ninjafile:print("") end -- add rules function _add_rules(ninjafile, outputdir) -- add rules for generator _add_rules_for_generator(ninjafile, outputdir) -- add rules for complier _add_rules_for_compiler(ninjafile) -- add rules for linker _add_rules_for_linker(ninjafile) end -- add build rule for phony function _add_build_for_phony(ninjafile, target) ninjafile:print("build %s: phony", target:name()) end -- add build rule for object function _add_build_for_object(ninjafile, target, sourcekind, sourcefile, objectfile, outputdir) objectfile = _get_relative_unix_path(objectfile, outputdir) sourcefile = _get_relative_unix_path(sourcefile, outputdir) local compflags = compiler.compflags(sourcefile, {target = target}) ninjafile:print("build %s: %s %s", objectfile, sourcekind, sourcefile) ninjafile:print(" ARGS = %s", os.args(_translate_compflags(compflags, outputdir))) ninjafile:print("") end -- add build rule for objects function _add_build_for_objects(ninjafile, target, sourcebatch, outputdir) for index, objectfile in ipairs(sourcebatch.objectfiles) do _add_build_for_object(ninjafile, target, sourcebatch.sourcekind, sourcebatch.sourcefiles[index], objectfile, outputdir) end end -- add build rule for target function _add_build_for_target(ninjafile, target, outputdir) -- https://github.com/xmake-io/xmake/issues/2337 target:data_set("plugin.project.kind", "ninja") -- is phony target? if target:is_phony() then return _add_build_for_phony(ninjafile, target) end -- build target ninjafile:print("# build target: %s", target:name()) local targetfile = _get_relative_unix_path(target:targetfile(), outputdir) ninjafile:print("build %s: phony %s", target:name(), targetfile) -- build target file ninjafile:printf("build %s: %s", targetfile, target:linker():kind()) local objectfiles = target:objectfiles() for _, objectfile in ipairs(objectfiles) do ninjafile:write(" " .. _get_relative_unix_path(objectfile, outputdir)) end -- merge objects with rule("utils.merge.object") for _, sourcebatch in pairs(target:sourcebatches()) do if sourcebatch.rulename == "utils.merge.object" then ninjafile:write(" " .. table.concat(sourcebatch.sourcefiles, " ")) end end local deps = target:get("deps") if deps then ninjafile:print(" || $") ninjafile:write(" ") for _, dep in ipairs(deps) do ninjafile:write(" " .. _get_relative_unix_path(project.target(dep):targetfile(), outputdir)) end end ninjafile:print("") ninjafile:print(" ARGS = %s", os.args(_translate_linkflags(target:linkflags(), outputdir))) ninjafile:print("") -- build target objects local sourcebatches = target:sourcebatches() for _, sourcebatch in table.orderpairs(sourcebatches) do if _sourcebatch_is_built(sourcebatch) then _add_build_for_objects(ninjafile, target, sourcebatch, outputdir) end end end -- add build rule for generator function _add_build_for_generator(ninjafile, outputdir) ninjafile:print("# build build.ninja") ninjafile:print("build build.ninja: gen $") local allfiles = project.allfiles() for idx, projectfile in ipairs(allfiles) do if not path.is_absolute(projectfile) or projectfile:startswith(os.projectdir()) then local filepath = _get_relative_unix_path(projectfile, outputdir) ninjafile:print(" %s %s", filepath, idx < #allfiles and "$" or "") end end ninjafile:print("") end -- add build rule for targets function _add_build_for_targets(ninjafile, outputdir) -- begin ninjafile:print("# build targets\n") -- add build rule for generator _add_build_for_generator(ninjafile, outputdir) -- TODO -- disable precompiled header first for _, target in pairs(project.targets()) do target:set("pcheader", nil) target:set("pcxxheader", nil) end -- build targets for _, target in pairs(project.targets()) do _add_build_for_target(ninjafile, target, outputdir) end -- build default local default = "" for targetname, target in pairs(project.targets()) do if target:is_default() then default = default .. " " .. targetname end end ninjafile:print("build default: phony%s", default) -- build all local all = "" for targetname, _ in pairs(project.targets()) do all = all .. " " .. targetname end ninjafile:print("build all: phony%s\n", all) -- end ninjafile:print("default default\n") end function make(outputdir) -- enter project directory local oldir = os.cd(os.projectdir()) -- open the build.ninja file -- -- we need to change encoding to support msvc_deps_prefix -- @see https://github.com/ninja-build/ninja/issues/613 -- -- TODO maybe we need support more encoding for other languages -- local encoding = is_subhost("windows") and "gbk" local ninjafile = io.open(path.join(outputdir, "build.ninja"), "w", {encoding = encoding}) -- add header _add_header(ninjafile) -- add rules _add_rules(ninjafile, outputdir) -- add build rules for targets _add_build_for_targets(ninjafile, outputdir) -- close the ninjafile ninjafile:close() -- leave project directory os.cd(oldir) end
0
repos/xmake/xmake/plugins/project
repos/xmake/xmake/plugins/project/vsxmake/getinfo.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 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 getinfo.lua -- -- imports import("core.base.option") import("core.base.semver") import("core.base.hashset") import("core.project.config") import("core.project.project") import("core.platform.platform") import("core.tool.compiler") import("core.tool.linker") import("core.tool.toolchain") import("core.cache.memcache") import("core.cache.localcache") import("lib.detect.find_tool") import("private.utils.target", {alias = "target_utils"}) import("private.action.run.runenvs") import("private.action.require.install", {alias = "install_requires"}) import("actions.config.configfiles", {alias = "generate_configfiles", rootdir = os.programdir()}) import("vstudio.impl.vsutils", {rootdir = path.join(os.programdir(), "plugins", "project")}) -- strip dot directories, e.g. ..\..\.. => .. -- @see https://github.com/xmake-io/xmake/issues/2039 function _strip_dotdirs(dir) local count dir, count = dir:gsub("%.%.[\\/]%.%.", "..") if count > 0 then dir = _strip_dotdirs(dir) end return dir end function _make_dirs(dir) if dir == nil then return "" end if type(dir) == "string" then dir = path.translate(dir) if dir == "" then return "" end if path.is_absolute(dir) then if dir:startswith(project.directory()) then return path.join("$(XmakeProjectDir)", vsutils.escape(path.relative(dir, project.directory()))) end return vsutils.escape(dir) end return path.join("$(XmakeProjectDir)", vsutils.escape(dir)) end local r = {} for k, v in ipairs(dir) do r[k] = _make_dirs(v) end r = table.unique(r) return path.joinenv(r) end function _make_arrs(arr, sep) if arr == nil then return "" end if type(arr) == "string" then return vsutils.escape(arr) end local r = {} for k, v in ipairs(arr) do r[k] = _make_arrs(v, sep) end r = table.unique(r) return table.concat(r, sep or ";") end -- get values from target function _get_values_from_target(target, name) local values = {} for _, value in ipairs((target:get_from(name, "*"))) do table.join2(values, value) end return table.unique(values) end -- get flags from target function _get_flags_from_target(target, name) local flags = _get_values_from_target(target, name) return target_utils.translate_flags_in_tool(target, name, flags) end -- make target info function _make_targetinfo(mode, arch, target) -- init target info local targetinfo = { mode = mode , arch = arch , plat = config.get("plat") , vsarch = vsutils.vsarch(arch) , sdkver = config.get("vs_sdkver") } -- write only if not default -- use target:get("xxx") rather than target:xxx() -- save target kind targetinfo.kind = target:kind() -- is default? targetinfo.default = tostring(target:is_default()) -- save target file targetinfo.basename = vsutils.escape(target:basename()) targetinfo.filename = vsutils.escape(target:filename()) -- save dirs targetinfo.targetdir = _make_dirs(target:get("targetdir")) targetinfo.buildir = _make_dirs(config.get("buildir")) targetinfo.rundir = _make_dirs(target:get("rundir")) targetinfo.configdir = _make_dirs(os.getenv("XMAKE_CONFIGDIR")) targetinfo.configfiledir = _make_dirs(target:get("configdir")) targetinfo.includedirs = _make_dirs(table.join(_get_values_from_target(target, "includedirs") or {}, _get_values_from_target(target, "sysincludedirs"))) targetinfo.linkdirs = _make_dirs(_get_values_from_target(target, "linkdirs")) targetinfo.forceincludes = path.joinenv(table.wrap(_get_values_from_target(target, "forceincludes"))) targetinfo.sourcedirs = _make_dirs(_get_values_from_target(target, "values.project.vsxmake.sourcedirs")) targetinfo.pcheaderfile = target:pcheaderfile("cxx") or target:pcheaderfile("c") -- save defines targetinfo.defines = _make_arrs(_get_values_from_target(target, "defines")) -- save flags targetinfo.cflags = _make_arrs(_get_flags_from_target(target, "cflags"), " ") targetinfo.cxflags = _make_arrs(_get_flags_from_target(target, "cxflags"), " ") targetinfo.cxxflags = _make_arrs(_get_flags_from_target(target, "cxxflags"), " ") -- save languages targetinfo.languages = _make_arrs(_get_values_from_target(target, "languages")) if targetinfo.languages then -- fix c++17 to cxx17 for Xmake.props targetinfo.languages = targetinfo.languages:replace("c++", "cxx", {plain = true}) end if target:is_phony() or target:is_headeronly() or target:is_moduleonly() then return targetinfo end -- save subsystem local linkflags = linker.linkflags(target:kind(), target:sourcekinds(), {target = target}) for _, linkflag in ipairs(linkflags) do if linkflag:lower():find("[%-/]subsystem:windows") then targetinfo.subsystem = "windows" end end if not targetinfo.subsystem then targetinfo.subsystem = "console" end -- save runenvs local targetrunenvs = {} local addrunenvs, setrunenvs = runenvs.make(target) for k, v in table.orderpairs(target:pkgenvs()) do addrunenvs = addrunenvs or {} addrunenvs[k] = table.join(table.wrap(addrunenvs[k]), path.splitenv(v)) end for _, dep in ipairs(target:orderdeps()) do for k, v in table.orderpairs(dep:pkgenvs()) do addrunenvs = addrunenvs or {} addrunenvs[k] = table.join(table.wrap(addrunenvs[k]), path.splitenv(v)) end end for k, v in table.orderpairs(addrunenvs) do -- https://github.com/xmake-io/xmake/issues/3391 v = table.unique(v) if k:upper() == "PATH" then targetrunenvs[k] = _make_dirs(v) .. ";$([System.Environment]::GetEnvironmentVariable('" .. k .. "'))" else targetrunenvs[k] = path.joinenv(v) .. ";$([System.Environment]::GetEnvironmentVariable('" .. k .."'))" end end for k, v in table.orderpairs(setrunenvs) do if #v == 1 then v = v[1] if path.is_absolute(v) and v:startswith(project.directory()) then targetrunenvs[k] = _make_dirs(v) else targetrunenvs[k] = v[1] end else targetrunenvs[k] = path.joinenv(v) end end local runenvstr = {} for k, v in table.orderpairs(targetrunenvs) do table.insert(runenvstr, k .. "=" .. v) end targetinfo.runenvs = table.concat(runenvstr, "\n") local runargs = target:get("runargs") if runargs then targetinfo.runargs = os.args(table.wrap(runargs)) end -- use mfc? save the mfc runtime kind if target:rule("win.sdk.mfc.shared_app") or target:rule("win.sdk.mfc.shared") then targetinfo.mfckind = "Dynamic" elseif target:rule("win.sdk.mfc.static_app") or target:rule("win.sdk.mfc.static") then targetinfo.mfckind = "Static" end -- use cuda? save the cuda runtime version if target:rule("cuda") then local nvcc = find_tool("nvcc", { version = true }) local ver = semver.new(nvcc.version) targetinfo.cudaver = ver:major() .. "." .. ver:minor() end return targetinfo end function _make_vsinfo_modes() local vsinfo_modes = {} local modes = option.get("modes") if modes then if not modes:find("\"") then modes = modes:gsub(",", path.envsep()) end for _, mode in ipairs(path.splitenv(modes)) do table.insert(vsinfo_modes, mode:trim()) end else vsinfo_modes = project.modes() end if not vsinfo_modes or #vsinfo_modes == 0 then vsinfo_modes = { config.mode() } end return vsinfo_modes end function _make_vsinfo_archs() local vsinfo_archs = {} local archs = option.get("archs") if archs then if not archs:find("\"") then archs = archs:gsub(",", path.envsep()) end for _, arch in ipairs(path.splitenv(archs)) do table.insert(vsinfo_archs, arch:trim()) end else -- we use it first if global set_arch("xx") is setted in xmake.lua vsinfo_archs = project.get("target.arch") if not vsinfo_archs then -- for set_allowedarchs() local allowed_archs = project.allowed_archs(config.plat()) if allowed_archs then vsinfo_archs = allowed_archs:to_array() end end if not vsinfo_archs then local default_archs = toolchain.load("msvc"):config("vcarchs") if not default_archs then default_archs = platform.archs() end if default_archs then default_archs = hashset.from(table.wrap(default_archs)) -- just generate single arch by default to avoid some fails for installing packages. -- @see https://github.com/xmake-io/xmake/issues/3268 local arch = config.arch() if default_archs:has(arch) then vsinfo_archs = { arch } else default_archs:remove("arm64") vsinfo_archs = default_archs:to_array() end end end end if not vsinfo_archs or #vsinfo_archs == 0 then vsinfo_archs = { config.arch() } end return vsinfo_archs end function _make_vsinfo_groups() local groups = {} local group_deps = {} for targetname, target in table.orderpairs(project.targets()) do local group_path = target:get("group") if group_path and #(group_path:trim()) > 0 then local group_name = path.filename(group_path) local group_names = path.split(group_path) for idx, name in ipairs(group_names) do local group = groups["group." .. name] or {} group.group = name group.group_id = hash.uuid4("group." .. name) if idx > 1 then group_deps["group_dep." .. name] = {current_id = group.group_id, parent_id = hash.uuid4("group." .. group_names[idx - 1])} end groups["group." .. name] = group end group_deps["group_dep.target." .. targetname] = {current_id = hash.uuid4(targetname), parent_id = groups["group." .. group_name].group_id} end end return groups, group_deps end -- make filter function _make_filter(filepath, target, vcxprojdir) local filter local is_plain = false local filegroups = target.filegroups if filegroups then -- @see https://github.com/xmake-io/xmake/issues/2282 filepath = path.absolute(filepath) local scriptdir = target.absscriptdir local filegroups_extraconf = target.filegroups_extraconf or {} for _, filegroup in ipairs(filegroups) do local extraconf = filegroups_extraconf[filegroup] or {} local rootdir = extraconf.rootdir assert(rootdir, "please set root directory, e.g. add_filegroups(%s, {rootdir = 'xxx'})", filegroup) for _, rootdir in ipairs(table.wrap(rootdir)) do if not path.is_absolute(rootdir) then rootdir = path.absolute(rootdir, scriptdir) end local fileitem = path.relative(filepath, rootdir) local files = extraconf.files or "**" local mode = extraconf.mode for _, filepattern in ipairs(files) do filepattern = path.pattern(path.absolute(path.join(rootdir, filepattern))) if filepath:match(filepattern) then if mode == "plain" then filter = path.normalize(filegroup) is_plain = true else -- file tree mode (default) if filegroup ~= "" then filter = path.normalize(path.join(filegroup, path.directory(fileitem))) else filter = path.normalize(path.directory(fileitem)) end end if filter and filter == '.' then filter = nil end goto found_filter end end -- stop once a rootdir matches if filter then goto found_filter end end ::found_filter:: end end if not filter and not is_plain then -- use the default filter rule filter = path.relative(path.absolute(path.directory(filepath)), vcxprojdir) -- @see https://github.com/xmake-io/xmake/issues/2039 if filter then filter = _strip_dotdirs(filter) end if filter and filter == '.' then filter = nil end end return filter end -- make vstudio project function main(outputdir, vsinfo) -- enter project directory local oldir = os.cd(project.directory()) -- init solution directory vsinfo.solution_dir = path.absolute(path.join(outputdir, "vsxmake" .. vsinfo.vstudio_version)) vsinfo.programdir = _make_dirs(xmake.programdir()) vsinfo.projectdir = project.directory() vsinfo.sln_projectfile = path.relative(project.rootfile(), vsinfo.solution_dir) local projectfile = path.filename(project.rootfile()) vsinfo.slnfile = project.name() or path.filename(project.directory()) -- write only if not default if projectfile ~= "xmake.lua" then vsinfo.projectfile = projectfile end vsinfo.xmake_info = format("xmake version %s", xmake.version()) vsinfo.solution_id = hash.uuid4(project.directory() .. vsinfo.solution_dir) vsinfo.vs_version = vsinfo.project_version .. ".0" -- init modes vsinfo.modes = _make_vsinfo_modes() -- init archs vsinfo.archs = _make_vsinfo_archs() -- init groups local groups, group_deps = _make_vsinfo_groups() vsinfo.groups = table.orderkeys(groups) vsinfo.group_deps = table.orderkeys(group_deps) vsinfo._groups = groups vsinfo._group_deps = group_deps -- init config flags local flags = {} for k, v in table.orderpairs(localcache.get("config", "options")) do if k ~= "plat" and k ~= "mode" and k ~= "arch" and k ~= "clean" and k ~= "buildir" then table.insert(flags, "--" .. k .. "=" .. tostring(v)) end end vsinfo.configflags = os.args(flags) -- load targets local targets = {} vsinfo._arch_modes = {} for _, mode in ipairs(vsinfo.modes) do vsinfo._arch_modes[mode] = {} for _, arch in ipairs(vsinfo.archs) do vsinfo._arch_modes[mode][arch] = { mode = mode, arch = arch } -- trace print("checking for %s.%s ...", mode, arch) -- reload config, project and platform -- modify config config.set("as", nil, {force = true}) -- force to re-check as for ml/ml64 config.set("mode", mode, {readonly = true, force = true}) config.set("arch", arch, {readonly = true, force = true}) -- clear all options for _, opt in ipairs(project.options()) do opt:clear() end -- clear cache memcache.clear() localcache.clear("detect") localcache.clear("option") localcache.clear("package") localcache.clear("toolchain") localcache.clear("cxxmodules") -- check platform platform.load(config.plat(), arch):check() -- check project options project.check_options() -- install and update requires install_requires() -- load targets project.load_targets() -- update config files generate_configfiles() -- ensure to enter project directory os.cd(project.directory()) -- save targets for targetname, target in table.orderpairs(project.targets()) do -- https://github.com/xmake-io/xmake/issues/2337 target:data_set("plugin.project.kind", "vsxmake") -- make target with the given mode and arch targets[targetname] = targets[targetname] or {} local _target = targets[targetname] -- init target info _target.target = targetname _target.vcxprojdir = path.join(vsinfo.solution_dir, targetname) _target.target_id = hash.uuid4(targetname) _target.kind = target:kind() _target.absscriptdir = target:scriptdir() _target.scriptdir = path.relative(target:scriptdir(), _target.vcxprojdir) _target.projectdir = path.relative(project.directory(), _target.vcxprojdir) local targetdir = target:get("targetdir") if targetdir then _target.targetdir = path.relative(targetdir, _target.vcxprojdir) end _target._targets = _target._targets or {} _target._targets[mode] = _target._targets[mode] or {} local targetinfo = _make_targetinfo(mode, arch, target) _target._targets[mode][arch] = targetinfo _target.sdkver = targetinfo.sdkver _target.default = targetinfo.default -- save all sourcefiles and headerfiles _target.sourcefiles = table.unique(table.join(_target.sourcefiles or {}, (target:sourcefiles()))) _target.headerfiles = table.unique(table.join(_target.headerfiles or {}, (target:headerfiles()))) _target.extrafiles = table.unique(table.join(_target.extrafiles or {}, (target:extrafiles()))) -- sort them to stabilize generation table.sort(_target.sourcefiles) table.sort(_target.headerfiles) table.sort(_target.extrafiles) -- save file groups _target.filegroups = table.unique(table.join(_target.filegroups or {}, target:get("filegroups"))) for filegroup, groupconf in pairs(target:extraconf("filegroups")) do _target.filegroups_extraconf = _target.filegroups_extraconf or {} local mergedconf = _target.filegroups_extraconf[filegroup] if not mergedconf then mergedconf = {} _target.filegroups_extraconf[filegroup] = mergedconf end if groupconf.rootdir then mergedconf.rootdir = table.unique(table.join(mergedconf.rootdir or {}, table.wrap(groupconf.rootdir))) end if groupconf.files then mergedconf.files = table.unique(table.join(mergedconf.files or {}, table.wrap(groupconf.files))) end mergedconf.plain = groupconf.plain or mergedconf.plain end -- save deps _target.deps = table.unique(table.join(_target.deps or {}, table.orderkeys(target:deps()), nil)) end end end os.cd(oldir) for _, target in table.orderpairs(targets) do target._paths = {} local dirs = {} local projectdir = project.directory() local root = target.absscriptdir or projectdir target.sourcefiles = table.imap(target.sourcefiles, function(_, v) return path.relative(v, projectdir) end) target.headerfiles = table.imap(target.headerfiles, function(_, v) return path.relative(v, projectdir) end) target.extrafiles = table.imap(target.extrafiles, function(_, v) return path.relative(v, projectdir) end) for _, f in ipairs(table.join(target.sourcefiles, target.headerfiles or {}, target.extrafiles)) do local dir = _make_filter(f, target, root) local escaped_f = vsutils.escape(f) target._paths[f] = { -- @see https://github.com/xmake-io/xmake/issues/2077 path = path.is_absolute(escaped_f) and escaped_f or "$(XmakeProjectDir)\\" .. escaped_f, dir = vsutils.escape(dir) } while dir and dir ~= "." do if not dirs[dir] then dirs[dir] = { dir = vsutils.escape(dir), dir_id = hash.uuid4(dir) } end dir = path.directory(dir) or "." end end target._dirs = dirs target.dirs = table.orderkeys(dirs) target._deps = {} for _, v in ipairs(target.deps) do target._deps[v] = targets[v] end end -- we need to set startup project for default or binary target -- @see https://github.com/xmake-io/xmake/issues/1249 local targetnames = {} for targetname, target in table.orderpairs(project.targets()) do if target:get("default") == true then table.insert(targetnames, 1, targetname) elseif target:is_binary() then local first_target = targetnames[1] and project.target(targetnames[1]) if not first_target or first_target:get("default") ~= true then table.insert(targetnames, 1, targetname) else table.insert(targetnames, targetname) end else table.insert(targetnames, targetname) end end vsinfo.targets = targetnames vsinfo._targets = targets return vsinfo end
0
repos/xmake/xmake/plugins/project
repos/xmake/xmake/plugins/project/vsxmake/render.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 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 render.lua -- function _fill(opt, params) return function(match) local imp = match:match("^Import%((.+)%)$") if imp then local funcs = os.files(path.join(opt.templatedir, imp .. "(*)")) assert(#funcs == 1) local func = funcs[1] local args = path.filename(func):match("%((.+)%)$"):split(",") return _render(func, opt, args) end return opt.paramsprovider(match, params) or "<Not Provided>" end end function _cfill(opt, params) return function(match) local tmp = match:split(";", {strict = true}) assert(#tmp == 2 or #tmp == 3) local cond = tmp[1] local value1 = tmp[2] local value2 = "" if #tmp == 3 then value2 = tmp[3] end tmp = cond:split("=") assert(#tmp == 2) local k = tmp[1]:trim() local v = tmp[2]:trim() if opt.paramsprovider(k, params) == v then return value1 end return value2 end end function _expand(params) local r = {""} for _, v in ipairs(params) do if type(v) == "string" then for i, p in ipairs(r) do r[i] = p .. "\0" .. v end else local newr = {} for _, c in ipairs(v) do local rcopy = {} for i, p in ipairs(r) do rcopy[i] = p .. "\0" .. c end newr = table.join(newr, rcopy) end r = newr end end for i, p in ipairs(r) do r[i] = p:split("\0") end return r end function _render(templatepath, opt, args) local template = io.readfile(templatepath) local params = _expand(opt.paramsprovider(args)) local replaced = "" for _, v in ipairs(params) do local tmpl = template:gsub(opt.cpattern, _cfill(opt, v)) replaced = replaced .. tmpl:gsub(opt.pattern, _fill(opt, v)) end return replaced end function main(templatepath, pattern, cpattern, paramsprovider) local opt = { pattern = pattern, cpattern = cpattern, paramsprovider = paramsprovider, templatedir = path.directory(templatepath) } return _render(templatepath, opt, {}) end
0
repos/xmake/xmake/plugins/project
repos/xmake/xmake/plugins/project/vsxmake/vsxmake.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 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 vsxmake.lua -- -- imports import("core.base.option") import("core.base.hashset") import("vstudio.impl.vsinfo", { rootdir = path.directory(os.scriptdir()) }) import("render") import("getinfo") import("core.project.config") import("core.cache.localcache") local template_root = path.join(os.programdir(), "scripts", "vsxmake", "vsproj", "templates") local template_sln = path.join(template_root, "sln", "vsxmake.sln") local template_vcx = path.join(template_root, "vcxproj", "#target#.vcxproj") local template_fil = path.join(template_root, "vcxproj.filters", "#target#.vcxproj.filters") local template_props = path.join(template_root, "Xmake.Custom.props") local template_targets = path.join(template_root, "Xmake.Custom.targets") local template_items = path.join(template_root, "Xmake.Custom.items") local template_itemfil = path.join(template_root, "Xmake.Custom.items.filters") function _filter_files(files, includeexts, excludeexts) local positive = not excludeexts local extset = hashset.from(positive and includeexts or excludeexts) local f = {} for _, file in ipairs(files) do local ext = path.extension(file) if (positive and extset:has(ext)) or not (positive or extset:has(ext)) then table.insert(f, file) end end table.sort(f) return f end function _buildparams(info, target, default) local function getprop(match, opt) local i = info local r = info[match] if target then opt = table.join(target, opt) end for _, k in ipairs(opt) do local v = (i._targets or {})[k] if v == nil and i._arch_modes then v = i._arch_modes[k] end if v == nil and i._paths then v = i._paths[k] end if v == nil and i._dirs then v = i._dirs[k] end if v == nil and i._deps then v = i._deps[k] end if v == nil and i._groups then v = i._groups[k] end if v == nil and i._group_deps then v = i._group_deps[k] end if v == nil then v = i[k] end if v == nil then raise("key '" .. k .. "' not found") end i = v r = i[match] or r end return r or default end local function listconfig(args) for _, k in ipairs(args) do args[k] = true end local r = {} if args.target then table.insert(r, info.targets) end if args.mode then table.insert(r, info.modes) end if args.arch then table.insert(r, info.archs) end if args.group then table.insert(r, info.groups) end if args.group_dep then table.insert(r, info.group_deps) end if args.dir then table.insert(r, info._targets[target].dirs) end if args.dep then table.insert(r, info._targets[target].deps) end if args.filec then local files = info._targets[target].sourcefiles table.insert(r, _filter_files(files, {".c"})) elseif args.filecxx then local files = info._targets[target].sourcefiles table.insert(r, _filter_files(files, {".cpp", ".cc", ".cxx"})) elseif args.filempp then local files = info._targets[target].sourcefiles table.insert(r, _filter_files(files, {".mpp", ".mxx", ".cppm", ".ixx"})) elseif args.filecu then local files = info._targets[target].sourcefiles table.insert(r, _filter_files(files, {".cu"})) elseif args.fileobj then local files = info._targets[target].sourcefiles table.insert(r, _filter_files(files, {".obj", ".o"})) elseif args.filerc then local files = info._targets[target].sourcefiles table.insert(r, _filter_files(files, {".rc"})) elseif args.fileui then -- for qt/.ui local files = info._targets[target].sourcefiles table.insert(r, _filter_files(files, {".ui"})) elseif args.fileqrc then -- for qt/.qrc local files = info._targets[target].sourcefiles table.insert(r, _filter_files(files, {".qrc"})) elseif args.filets then -- for qt/.ts local files = info._targets[target].sourcefiles table.insert(r, _filter_files(files, {".ts"})) elseif args.incc then local files = table.join(info._targets[target].headerfiles or {}, info._targets[target].extrafiles) table.insert(r, _filter_files(files, nil, {".natvis"})) elseif args.incnatvis then local files = table.join(info._targets[target].headerfiles or {}, info._targets[target].extrafiles) table.insert(r, _filter_files(files, {".natvis"})) end return r end return function(match, opt) if type(match) == "table" then return listconfig(match) end return getprop(match, opt) end end function _trycp(file, target, targetname) targetname = targetname or path.filename(file) local targetfile = path.join(target, targetname) if os.isfile(targetfile) then dprint("skipped file %s since the file already exists", path.relative(targetfile)) return end os.cp(file, targetfile) end function _writefileifneeded(file, content) if os.isfile(file) and io.readfile(file) == content then dprint("skipped file %s since the file has the same content", path.relative(file)) return end -- we need utf8 with bom encoding for unicode -- @see https://github.com/xmake-io/xmake/issues/1689 io.writefile(file, content, {encoding = "utf8bom"}) end -- save plugin arguments for `plugin.vsxmake.autoupdate` -- @see https://github.com/xmake-io/xmake/issues/1895 function _save_plugin_arguments() local vsxmake_cache = localcache.cache("vsxmake") for _, name in ipairs({"kind", "modes", "archs", "outputdir"}) do vsxmake_cache:set(name, option.get(name)) end vsxmake_cache:save() end -- clear cache function _clear_cache() localcache.clear("detect") localcache.clear("option") localcache.clear("package") localcache.clear("toolchain") -- force recheck localcache.set("config", "recheck", true) localcache.save() end -- make function make(version) if not version then version = tonumber(config.get("vs")) if not version then return function(outputdir) raise("invalid vs version, run `xmake f --vs=20xx`") end end end return function(outputdir) -- trace vprint("using project kind vs%d", version) -- check assert(version >= 2010, "vsxmake does not support vs version lower than 2010") -- get info and params local info = getinfo(outputdir, vsinfo(version)) local paramsprovidersln = _buildparams(info) -- write solution file local sln = path.join(info.solution_dir, info.slnfile .. ".sln") _writefileifneeded(sln, render(template_sln, "#([A-Za-z0-9_,%.%*%(%)]+)#", "@([^@]+)@", paramsprovidersln)) -- add solution custom file _trycp(template_props, info.solution_dir) _trycp(template_targets, info.solution_dir) for _, target in ipairs(info.targets) do local paramsprovidertarget = _buildparams(info, target, "<!-- nil -->") local proj_dir = info._targets[target].vcxprojdir -- write project file local proj = path.join(proj_dir, target .. ".vcxproj") _writefileifneeded(proj, render(template_vcx, "#([A-Za-z0-9_,%.%*%(%)]+)#", "@([^@]+)@", paramsprovidertarget)) local projfil = path.join(proj_dir, target .. ".vcxproj.filters") _writefileifneeded(projfil, render(template_fil, "#([A-Za-z0-9_,%.%*%(%)]+)#", "@([^@]+)@", paramsprovidertarget)) -- add project custom file _trycp(template_props, proj_dir) _trycp(template_targets, proj_dir) _trycp(template_items, proj_dir) _trycp(template_itemfil, proj_dir) end -- clear config and local cache _clear_cache() -- save plugin arguments for autoupdate _save_plugin_arguments() end end
0
repos/xmake/xmake/plugins/project
repos/xmake/xmake/plugins/project/make/makefile.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file makefile.lua -- -- imports import("core.base.colors") import("core.tool.compiler") import("core.project.config") import("core.project.project") import("core.language.language") import("core.platform.platform") import("lib.detect.find_tool") import("private.utils.batchcmds") import("private.utils.rule_groups") import("plugins.project.utils.target_cmds", {rootdir = os.programdir()}) -- tranlate path function _translate_path(filepath, outputdir) filepath = path.translate(filepath) if filepath == "" then return "" end if path.is_absolute(filepath) then if filepath:startswith(project.directory()) then return path.relative(filepath, outputdir) end return filepath else return path.relative(path.absolute(filepath), outputdir) end end -- get relative unix path function _get_relative_unix_path(filepath, outputdir) filepath = _translate_path(filepath, outputdir) filepath = path.translate(filepath) return os.args(filepath) end -- translate flag function _translate_flag(flag, outputdir) if flag then if path.instance_of(flag) then flag = flag:clone():set(_get_relative_unix_path(flag:rawstr(), outputdir)):str() elseif path.is_absolute(flag) then flag = _get_relative_unix_path(flag, outputdir) elseif flag:startswith("-fmodule-file=") then flag = "-fmodule-file=" .. _get_relative_unix_path(flag:sub(15), outputdir) elseif flag:startswith("-fmodule-mapper=") then flag = "-fmodule-mapper=" .. _get_relative_unix_path(flag:sub(17), outputdir) elseif flag:startswith("-isystem") and #flag > 8 then flag = "-isystem" .. _get_relative_unix_path(flag:sub(9), outputdir) elseif flag:startswith("-I") and #flag > 2 then flag = "-I" .. _get_relative_unix_path(flag:sub(3), outputdir) elseif flag:startswith("-L") and #flag > 2 then flag = "-L" .. _get_relative_unix_path(flag:sub(3), outputdir) elseif flag:startswith("-F") and #flag > 2 then flag = "-F" .. _get_relative_unix_path(flag:sub(3), outputdir) elseif flag:match("(.+)=(.+)") then local k, v = flag:match("(.+)=(.+)") if v and v:endswith(".ifc") then -- e.g. hello=xxx/hello.ifc flag = k .. "=" .. _get_relative_unix_path(v, outputdir) end end end return flag end -- translate flags function _translate_flags(flags, outputdir) local result = {} for _, flag in ipairs(flags) do if type(flag) == "table" and not path.instance_of(flag) then for _, v in ipairs(flag) do table.insert(result, _translate_flag(v, outputdir)) end else table.insert(result, _translate_flag(flag, outputdir)) end end return result end -- get program from target toolchains function _get_program_from_target(target, toolkind) local program = target:get("toolchain." .. toolkind) if not program then program, _ = target:tool(toolkind) end return program end -- get common flags function _get_common_flags(target, sourcekind, sourcebatch) -- make source flags local sourceflags = {} local flags_stats = {} local files_count = 0 local first_flags = nil for _, sourcefile in ipairs(sourcebatch.sourcefiles) do -- make compiler flags local flags = compiler.compflags(sourcefile, {target = target, sourcekind = sourcekind}) for _, flag in ipairs(flags) do flags_stats[flag] = (flags_stats[flag] or 0) + 1 end -- update files count files_count = files_count + 1 -- save first flags if first_flags == nil then first_flags = flags end -- save source flags sourceflags[sourcefile] = flags end -- make common flags local commonflags = {} for _, flag in ipairs(first_flags) do if flags_stats[flag] >= files_count then table.insert(commonflags, flag) end end -- remove common flags from source flags local sourceflags_ = {} for sourcefile, flags in pairs(sourceflags) do local otherflags = {} for _, flag in ipairs(flags) do if flags_stats[flag] < files_count then table.insert(otherflags, flag) end end sourceflags_[sourcefile] = otherflags end return commonflags, sourceflags_ end -- get command: mkdir function _get_cmd_mkdir(dir) if is_subhost("windows") then return string.format("-@mkdir %s > NUL 2>&1", dir) else return string.format("@mkdir -p %s", dir) end end -- get command: cp function _get_cmd_cp(sourcefile, targetfile) if is_subhost("windows") then return string.format("@copy /Y %s %s > NUL 2>&1", sourcefile, targetfile) else return string.format("@cp %s %s", sourcefile, targetfile) end end -- get command: mv function _get_cmd_mv(sourcefile, targetfile) if is_subhost("windows") then return string.format("@ren %s %s > NUL 2>&1", sourcefile, targetfile) else return string.format("@mv %s %s", sourcefile, targetfile) end end -- get command: ln function _get_cmd_ln(sourcefile, targetfile) if is_subhost("windows") then if os.isdir(sourcefile) then return string.format("@mklink /D %s %s > NUL 2>&1", sourcefile, targetfile) else return string.format("@mklink %s %s > NUL 2>&1", sourcefile, targetfile) end else return string.format("@ln -s %s %s", sourcefile, targetfile) end end -- get command: cpdir function _get_cmd_cpdir(sourcedir, targetdir) if is_subhost("windows") then return string.format("@copy /Y %s %s > NUL 2>&1", sourcedir, targetdir) else return string.format("@cp -r %s %s", sourcedir, targetdir) end end -- get command: rm function _get_cmd_rm(filedir) if is_subhost("windows") then -- we attempt to delete it as file first, we remove it as directory if failed return string.format("@del /F /Q %s > NUL 2>&1 || rmdir /S /Q %s > NUL 2>&1", filedir, filedir) else return string.format("@rm -rf %s", filedir) end end -- get command: rmdir function _get_cmd_rmdir(filedir) if is_subhost("windows") then return string.format("@rmdir /S /Q %s > NUL 2>&1", filedir) else return string.format("@rm -rf %s", filedir) end end -- get command: echo function _get_cmd_echo(str) return string.format("@echo %s", colors.ignore(str)) end -- get command: cd function _get_cmd_cd(dir) return string.format("@cd %s", dir) end -- get command string function _get_command_string(cmd, outputdir) local kind = cmd.kind local opt = cmd.opt if cmd.program then -- @see https://github.com/xmake-io/xmake/discussions/2156 local argv = {} for _, v in ipairs(cmd.argv) do table.insert(argv, _translate_flag(v, outputdir)) end local command = _get_relative_unix_path(cmd.program) .. " " .. os.args(argv) if opt and opt.curdir then wprint("curdir has been not supported in batchcmds:execv() for makefile generator!") end return "%$(VV)" .. command elseif kind == "cp" then if os.isdir(cmd.srcpath) then return _get_cmd_cpdir(get_relative_unix_path(cmd.srcpath, outputdir), _get_relative_unix_path(cmd.dstpath, outputdir)) else return _get_cmd_cp(_get_relative_unix_path(cmd.srcpath, outputdir), _get_relative_unix_path(cmd.dstpath, outputdir)) end elseif kind == "rm" then return _get_cmd_rm(_get_relative_unix_path(cmd.filepath, outputdir)) elseif kind == "rmdir" then return _get_cmd_rmdir(_get_relative_unix_path(cmd.dir, outputdir)) elseif kind == "mv" then return _get_cmd_mv(_get_relative_unix_path(cmd.srcpath, outputdir), _get_relative_unix_path(cmd.dstpath, outputdir)) elseif kind == "ln" then return _get_cmd_ln(_get_relative_unix_path(cmd.srcpath, outputdir), _get_relative_unix_path(cmd.dstpath, outputdir)) elseif kind == "cd" then return _get_cmd_cd(_get_relative_unix_path(cmd.dir, outputdir)) elseif kind == "mkdir" then return _get_cmd_mkdir(_get_relative_unix_path(cmd.dir, outputdir)) elseif kind == "show" then return _get_cmd_echo(cmd.showtext) end end -- remove the given files or directories function _add_remove_files(makefile, filedirs, outputdir) for _, filedir in ipairs(filedirs) do filedir = _get_relative_unix_path(filedir, outputdir) makefile:print("\t%s", _get_cmd_rm(filedir)) end end -- add header function _add_header(makefile) makefile:print([[# this is the build file for project %s # it is autogenerated by the xmake build system. # do not edit by hand. ]], project.name() or "") end -- add switches function _add_switches(makefile) if is_subhost("windows") then makefile:print("!if \"%$(VERBOSE)\" != \"1\"") makefile:print("VV=@") makefile:print("!endif") else makefile:print("ifneq (%$(VERBOSE),1)") makefile:print("VV=@") makefile:print("endif") end makefile:print("") end -- add toolchains function _add_toolchains(makefile, outputdir) -- add ccache local ccache = find_tool("ccache") if ccache then makefile:print("CCACHE=" .. ccache.program) end -- add compilers for sourcekind, _ in pairs(language.sourcekinds()) do local program = platform.tool(sourcekind) if program and program ~= "" then makefile:print("%s=%s", sourcekind:upper(), program) end end makefile:print("") -- add linkers local linkerkinds = {} for _, _linkerkinds in pairs(language.targetkinds()) do table.join2(linkerkinds, _linkerkinds) end for _, linkerkind in ipairs(table.unique(linkerkinds)) do local program = platform.tool(linkerkind) if program and program ~= "" then makefile:print("%s=%s", (linkerkind:upper():gsub('%-', '_')), program) end end makefile:print("") -- add toolchains from targets for targetname, target in pairs(project.targets()) do if not target:is_phony() then local program = _get_program_from_target(target, target:linker():kind()) if program then makefile:print("%s_%s=%s", targetname, target:linker():kind():upper(), program) end for _, sourcebatch in pairs(target:sourcebatches()) do local sourcekind = sourcebatch.sourcekind if sourcekind then local program = _get_program_from_target(target, sourcekind) if program then makefile:print("%s_%s=%s", targetname, sourcekind:upper(), program) end end end end end makefile:print("") end -- add flags function _add_flags(makefile, targetflags, outputdir) for targetname, target in pairs(project.targets()) do if not target:is_phony() then for _, sourcebatch in pairs(target:sourcebatches()) do local sourcekind = sourcebatch.sourcekind if sourcekind then local commonflags, sourceflags = _get_common_flags(target, sourcekind, sourcebatch) makefile:print("%s_%sFLAGS=%s", targetname, sourcekind:upper(), os.args(_translate_flags(commonflags, outputdir))) targetflags[targetname .. '_' .. sourcekind:upper()] = sourceflags end end makefile:print("%s_%sFLAGS=%s", targetname, target:linker():kind():upper(), os.args(_translate_flags(target:linkflags(), outputdir))) end end makefile:print("") end -- add build object function _add_build_object(makefile, target, sourcefile, objectfile, sourceflags, outputdir, precmds_label) -- get the source file kind local sourcekind = language.sourcekind_of(sourcefile) -- get program local program_global = false local program = _get_program_from_target(target, sourcekind) if not program then program = platform.tool(sourcekind) program_global = true end -- get complier flags local compflags = _translate_flags(sourceflags[sourcefile], outputdir) -- translate file paths sourcefile = _get_relative_unix_path(sourcefile, outputdir) objectfile = _get_relative_unix_path(objectfile, outputdir) -- make command local macro = "$\01" .. target:name() .. '_' .. sourcekind:upper() .. "FLAGS\02" local command = compiler.compcmd(sourcefile, objectfile, {target = target, compflags = table.join(macro, compflags)}) command = command:gsub('\01', '(') command = command:gsub('\02', ')') -- replace program to $(XX) local p, e = command:find("\"" .. program .. "\"", 1, true) if not p then p, e = command:find(program, 1, true) end if p then if program_global then command = format("%s$(%s)%s", command:sub(1, p - 1), sourcekind:upper(), command:sub(e + 1)) else command = format("%s$(%s_%s)%s", command:sub(1, p - 1), target:name(), sourcekind:upper(), command:sub(e + 1)) end end -- replace ccache to $(CCACHE) local ccache = config.get("ccache") ~= false and find_tool("ccache") if ccache then p, e = command:find(ccache.program, 1, true) if p then command = format("%s$(%s)%s", command:sub(1, p - 1), "CCACHE", command:sub(e + 1)) end end -- make head makefile:printf("%s:", objectfile) if precmds_label then makefile:printf(" %s", precmds_label) end -- make dependence makefile:print(" %s", sourcefile) -- make body makefile:print("\t%s", _get_cmd_echo(string.format("%scompiling.$(mode) %s", ccache and "ccache " or "", sourcefile))) makefile:print("\t%s", _get_cmd_mkdir(path.directory(objectfile))) makefile:writef("\t$(VV)%s\n", command) -- make tail makefile:print("") end -- add build objects function _add_build_objects(makefile, target, sourcekind, sourcebatch, sourceflags, outputdir, precmds_label) local handled_objects = target:data("makefile.handled_objects") if not handled_objects then handled_objects = {} target:data_set("makefile.handled_objects", handled_objects) end for index, objectfile in ipairs(sourcebatch.objectfiles) do -- remove repeat -- this is because some rules will repeatedly bind the same sourcekind, e.g. `rule("c++.build.modules.builder")` if not handled_objects[objectfile] then _add_build_object(makefile, target, sourcebatch.sourcefiles[index], objectfile, sourceflags, outputdir, precmds_label) handled_objects[objectfile] = true end end end -- add build phony function _add_build_phony(makefile, target) -- make dependence for the dependent targets makefile:printf("%s:", target:name()) for _, dep in ipairs(target:get("deps")) do makefile:write(" " .. dep) end makefile:print("") end -- add custom commands before building target function _add_build_custom_commands_before(makefile, target, sourcegroups, outputdir) -- add before commands -- we use irpairs(groups), because the last group that should be given the highest priority. local cmds_before = {} target_cmds.get_target_buildcmd(target, cmds_before, {suffix = "before"}) target_cmds.get_target_buildcmd_sourcegroups(target, cmds_before, sourcegroups, {suffix = "before"}) target_cmds.get_target_buildcmd_sourcegroups(target, cmds_before, sourcegroups) local targetname = target:name() local label = "precmds_" .. targetname if #cmds_before > 0 then makefile:print("%s:", label) for _, cmd in ipairs(cmds_before) do local command = _get_command_string(cmd, outputdir) if command then makefile:print("\t%s", command) end end makefile:print("") return label end end -- add custom commands after building target function _add_build_custom_commands_after(makefile, target, sourcegroups, outputdir) local cmds_after = {} target_cmds.get_target_buildcmd_sourcegroups(target, cmds_after, sourcegroups, {suffix = "after"}) target_cmds.get_target_buildcmd(target, cmds_after, {suffix = "after"}) if #cmds_after > 0 then for _, cmd in ipairs(cmds_after) do local command = _get_command_string(cmd, outputdir) if command then makefile:print("\t%s", command) end end end end -- add build target function _add_build_target(makefile, target, targetflags, outputdir) -- https://github.com/xmake-io/xmake/issues/2337 target:data_set("plugin.project.kind", "makefile") -- build sourcebatch groups first local sourcegroups = rule_groups.build_sourcebatch_groups(target, target:sourcebatches()) -- add custom commands before building target local precmds_label = _add_build_custom_commands_before(makefile, target, sourcegroups, outputdir) -- is phony target? if target:is_phony() then return _add_build_phony(makefile, target) end -- make head local targetfile = _get_relative_unix_path(target:targetfile(), outputdir) local targetname = target:name() -- rules like `./target` and `target` are equivalent and can causes issues -- for cases where targetdir is . -- in these cases, the targetfile rule is not created if target:targetfile() == "./" .. targetname then makefile:printf("%s:", targetname) if precmds_label then makefile:printf(" %s", precmds_label) end else makefile:print("%s: %s", targetname, targetfile) makefile:printf("%s:", targetfile) end if precmds_label then makefile:printf(" %s", precmds_label) end -- make dependence for the dependent targets for _, depname in ipairs(target:get("deps")) do local dep = project.target(depname) makefile:write(" " .. (dep:is_phony() and depname or _get_relative_unix_path(dep:targetfile(), outputdir))) end -- make dependence for objects local objectfiles = target:objectfiles() local objectfiles_translated = {} for _, objectfile in ipairs(objectfiles) do objectfile = _get_relative_unix_path(objectfile, outputdir) table.insert(objectfiles_translated, objectfile) makefile:write(" " .. objectfile) end -- make dependence end makefile:print("") -- get linker kind local linkerkind = target:linker():kind() -- get program local program_global = false local program = _get_program_from_target(target, linkerkind) if not program then program = platform.tool(linkerkind) program_global = true end -- get command local command = target:linker():linkcmd(objectfiles_translated, targetfile, {target = target}) -- replace linkflags to $(XX) local p, e = command:find(os.args(target:linkflags()), 1, true) if p then command = format("%s$(%s_%sFLAGS)%s", command:sub(1, p - 1), target:name(), (linkerkind:upper():gsub('%-', '_')), command:sub(e + 1)) end -- replace program to $(XX) p, e = command:find("\"" .. program .. "\"", 1, true) if not p then p, e = command:find(program, 1, true) end if p then if program_global then command = format("%s$(%s)%s", command:sub(1, p - 1), (linkerkind:upper():gsub('%-', '_')), command:sub(e + 1)) else command = format("%s$(%s_%s)%s", command:sub(1, p - 1), target:name(), (linkerkind:upper():gsub('%-', '_')), command:sub(e + 1)) end end -- make body makefile:print("\t%s", _get_cmd_echo(string.format("linking.$(mode) %s", path.filename(targetfile)))) makefile:print("\t%s", _get_cmd_mkdir(path.directory(targetfile))) makefile:writef("\t$(VV)%s\n", command) -- add custom commands after building target _add_build_custom_commands_after(makefile, target, sourcegroups, outputdir) -- end makefile:print("") -- build source batches for _, sourcebatch in pairs(target:sourcebatches()) do local sourcekind = sourcebatch.sourcekind if sourcekind then -- compile source files to single object at once local sourceflags = targetflags[target:name() .. '_' .. sourcekind:upper()] _add_build_objects(makefile, target, sourcekind, sourcebatch, sourceflags, outputdir, precmds_label) end end end -- add build targets function _add_build_targets(makefile, targetflags, outputdir) local default = "" for targetname, target in pairs(project.targets()) do if target:is_default() then default = default .. " " .. targetname end end makefile:print("default: %s\n", default) local all = "" for targetname, _ in pairs(project.targets()) do all = all .. " " .. targetname end makefile:print("all: %s\n", all) makefile:print(".PHONY: default all %s\n", all) for _, target in pairs(project.targets()) do _add_build_target(makefile, target, targetflags, outputdir) end end -- add build function _add_build(makefile, targetflags, outputdir) -- TODO -- disable precompiled header first for _, target in pairs(project.targets()) do target:set("pcheader", nil) target:set("pcxxheader", nil) end -- add build targets _add_build_targets(makefile, targetflags, outputdir) end -- add clean target function _add_clean_target(makefile, target, outputdir) makefile:printf("clean_%s: ", target:name()) for _, dep in ipairs(target:get("deps")) do makefile:write(" clean_" .. dep) end makefile:print("") if not target:is_phony() then _add_remove_files(makefile, target:targetfile(), outputdir) _add_remove_files(makefile, target:symbolfile(), outputdir) _add_remove_files(makefile, target:objectfiles(), outputdir) end makefile:print("") end -- add clean targets function _add_clean_targets(makefile, outputdir) local all = "" for targetname, _ in pairs(project.targets()) do all = all .. " clean_" .. targetname end makefile:print("clean: %s\n", all) -- add clean targets for _, target in pairs(project.targets()) do _add_clean_target(makefile, target, outputdir) end end -- add clean function _add_clean(makefile, outputdir) _add_clean_targets(makefile, outputdir) end function make(outputdir) -- enter project directory local oldir = os.cd(os.projectdir()) -- open the makefile local makefile = io.open(path.join(outputdir, "makefile"), "w") -- add header _add_header(makefile) -- add switches _add_switches(makefile) -- add toolchains _add_toolchains(makefile, outputdir) -- add flags local targetflags = {} _add_flags(makefile, targetflags, outputdir) -- add build _add_build(makefile, targetflags, outputdir) -- add clean _add_clean(makefile, outputdir) -- close the makefile makefile:close() -- leave project directory os.cd(oldir) end
0
repos/xmake/xmake/plugins/project
repos/xmake/xmake/plugins/project/make/xmakefile.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file xmakefile.lua -- -- imports import("core.project.project") -- make head function _make_head(makefile) -- verbose? makefile:print("ifeq (%$(V),1)") makefile:print("VERBOSE=-v") makefile:print("else") makefile:print("VERBOSE=") makefile:print("endif") makefile:print("") -- diagnosis? makefile:print("ifeq (%$(D),1)") makefile:print("DIAGNOSIS=-D") makefile:print("else") makefile:print("DIAGNOSIS=") makefile:print("endif") makefile:print("") end -- make build function _make_build(makefile) makefile:print(".PHONY: build") makefile:print("") makefile:print("build: ") makefile:print("\t@xmake --build %$(VERBOSE) %$(DIAGNOSIS) %$(TARGET)") makefile:print("") end -- make rebuild function _make_rebuild(makefile) makefile:print("rebuild: ") makefile:print("\t@xmake --rebuild %$(VERBOSE) %$(DIAGNOSIS) %$(TARGET)") makefile:print("") end -- make install function _make_install(makefile) makefile:print("install: ") makefile:print("\t@xmake install %$(VERBOSE) %$(DIAGNOSIS) %$(TARGET)") makefile:print("") end -- make uninstall function _make_uninstall(makefile) makefile:print("uninstall: ") makefile:print("\t@xmake uninstall %$(VERBOSE) %$(DIAGNOSIS) %$(TARGET)") makefile:print("") end -- make package function _make_package(makefile) makefile:print("package: ") makefile:print("\t@xmake package %$(VERBOSE) %$(DIAGNOSIS) %$(TARGET)") makefile:print("") end -- make clean function _make_clean(makefile) makefile:print("clean: ") makefile:print("\t@xmake clean %$(VERBOSE) %$(DIAGNOSIS) %$(TARGET)") makefile:print("") end -- make run function _make_run(makefile) makefile:print("run: ") makefile:print("\t@xmake run %$(VERBOSE) %$(DIAGNOSIS) %$(TARGET)") makefile:print("") end -- make debug function _make_debug(makefile) makefile:print("debug: ") makefile:print("\t@xmake run -d %$(VERBOSE) %$(DIAGNOSIS) %$(TARGET)") makefile:print("") end -- make config function _make_config(makefile) makefile:print("ifneq (%$(PLAT),)") makefile:print("ifneq (%$(ARCH),)") makefile:print("ifneq (%$(MODE),)") makefile:print("CONFIG=xmake config -c %$(VERBOSE) %$(DIAGNOSIS) -p %$(PLAT) -a %$(ARCH) -m %$(MODE) %$(TARGET)") makefile:print("else") makefile:print("CONFIG=xmake config -c %$(VERBOSE) %$(DIAGNOSIS) -p %$(PLAT) -a %$(ARCH) %$(TARGET)") makefile:print("endif") makefile:print("else") makefile:print("CONFIG=xmake config -c %$(VERBOSE) %$(DIAGNOSIS) -p %$(PLAT) %$(TARGET)") makefile:print("endif") makefile:print("else") makefile:print("CONFIG=xmake config -c %$(VERBOSE) %$(DIAGNOSIS) %$(TARGET)") makefile:print("endif") makefile:print("config: ") makefile:print("\t@%$(CONFIG)") makefile:print("") end -- make function make(outputdir) -- enter project directory local oldir = os.cd(os.projectdir()) -- open the makefile local makefile = io.open(path.join(outputdir, "makefile"), "w") -- make head _make_head(makefile) -- make build _make_build(makefile) -- make rebuild _make_rebuild(makefile) -- make install _make_install(makefile) -- make uninstall _make_uninstall(makefile) -- make package _make_package(makefile) -- make clean _make_clean(makefile) -- make run _make_run(makefile) -- make debug _make_debug(makefile) -- make config _make_config(makefile) -- close the makefile makefile:close() -- leave project directory os.cd(oldir) end
0
repos/xmake/xmake/plugins/project
repos/xmake/xmake/plugins/project/vstudio/vs.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file vs.lua -- -- imports import("impl.vs200x") import("impl.vs201x") import("impl.vsinfo") import("core.tool.toolchain") import("core.project.config") -- make factory function make(version) if not version then version = tonumber(toolchain.load("msvc"):config("vs") or config.get("vs")) if not version then return function (outputdir) raise("invalid vs version, run `xmake f --vs=201x`") end end end -- get vs version info local info = vsinfo(version) if version < 2010 then return function (outputdir) vprint("using project kind vs%d", version) vs200x.make(outputdir, info) end else return function (outputdir) wprint("please use the new vs project generator, .e.g xmake project -k vsxmake") vprint("using project kind vs%d", version) vs201x.make(outputdir, info) end end end
0
repos/xmake/xmake/plugins/project/vstudio
repos/xmake/xmake/plugins/project/vstudio/impl/vs201x_solution.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file vs201x_solution.lua -- -- imports import("core.project.project") import("vsfile") import("vsutils") -- make header function _make_header(slnfile, vsinfo) slnfile:print("Microsoft Visual Studio Solution File, Format Version %s.00", vsinfo.solution_version) slnfile:print("# Visual Studio %s", vsinfo.vstudio_version) end -- make projects function _make_projects(slnfile, vsinfo) -- make all targets local groups = {} local targets = {} local vctool = "8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942" for targetname, target in table.orderpairs(project.targets()) do -- we need to set startup project for default or binary target -- @see https://github.com/xmake-io/xmake/issues/1249 if target:get("default") == true then table.insert(targets, 1, target) elseif target:is_binary() then local first_target = targets[1] if not first_target or first_target:get("default") ~= true then table.insert(targets, 1, target) else table.insert(targets, target) end else table.insert(targets, target) end end for _, target in ipairs(targets) do local targetname = target:name() slnfile:enter("Project(\"{%s}\") = \"%s\", \"%s\\%s.vcxproj\", \"{%s}\"", vctool, targetname, targetname, targetname, hash.uuid4(targetname)) for _, dep in ipairs(target:get("deps")) do slnfile:enter("ProjectSection(ProjectDependencies) = postProject") slnfile:print("{%s} = {%s}", hash.uuid4(dep), hash.uuid4(dep)) slnfile:leave("EndProjectSection") end slnfile:leave("EndProject") local group_path = target:get("group") if group_path and #(group_path:trim()) > 0 then for _, group_name in ipairs(path.split(group_path)) do groups[group_name] = hash.uuid4("group." .. group_name) end end end -- make all groups local project_group_uuid = "2150E333-8FDC-42A3-9474-1A3956D46DE8" for group_name, group_uuid in table.orderpairs(groups) do slnfile:enter("Project(\"{%s}\") = \"%s\", \"%s\", \"{%s}\"", project_group_uuid, group_name, group_name, group_uuid) slnfile:leave("EndProject") end end -- make global function _make_global(slnfile, vsinfo) -- enter global slnfile:enter("Global") -- add solution configuration platforms slnfile:enter("GlobalSection(SolutionConfigurationPlatforms) = preSolution") for _, mode in ipairs(vsinfo.modes) do for _, arch in ipairs(vsinfo.archs) do slnfile:print("%s|%s = %s|%s", mode, arch, mode, arch) end end slnfile:leave("EndGlobalSection") -- add project configuration platforms slnfile:enter("GlobalSection(ProjectConfigurationPlatforms) = postSolution") for targetname, target in table.orderpairs(project.targets()) do for _, mode in ipairs(vsinfo.modes) do for _, arch in ipairs(vsinfo.archs) do local vs_arch = vsutils.vsarch(arch) slnfile:print("{%s}.%s|%s.ActiveCfg = %s|%s", hash.uuid4(targetname), mode, arch, mode, vs_arch) slnfile:print("{%s}.%s|%s.Build.0 = %s|%s", hash.uuid4(targetname), mode, arch, mode, vs_arch) end end end slnfile:leave("EndGlobalSection") -- add solution properties slnfile:enter("GlobalSection(SolutionProperties) = preSolution") slnfile:print("HideSolutionNode = FALSE") slnfile:leave("EndGlobalSection") -- add project groups slnfile:enter("GlobalSection(NestedProjects) = preSolution") local subgroups = {} for targetname, target in table.orderpairs(project.targets()) do local group_path = target:get("group") if group_path then -- target -> group local group_name = path.filename(group_path) slnfile:print("{%s} = {%s}", hash.uuid4(targetname), hash.uuid4("group." .. group_name)) -- group -> group -> ... local group_names = path.split(group_path) for idx, group_name in ipairs(group_names) do local group_name_sub = group_names[idx + 1] local key = group_name .. (group_name_sub or "") if group_name_sub and not subgroups[key] then slnfile:print("{%s} = {%s}", hash.uuid4("group." .. group_name_sub), hash.uuid4("group." .. group_name)) subgroups[key] = true end end end end slnfile:leave("EndGlobalSection") -- leave global slnfile:leave("EndGlobal") end -- make solution function make(vsinfo) -- init solution name vsinfo.solution_name = project.name() or ("vs" .. vsinfo.vstudio_version) -- open solution file local slnpath = path.join(vsinfo.solution_dir, vsinfo.solution_name .. ".sln") local slnfile = vsfile.open(slnpath, "w") -- init indent character vsfile.indentchar('\t') -- make header _make_header(slnfile, vsinfo) -- make projects _make_projects(slnfile, vsinfo) -- make global _make_global(slnfile, vsinfo) -- exit solution file slnfile:close() end
0
repos/xmake/xmake/plugins/project/vstudio
repos/xmake/xmake/plugins/project/vstudio/impl/vs201x_vcxproj_filters.lua
--!A cross-platform build utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author EnoroF, ruki -- @file vs201x_vcxproj_filters.lua -- -- imports import("core.tool.compiler") import("vsfile") -- make header function _make_header(filtersfile, vsinfo) -- the versions local versions = { vs2010 = '10.0' , vs2012 = '11.0' , vs2013 = '12.0' , vs2015 = '14.0' , vs2017 = '15.0' , vs2019 = '16.0' , vs2022 = '17.0' } -- make header filtersfile:print("<?xml version=\"1.0\" encoding=\"utf-8\"?>") filtersfile:enter("<Project ToolsVersion=\"%s\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">", vsinfo.filters_version or versions[vsinfo.vstudio_version]) end -- make tailer function _make_tailer(filtersfile, vsinfo) filtersfile:leave("</Project>") end -- strip dot directories, e.g. ..\..\.. => .. -- @see https://github.com/xmake-io/xmake/issues/2039 function _strip_dotdirs(dir) local count dir, count = dir:gsub("%.%.[\\/]%.%.", "..") if count > 0 then dir = _strip_dotdirs(dir) end return dir end -- make filter function _make_filter(filepath, target, vcxprojdir) local filter local is_plain = false local filegroups = target.filegroups if filegroups then -- @see https://github.com/xmake-io/xmake/issues/2282 filepath = path.absolute(filepath) local scriptdir = target.scriptdir local filegroups_extraconf = target.filegroups_extraconf or {} for _, filegroup in ipairs(filegroups) do local extraconf = filegroups_extraconf[filegroup] or {} local rootdir = extraconf.rootdir assert(rootdir, "please set root directory, e.g. add_filegroups(%s, {rootdir = 'xxx'})", filegroup) for _, rootdir in ipairs(table.wrap(rootdir)) do if not path.is_absolute(rootdir) then rootdir = path.absolute(rootdir, scriptdir) end local fileitem = path.relative(filepath, rootdir) local files = extraconf.files or "**" local mode = extraconf.mode for _, filepattern in ipairs(files) do filepattern = path.pattern(path.absolute(path.join(rootdir, filepattern))) if filepath:match(filepattern) then if mode == "plain" then filter = path.normalize(filegroup) is_plain = true else -- file tree mode (default) if filegroup ~= "" then filter = path.normalize(path.join(filegroup, path.directory(fileitem))) else filter = path.normalize(path.directory(fileitem)) end end if filter and filter == '.' then filter = nil end goto found_filter end end -- stop once a rootdir matches if filter then goto found_filter end end ::found_filter:: end end if not filter and not is_plain then -- use the default filter rule filter = path.relative(path.absolute(path.directory(filepath)), target.scriptdir or vcxprojdir) -- @see https://github.com/xmake-io/xmake/issues/2039 if filter then filter = _strip_dotdirs(filter) end if filter and filter == '.' then filter = nil end end return filter end -- make filters function _make_filters(filtersfile, vsinfo, target, vcxprojdir) -- add filters filtersfile:enter("<ItemGroup>") local exists = {} for _, filepath in pairs(table.join(target.sourcefiles, target.headerfiles or {}, target.extrafiles)) do local filter = _make_filter(filepath, target, vcxprojdir) while filter and filter ~= '.' do if not exists[filter] then filtersfile:enter("<Filter Include=\"%s\">", filter) filtersfile:print("<UniqueIdentifier>{%s}</UniqueIdentifier>", hash.uuid4(filter)) filtersfile:leave("</Filter>") exists[filter] = true end filter = path.directory(filter) end end filtersfile:leave("</ItemGroup>") end -- make sources function _make_sources(filtersfile, vsinfo, target, vcxprojdir) -- and sources filtersfile:enter("<ItemGroup>") for _, sourcefile in ipairs(target.sourcefiles) do local filter = _make_filter(sourcefile, target, vcxprojdir) if filter then local nodename local ext = path.extension(sourcefile) if ext == "asm" then nodename = "CustomBuild" elseif ext == "cu" then nodename = "CudaCompile" else nodename = "ClCompile" end filtersfile:enter("<%s Include=\"%s\">", nodename, path.relative(path.absolute(sourcefile), vcxprojdir)) filtersfile:print("<Filter>%s</Filter>", filter) filtersfile:leave("</%s>", nodename) end local pcheader = target.pcxxheader or target.pcheader if pcheader then local filter = _make_filter(pcheader, target, vcxprojdir) if filter then filtersfile:enter("<ClCompile Include=\"%s\">", path.relative(path.absolute(pcheader), vcxprojdir)) filtersfile:print("<Filter>%s</Filter>", filter) filtersfile:leave("</ClCompile>") end end end filtersfile:leave("</ItemGroup>") end -- make includes function _make_includes(filtersfile, vsinfo, target, vcxprojdir) filtersfile:enter("<ItemGroup>") for _, includefile in ipairs(table.join(target.headerfiles or {}, target.extrafiles)) do local filter = _make_filter(includefile, target, vcxprojdir) if filter then filtersfile:enter("<ClInclude Include=\"%s\">", path.relative(path.absolute(includefile), vcxprojdir)) filtersfile:print("<Filter>%s</Filter>", filter) filtersfile:leave("</ClInclude>") end end filtersfile:leave("</ItemGroup>") end -- main filters function make(vsinfo, target) -- the target name local targetname = target.name -- the vcxproj directory local vcxprojdir = path.join(vsinfo.solution_dir, targetname) -- open vcxproj.filters file local filterspath = path.join(vcxprojdir, targetname .. ".vcxproj.filters") local filtersfile = vsfile.open(filterspath, "w") -- init indent character vsfile.indentchar(' ') -- make header _make_header(filtersfile, vsinfo) -- make filters _make_filters(filtersfile, vsinfo, target, vcxprojdir) -- make sources _make_sources(filtersfile, vsinfo, target, vcxprojdir) -- make includes _make_includes(filtersfile, vsinfo, target, vcxprojdir) -- make tailer _make_tailer(filtersfile, vsinfo) -- exit solution file filtersfile:close() end
0
repos/xmake/xmake/plugins/project/vstudio
repos/xmake/xmake/plugins/project/vstudio/impl/vs200x_vcproj.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file vs200x_vcproj.lua -- -- imports import("core.tool.linker") import("core.tool.compiler") import("core.project.config") import("vsfile") -- make compiling flags function _make_compflags(sourcefile, target, vcprojdir) -- make the compiling flags local compflags = compiler.compflags(sourcefile, {target = target}) -- replace -Idir or /Idir, -Fdsymbol.pdb or /Fdsymbol.pdb local flags = {} for _, flag in ipairs(compflags) do -- replace -Idir or /Idir flag = flag:gsub("[%-|/]I(.*)", function (dir) dir = path.translate(dir:trim()) if not path.is_absolute(dir) then dir = path.relative(path.absolute(dir), vcprojdir) end return "/I" .. dir end) -- replace -Fdsymbol.pdb or /Fdsymbol.pdb flag = flag:gsub("[%-|/]Fd(.*)", function (dir) dir = path.translate(dir:trim()) if not path.is_absolute(dir) then dir = path.relative(path.absolute(dir), vcprojdir) end return "/Fd" .. dir end) -- save flag table.insert(flags, flag) end -- make flags string flags = os.args(flags) -- replace " => &quot; flags = flags:gsub("\"", "&quot;") -- ok? return flags end -- make linking flags function _make_linkflags(target, vcprojdir) -- make the linking flags local linkflags = linker.linkflags(target:kind(), target:sourcekinds(), {target = target}) -- replace -libpath:dir or /libpath:dir, -pdb:symbol.pdb or /pdb:symbol.pdb local flags = {} for _, flag in ipairs(linkflags) do -- replace -libpath:dir or /libpath:dir flag = flag:gsub("[%-|/]libpath:(.*)", function (dir) dir = path.translate(dir:trim()) if not path.is_absolute(dir) then dir = path.relative(path.absolute(dir), vcprojdir) end return "/libpath:" .. dir end) -- replace -pdb:symbol.pdb or /pdb:symbol.pdb flag = flag:gsub("[%-|/]pdb:(.*)", function (dir) dir = path.translate(dir:trim()) if not path.is_absolute(dir) then dir = path.relative(path.absolute(dir), vcprojdir) end return "/pdb:" .. dir end) -- save flag table.insert(flags, flag) end -- make flags string flags = os.args(flags) -- replace " => &quot; flags = flags:gsub("\"", "&quot;") -- ok? return flags end -- make header function _make_header(vcprojfile, vsinfo, target) -- the target name local targetname = target:name() -- make header vcprojfile:print("<?xml version=\"1.0\" encoding=\"utf-8\"?>") vcprojfile:enter("<VisualStudioProject") vcprojfile:print("ProjectType=\"Visual C++\"") vcprojfile:print("Version=\"%s0\"", assert(vsinfo.project_version)) vcprojfile:print("Name=\"%s\"", targetname) vcprojfile:print("ProjectGUID=\"{%s}\"", hash.uuid4(targetname)) vcprojfile:print("RootNamespace=\"%s\"", targetname) vcprojfile:print("TargetFrameworkVersion=\"196613\"") vcprojfile:print(">") end -- make tailer function _make_tailer(vcprojfile, vsinfo, target) vcprojfile:leave("</VisualStudioProject>") end -- make platforms function _make_platforms(vcprojfile, vsinfo, target) -- add Win32 platform vcprojfile:enter("<Platforms>") vcprojfile:enter("<Platform") vcprojfile:print("Name=\"Win32\"") vcprojfile:leave("/>") vcprojfile:leave("</Platforms>") end -- make toolfiles function _make_toolfiles(vcprojfile, vsinfo, target) -- empty toolfiles vcprojfile:enter("<ToolFiles>") vcprojfile:leave("</ToolFiles>") end -- make VCCLCompilerTool -- -- e.g. -- -- <Tool -- Name="VCCLCompilerTool" -- AdditionalOptions="/TP" -- Optimization="0" -- AdditionalIncludeDirectories="&quot;$(SolutionDir)\..\..\src&quot;;&quot;" -- PreprocessorDefinitions="" -- MinimalRebuild="true" -- BasicRuntimeChecks="3" -- RuntimeLibrary="3" -- UsePrecompiledHeader="0" -- WarningLevel="3" -- DebugInformationFormat="4" -- /> function _make_VCCLCompilerTool(vcprojfile, vsinfo, target, compflags) vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCCLCompilerTool\"") vcprojfile:print("ProgramDataBaseFileName=\"\"") -- disable pdb file default -- MT:0, MTd:1, MD:2, MDd:3, ML:4, MLd:5 local runtime = 0 for _,flag in pairs(compflags) do if flag:find("[%-|/]MD") then runtime = 2 break elseif flag:find("[%-|/]MT") then runtime = 0 break end end vcprojfile:print("RuntimeLibrary=\"%d\"", is_mode("debug") and runtime + 1 or runtime) vcprojfile:leave("/>") end -- make VCLinkerTool -- -- e.g. -- <Tool -- Name="VCLinkerTool" -- AdditionalDependencies="xxx.lib" -- LinkIncremental="2" -- AdditionalLibraryDirectories="&quot;$(SolutionDir)\..\..\lib&quot;" -- GenerateDebugInformation="true" -- SubSystem="1" -- TargetMachine="1" -- /> function _make_VCLinkerTool(vcprojfile, vsinfo, target, vcprojdir) -- need not linker? local kind = target:kind() if kind ~= "binary" and kind ~= "shared" then vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCLinkerTool\"") vcprojfile:leave("/>") return end -- generate debug infomation? local debug = false for _, symbol in ipairs(target:get("symbols")) do if symbol == "debug" then debug = true break end end -- subsystem, console: 1, windows: 2 local subsystem = 1 local flags = _make_linkflags(target, vcprojdir) if flags:lower():find("[%-/]subsystem:windows") then subsystem = 2 end -- make it vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCLinkerTool\"") vcprojfile:print("AdditionalOptions=\"%s\"", flags) vcprojfile:print("AdditionalDependencies=\"\"") vcprojfile:print("AdditionalLibraryDirectories=\"\"") vcprojfile:print("LinkIncremental=\"2\"") -- enable: 2, disable: 1 vcprojfile:print("GenerateDebugInformation=\"%s\"", tostring(debug)) vcprojfile:print("SubSystem=\"%d\"", subsystem) -- console: 1, windows: 2 vcprojfile:print("TargetMachine=\"%d\"", is_arch("x64") and 17 or 1) vcprojfile:leave("/>") end -- make configurations function _make_configurations(vcprojfile, vsinfo, target, vcprojdir) -- init configuration type local configuration_types = { binary = 1 , shared = 2 , static = 4 } -- save compiler flags local compflags=nil for _, sourcebatch in pairs(target:sourcebatches()) do local sourcekind = sourcebatch.sourcekind if sourcekind then for _, sourcefile in ipairs(sourcebatch.sourcefiles) do local flags = compiler.compflags(sourcefile, {target = target}) if sourcekind == "cc" or sourcekind == "cxx" then compflags = flags break end end end if compflags then break end end -- use mfc? not used: 0, static: 1, shared: 2 local usemfc = 0 if target:rule("win.sdk.mfc.shared_app") or target:rule("win.sdk.mfc.shared") then usemfc = 2 elseif target:rule("win.sdk.mfc.static_app") or target:rule("win.sdk.mfc.static") then usemfc = 1 end -- set unicode local unicode = false for _, flag in ipairs(compflags) do if flag:find("[%-|/]DUNICODE") then unicode = true break end end -- enter configurations vcprojfile:enter("<Configurations>") -- make configuration for the current mode vcprojfile:enter("<Configuration") vcprojfile:print("Name=\"$(mode)|Win32\"") vcprojfile:print("OutputDirectory=\"%s\"", path.relative(path.absolute(target:targetdir()), vcprojdir)) vcprojfile:print("IntermediateDirectory=\"%s\"", path.relative(path.absolute(target:objectdir()), vcprojdir)) vcprojfile:print("ConfigurationType=\"%d\"", assert(configuration_types[target:kind()])) vcprojfile:print("CharacterSet=\"%d\"", unicode and 1 or 2) -- mbc: 2, wcs: 1 vcprojfile:print("UseOfMFC=\"%d\"", usemfc) vcprojfile:print(">") -- make VCPreBuildEventTool vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCPreBuildEventTool\"") vcprojfile:leave("/>") -- make VCCustomBuildTool vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCCustomBuildTool\"") vcprojfile:leave("/>") -- make VCXMLDataGeneratorTool vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCXMLDataGeneratorTool\"") vcprojfile:leave("/>") -- make VCWebServiceProxyGeneratorTool vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCWebServiceProxyGeneratorTool\"") vcprojfile:leave("/>") -- make VCMIDLTool vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCMIDLTool\"") vcprojfile:leave("/>") -- make VCCLCompilerTool _make_VCCLCompilerTool(vcprojfile, vsinfo, target, compflags) -- make VCManagedResourceCompilerTool vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCManagedResourceCompilerTool\"") vcprojfile:leave("/>") -- make VCResourceCompilerTool vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCResourceCompilerTool\"") vcprojfile:leave("/>") -- make VCPreLinkEventTool vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCPreLinkEventTool\"") vcprojfile:leave("/>") -- make VCLinkerTool _make_VCLinkerTool(vcprojfile, vsinfo, target, vcprojdir) -- make VCALinkTool vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCALinkTool\"") vcprojfile:leave("/>") -- make VCManifestTool vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCManifestTool\"") vcprojfile:leave("/>") -- make VCXDCMakeTool vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCXDCMakeTool\"") vcprojfile:leave("/>") -- make VCBscMakeTool vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCBscMakeTool\"") vcprojfile:leave("/>") -- make VCFxCopTool vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCFxCopTool\"") vcprojfile:leave("/>") -- make VCAppVerifierTool vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCAppVerifierTool\"") vcprojfile:leave("/>") -- make VCPostBuildEventTool vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCPostBuildEventTool\"") vcprojfile:leave("/>") -- leave configuration vcprojfile:leave("</Configuration>") -- leave configurations vcprojfile:leave("</Configurations>") end -- make references function _make_references(vcprojfile, vsinfo, target) vcprojfile:enter("<References>") vcprojfile:leave("</References>") end -- make cxfile -- -- e.g. -- <File -- RelativePath="..\..\..\src\file3.c" -- > -- <FileConfiguration -- Name="Debug|Win32" -- > -- <Tool -- Name="VCCLCompilerTool" -- AdditionalOptions="-Dtest" -- /> -- </FileConfiguration> -- </File> function _make_cxfile(vcprojfile, vsinfo, target, sourcefile, objectfile, vcprojdir) -- get the target key local key = target:cachekey() -- make flags cache _g.flags = _g.flags or {} -- make flags local flags = _g.flags[key] or _make_compflags(sourcefile, target, vcprojdir) _g.flags[key] = flags -- enter file vcprojfile:enter("<File") -- add file path vcprojfile:print("RelativePath=\"%s\"", path.relative(path.absolute(sourcefile), vcprojdir)) vcprojfile:print(">") -- add file configuration vcprojfile:enter("<FileConfiguration") vcprojfile:print("Name=\"$(mode)|Win32\"") vcprojfile:print(">") -- add compiling options vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCCLCompilerTool\"") vcprojfile:print("AdditionalOptions=\"%s\"", flags) vcprojfile:print("ObjectFile=\"%s\"", path.relative(path.absolute(objectfile), vcprojdir)) -- compile as c++ if exists flag: /TP if flags:find("[%-|/]TP") then vcprojfile:print("CompileAs=\"2\"") end vcprojfile:leave("/>") vcprojfile:leave("</FileConfiguration>") -- leave file vcprojfile:leave("</File>") end -- make rcfile -- -- e.g. -- <File -- RelativePath="..\..\..\src\resource.rc" -- > -- <FileConfiguration -- Name="Debug|Win32" -- > -- <Tool -- Name="VCResourceCompilerTool" -- ResourceOutputFileName="..\..\..\build\src\resource.res" -- /> -- </FileConfiguration> -- </File> function _make_rcfile(vcprojfile, vsinfo, target, sourcefile, objectfile, vcprojdir) -- enter file vcprojfile:enter("<File") -- add file path vcprojfile:print("RelativePath=\"%s\"", path.relative(path.absolute(sourcefile), vcprojdir)) vcprojfile:print(">") -- add file configuration vcprojfile:enter("<FileConfiguration") vcprojfile:print("Name=\"$(mode)|Win32\"") vcprojfile:print(">") -- add compiling options vcprojfile:enter("<Tool") vcprojfile:print("Name=\"VCResourceCompilerTool\"") -- FIXME: multi rc files support -- vcprojfile:print("ResourceOutputFileName=\"%s\"", path.relative(path.absolute(objectfile), vcprojdir)) vcprojfile:leave("/>") vcprojfile:leave("</FileConfiguration>") -- leave file vcprojfile:leave("</File>") end -- make files -- -- e.g. -- <Filter -- Name="Source Files" -- > -- <File -- RelativePath="..\..\..\src\file1.c" -- > -- </File> -- <File -- RelativePath="..\..\..\src\file2.c" -- > -- </File> -- <File -- RelativePath="..\..\..\src\file3.c" -- > -- <FileConfiguration -- Name="Debug|Win32" -- > -- <Tool -- Name="VCCLCompilerTool" -- AdditionalOptions="-Dtest" -- /> -- </FileConfiguration> -- </File> -- <File -- RelativePath="..\..\..\src\file4.c" -- > -- </File> -- </Filter> function _make_files(vcprojfile, vsinfo, target, vcprojdir) -- enter files vcprojfile:enter("<Files>") local sourcebatches = target:sourcebatches() -- c/cxx files vcprojfile:enter("<Filter Name=\"Source Files\">") for _, sourcebatch in pairs(sourcebatches) do local sourcekind = sourcebatch.sourcekind if sourcekind ~= "mrc" then local objectfiles = sourcebatch.objectfiles for idx, sourcefile in ipairs(sourcebatch.sourcefiles) do _make_cxfile(vcprojfile, vsinfo, target, sourcefile, objectfiles[idx], vcprojdir) end end end -- leave c/cxx files vcprojfile:leave("</Filter>") -- *.rc files vcprojfile:enter("<Filter Name=\"Resource Files\">") for _, sourcebatch in pairs(sourcebatches) do local sourcekind = sourcebatch.sourcekind if sourcekind == "mrc" then local objectfiles = sourcebatch.objectfiles for idx, sourcefile in ipairs(sourcebatch.sourcefiles) do _make_rcfile(vcprojfile, vsinfo, target, sourcefile, objectfiles[idx], vcprojdir) end end end -- leave *.rc files vcprojfile:leave("</Filter>") vcprojfile:leave("</Files>") end -- make globals function _make_globals(vcprojfile, vsinfo, target) vcprojfile:enter("<Globals>") vcprojfile:leave("</Globals>") end -- make vcproj function make(vsinfo, target) -- the target name local targetname = target:name() -- the vcproj directory local vcprojdir = path.join(vsinfo.solution_dir, targetname) -- open vcproj file local vcprojfile = vsfile.open(path.join(vcprojdir, targetname .. ".vcproj"), "w") -- init indent character vsfile.indentchar('\t') -- make header _make_header(vcprojfile, vsinfo, target) -- make platforms _make_platforms(vcprojfile, vsinfo, target) -- make toolfiles _make_toolfiles(vcprojfile, vsinfo, target) -- make configurations _make_configurations(vcprojfile, vsinfo, target, vcprojdir) -- make references _make_references(vcprojfile, vsinfo, target) -- make files _make_files(vcprojfile, vsinfo, target, vcprojdir) -- make globals _make_globals(vcprojfile, vsinfo, target) -- make tailer _make_tailer(vcprojfile, vsinfo, target) -- exit solution file vcprojfile:close() end
0
repos/xmake/xmake/plugins/project/vstudio
repos/xmake/xmake/plugins/project/vstudio/impl/vs201x.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file vs201x.lua -- -- imports import("core.base.option") import("core.base.colors") import("core.base.hashset") import("core.project.rule") import("core.project.config") import("core.project.project") import("core.platform.platform") import("core.tool.compiler") import("core.tool.linker") import("core.tool.toolchain") import("vs201x_solution") import("vs201x_vcxproj") import("vs201x_vcxproj_filters") import("vsutils") import("core.cache.memcache") import("core.cache.localcache") import("private.action.require.install", {alias = "install_requires"}) import("private.action.run.runenvs") import("actions.config.configfiles", {alias = "generate_configfiles", rootdir = os.programdir()}) import("private.utils.batchcmds") import("private.utils.rule_groups") import("plugins.project.utils.target_cmds", {rootdir = os.programdir()}) function _translate_path(dir, vcxprojdir) if dir == nil then return "" end if type(dir) == "string" then dir = path.translate(dir) if dir == "" then return "" end if path.is_absolute(dir) then if dir:startswith(project.directory()) then return vsutils.escape(path.relative(dir, vcxprojdir)) end return vsutils.escape(dir) else return vsutils.escape(path.relative(path.absolute(dir), vcxprojdir)) end end local r = {} for k, v in ipairs(dir) do r[k] = _translate_path(v, vcxprojdir) end r = table.unique(r) return path.joinenv(r) end -- clear cache function _clear_cache() localcache.clear("detect") localcache.clear("option") localcache.clear("package") localcache.clear("toolchain") -- force recheck localcache.set("config", "recheck", true) localcache.save() end -- get c++ modules rules function _get_cxxmodules_rules() return {"c++.build.modules", "c++.build.modules.builder"} end -- get command string function _get_command_string(cmd, vcxprojdir) local kind = cmd.kind local opt = cmd.opt if cmd.program then local argv = {} for _, v in ipairs(table.join(cmd.program, cmd.argv)) do if path.instance_of(v) then v = v:clone():set(_translate_path(v:rawstr(), vcxprojdir)):str() elseif path.is_absolute(v) then v = _translate_path(v, vcxprojdir) end table.insert(argv, v) end local command = os.args(argv) if opt and opt.curdir then command = string.format("pushd \"%s\"\n%s\npopd", _translate_path(opt.curdir, vcxprojdir), command) end return command elseif kind == "cp" then return string.format("copy /Y \"%s\" \"%s\"", _translate_path(cmd.srcpath, vcxprojdir), _translate_path(cmd.dstpath, vcxprojdir)) elseif kind == "rm" then return string.format("del /F /Q \"%s\" || rmdir /S /Q \"%s\"", _translate_path(cmd.filepath, vcxprojdir), _translate_path(cmd.filepath, vcxprojdir)) elseif kind == "rmdir" then return string.format("rmdir /S /Q \"%s\"", _translate_path(cmd.filepath, vcxprojdir)) elseif kind == "mv" then return string.format("rename \"%s\" \"%s\"", _translate_path(cmd.srcpath, vcxprojdir), _translate_path(cmd.dstpath, vcxprojdir)) elseif kind == "cd" then return string.format("cd \"%s\"", _translate_path(cmd.dir, vcxprojdir)) elseif kind == "mkdir" then local dir = _translate_path(cmd.dir, vcxprojdir) return string.format("if not exist \"%s\" mkdir \"%s\"", dir, dir) elseif kind == "show" then return string.format("echo %s", colors.ignore(cmd.showtext)) end end -- make custom commands function _make_custom_commands(target, vcxprojdir) -- https://github.com/xmake-io/xmake/issues/2337 target:data_set("plugin.project.kind", "vs") -- https://github.com/xmake-io/xmake/issues/2258 target:data_set("plugin.project.translate_path", function (p) return _translate_path(p, vcxprojdir) end) -- build sourcebatch groups first local sourcegroups = rule_groups.build_sourcebatch_groups(target, target:sourcebatches()) -- ignore c++ modules rules local ignored_rules = _get_cxxmodules_rules() -- add before commands -- we use irpairs(groups), because the last group that should be given the highest priority. local cmds_before = {} target_cmds.get_target_buildcmd(target, cmds_before, {suffix = "before", ignored_rules = ignored_rules}) target_cmds.get_target_buildcmd_sourcegroups(target, cmds_before, sourcegroups, {suffix = "before", ignored_rules = ignored_rules}) -- rule.on_buildcmd_files should also be executed before building the target, as cmake PRE_BUILD does not work. target_cmds.get_target_buildcmd_sourcegroups(target, cmds_before, sourcegroups, {ignored_rules = ignored_rules}) -- add after commands local cmds_after = {} target_cmds.get_target_buildcmd_sourcegroups(target, cmds_after, sourcegroups, {suffix = "after", ignored_rules = ignored_rules}) target_cmds.get_target_buildcmd(target, cmds_after, {suffix = "after", ignored_rules = ignored_rules}) local commands = {} for _, cmd in ipairs(cmds_before) do commands.before = commands.before or {} table.insert(commands.before, _get_command_string(cmd, vcxprojdir)) end for _, cmd in ipairs(cmds_after) do commands.after = commands.after or {} table.insert(commands.after, _get_command_string(cmd, vcxprojdir)) end return commands end -- make target info function _make_targetinfo(mode, arch, target, vcxprojdir) -- init target info local targetinfo = { mode = mode, arch = vsutils.vsarch(arch) } -- get sdk version local msvc = toolchain.load("msvc") if msvc then local vcvars = msvc:config("vcvars") if vcvars then targetinfo.sdkver = vcvars.WindowsSDKVersion end end -- save c/c++ precompiled output file (.pch) targetinfo.pcoutputfile = target:pcoutputfile("c") targetinfo.pcxxoutputfile = target:pcoutputfile("cxx") target:set("pcheader", nil) target:set("pcxxheader", nil) -- save languages targetinfo.languages = table.wrap(target:get("languages")) -- save symbols targetinfo.symbols = target:get("symbols") -- has modules targetinfo.has_modules = target:data("cxx.has_modules") -- save target kind targetinfo.targetkind = target:kind() if target:is_phony() or target:is_headeronly() then return targetinfo end -- save target file targetinfo.targetfile = target:targetfile() -- save symbol file targetinfo.symbolfile = target:symbolfile() -- save sourcekinds targetinfo.sourcekinds = target:sourcekinds() -- save target dir targetinfo.targetdir = target:targetdir() -- save object dir targetinfo.objectdir = target:objectdir() -- save compiler flags and cmds local firstcompflags = nil targetinfo.compflags = {} targetinfo.compargvs = {} local sourcebatches = target:sourcebatches() for _, sourcebatch in table.orderpairs(sourcebatches) do local sourcekind = sourcebatch.sourcekind local rulename = sourcebatch.rulename if sourcekind then for _, sourcefile in ipairs(sourcebatch.sourcefiles) do local compflags = compiler.compflags(sourcefile, {target = target, sourcekind = sourcekind}) if not firstcompflags and (rulename == "c.build" or rulename == "c++.build" or rulename == "c++.build.modules" or rulename == "cuda.build") then firstcompflags = compflags end targetinfo.compflags[sourcefile] = compflags targetinfo.compargvs[sourcefile] = table.join(compiler.compargv("__sourcefile__", "__objectfile__", {sourcekind = sourcekind, target = target})) -- detect manifest -- @see https://github.com/xmake-io/xmake/issues/2176 if sourcekind == "mrc" and os.isfile(sourcefile) then local resoucedata = io.readfile(sourcefile) if resoucedata and resoucedata:find("RT_MANIFEST") then targetinfo.manifest_embed = false end end end end end -- save sourcebatches targetinfo.sourcebatches = target:sourcebatches() -- save linker flags local linkflags = linker.linkflags(target:is_moduleonly() and 'static' or target:kind(), target:sourcekinds(), {target = target}) targetinfo.linkflags = linkflags if table.contains(target:sourcekinds(), "cu") then -- save cuda linker flags local linkinst = linker.load("gpucode", "cu", {target = target}) targetinfo.culinkflags = linkinst:linkflags({target = target}) -- save cuda devlink status targetinfo.cudevlink = target:policy("build.cuda.devlink") or target:values("cuda.build.devlink") end -- save execution dir (when executed from VS) targetinfo.rundir = target:is_moduleonly() and "" or target:rundir() -- save runenvs local targetrunenvs = {} local addrunenvs, setrunenvs = runenvs.make(target) for k, v in table.orderpairs(target:pkgenvs()) do addrunenvs = addrunenvs or {} addrunenvs[k] = table.join(table.wrap(addrunenvs[k]), path.splitenv(v)) end for _, dep in ipairs(target:orderdeps()) do for k, v in table.orderpairs(dep:pkgenvs()) do addrunenvs = addrunenvs or {} addrunenvs[k] = table.join(table.wrap(addrunenvs[k]), path.splitenv(v)) end end for k, v in table.orderpairs(addrunenvs) do if k:upper() == "PATH" then targetrunenvs[k] = _translate_path(v, vcxprojdir) .. ";$([System.Environment]::GetEnvironmentVariable('" .. k .. "'))" else targetrunenvs[k] = path.joinenv(v) .. ";$([System.Environment]::GetEnvironmentVariable('" .. k .."'))" end end for k, v in table.orderpairs(setrunenvs) do if #v == 1 then v = v[1] if path.is_absolute(v) and v:startswith(project.directory()) then targetrunenvs[k] = _translate_path(v, vcxprojdir) else targetrunenvs[k] = v[1] end else targetrunenvs[k] = path.joinenv(v) end end local runenvstr = {} for k, v in table.orderpairs(targetrunenvs) do table.insert(runenvstr, k .. "=" .. v) end targetinfo.runenvs = table.concat(runenvstr, "\n") -- use mfc? save the mfc runtime kind if target:rule("win.sdk.mfc.shared_app") or target:rule("win.sdk.mfc.shared") then targetinfo.usemfc = "Dynamic" elseif target:rule("win.sdk.mfc.static_app") or target:rule("win.sdk.mfc.static") then targetinfo.usemfc = "Static" end -- set unicode for _, flag in ipairs(firstcompflags) do if flag:find("[%-|/]DUNICODE") then targetinfo.unicode = true break end end -- save custom commands targetinfo.commands = _make_custom_commands(target, vcxprojdir) return targetinfo end function _make_vsinfo_modes() local vsinfo_modes = {} local modes = option.get("modes") if modes then if not modes:find("\"") then modes = modes:gsub(",", path.envsep()) end for _, mode in ipairs(path.splitenv(modes)) do table.insert(vsinfo_modes, mode:trim()) end else vsinfo_modes = project.modes() end if not vsinfo_modes or #vsinfo_modes == 0 then vsinfo_modes = { config.mode() } end return vsinfo_modes end function _make_vsinfo_archs() local vsinfo_archs = {} local archs = option.get("archs") if archs then if not archs:find("\"") then archs = archs:gsub(",", path.envsep()) end for _, arch in ipairs(path.splitenv(archs)) do table.insert(vsinfo_archs, arch:trim()) end else -- we use it first if global set_arch("xx") is setted in xmake.lua vsinfo_archs = project.get("target.arch") if not vsinfo_archs then -- for set_allowedarchs() local allowed_archs = project.allowed_archs(config.plat()) if allowed_archs then vsinfo_archs = allowed_archs:to_array() end end if not vsinfo_archs then local default_archs = toolchain.load("msvc"):config("vcarchs") if not default_archs then default_archs = platform.archs() end if default_archs then default_archs = hashset.from(table.wrap(default_archs)) -- just generate single arch by default to avoid some fails for installing packages. -- @see https://github.com/xmake-io/xmake/issues/3268 local arch = config.arch() if default_archs:has(arch) then vsinfo_archs = { arch } else default_archs:remove("arm64") vsinfo_archs = default_archs:to_array() end end end end if not vsinfo_archs or #vsinfo_archs == 0 then vsinfo_archs = { config.arch() } end return vsinfo_archs end -- make vstudio project function make(outputdir, vsinfo) -- enter project directory local oldir = os.cd(project.directory()) -- init solution directory vsinfo.solution_dir = path.join(outputdir, "vs" .. vsinfo.vstudio_version) -- init modes vsinfo.modes = _make_vsinfo_modes() -- init archs vsinfo.archs = _make_vsinfo_archs() -- load targets local targets = {} for mode_idx, mode in ipairs(vsinfo.modes) do for arch_idx, arch in ipairs(vsinfo.archs) do -- trace print("checking for %s.%s ...", mode, arch) -- reload config, project and platform if mode ~= config.mode() or arch ~= config.arch() then -- modify config config.set("as", nil, {force = true}) -- force to re-check as for ml/ml64 config.set("mode", mode, {readonly = true, force = true}) config.set("arch", arch, {readonly = true, force = true}) -- clear all options for _, opt in ipairs(project.options()) do opt:clear() end -- clear cache memcache.clear() localcache.clear("detect") localcache.clear("option") localcache.clear("package") localcache.clear("toolchain") localcache.clear("cxxmodules") -- check platform platform.load(config.plat(), arch):check() -- check project options project.check_options() -- install and update requires install_requires() -- load targets project.load_targets() -- update config files generate_configfiles() end -- ensure to enter project directory os.cd(project.directory()) -- save targets for targetname, target in table.orderpairs(project.targets()) do -- make target with the given mode and arch targets[targetname] = targets[targetname] or {} local _target = targets[targetname] -- the vcxproj directory _target.project_dir = path.join(vsinfo.solution_dir, targetname) -- save c/c++ precompiled header _target.pcheader = target:pcheaderfile("c") -- header.h _target.pcxxheader = target:pcheaderfile("cxx") -- header.[hpp|inl] -- init target info _target.name = targetname _target.kind = target:kind() _target.scriptdir = target:scriptdir() _target.info = _target.info or {} table.insert(_target.info, _make_targetinfo(mode, arch, target, _target.project_dir)) -- save all sourcefiles and headerfiles _target.sourcefiles = table.unique(table.join(_target.sourcefiles or {}, (target:sourcefiles()))) _target.headerfiles = table.unique(table.join(_target.headerfiles or {}, (target:headerfiles()))) _target.extrafiles = table.unique(table.join(_target.extrafiles or {}, (target:extrafiles()))) -- sort them to stabilize generation table.sort(_target.sourcefiles) table.sort(_target.headerfiles) table.sort(_target.extrafiles) -- save file groups _target.filegroups = table.unique(table.join(_target.filegroups or {}, target:get("filegroups"))) -- save references to deps for _, dep in ipairs(target:orderdeps()) do _target.deps = _target.deps or {} local dep_name = dep:name() _target.deps[dep_name] = path.relative(path.join(vsinfo.solution_dir, dep_name, dep_name .. ".vcxproj"), _target.project_dir) end for filegroup, groupconf in pairs(target:extraconf("filegroups")) do _target.filegroups_extraconf = _target.filegroups_extraconf or {} local mergedconf = _target.filegroups_extraconf[filegroup] if not mergedconf then mergedconf = {} _target.filegroups_extraconf[filegroup] = mergedconf end if groupconf.rootdir then mergedconf.rootdir = table.unique(table.join(mergedconf.rootdir or {}, table.wrap(groupconf.rootdir))) end if groupconf.files then mergedconf.files = table.unique(table.join(mergedconf.files or {}, table.wrap(groupconf.files))) end mergedconf.plain = groupconf.plain or mergedconf.plain end end end end -- make solution vs201x_solution.make(vsinfo) -- make .vcxproj for _, target in table.orderpairs(targets) do vs201x_vcxproj.make(vsinfo, target) vs201x_vcxproj_filters.make(vsinfo, target) end -- clear local cache _clear_cache() -- leave project directory os.cd(oldir) end
0
repos/xmake/xmake/plugins/project/vstudio
repos/xmake/xmake/plugins/project/vstudio/impl/vs201x_vcxproj.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file vs201x_vcxproj.lua -- -- imports import("core.base.hashset") import("core.project.rule") import("core.project.config") import("core.project.project") import("core.language.language") import("core.tool.toolchain") import("private.utils.batchcmds") import("detect.sdks.find_cuda") import("vsfile") import("vsutils") import("private.utils.toolchain", {alias = "toolchain_utils"}) function _make_dirs(dir, vcxprojdir) dir = dir:trim() if #dir == 0 then return "" end dir = path.translate(dir) if not path.is_absolute(dir) then dir = path.relative(path.absolute(dir), vcxprojdir) end return dir end -- check for CUDA function _check_cuda(target) local cuda for _, targetinfo in ipairs(target.info) do if targetinfo.sourcekinds and table.contains(targetinfo.sourcekinds, "cu") then cuda = find_cuda() break end end if cuda then if cuda.msbuildextensionsdir and cuda.version and os.isfile(path.join(cuda.msbuildextensionsdir, format("CUDA %s.props", cuda.version))) then return cuda else os.raise("The Visual Studio Integration for CUDA %s is not found. Please check your CUDA installation.", cuda.version) end end end -- get toolset version function _get_toolset_ver(targetinfo, vsinfo) -- get toolset version from vs version local vs_toolset = toolchain.load("msvc"):config("vs_toolset") or config.get("vs_toolset") local toolset_ver = toolchain_utils.get_vs_toolset_ver(vs_toolset) if not toolset_ver then toolset_ver = vsinfo.toolset_version end return toolset_ver end -- get platform sdk version from vcvars.WindowsSDKVersion function _get_platform_sdkver(target, vsinfo) local sdkver = nil for _, targetinfo in ipairs(target.info) do sdkver = targetinfo.sdkver if sdkver then break end end return sdkver or vsinfo.sdk_version end -- combine two successive flags function _combine_flags(flags, patterns) local newflags = {} local temparg for _, arg in ipairs(flags) do if temparg then table.insert(newflags, temparg .. " " .. arg) temparg = nil else for _, pattern in ipairs(patterns) do if arg:match(pattern) then temparg = arg end end if not temparg then table.insert(newflags, arg) end end end return newflags end -- exclude patterns from flags function _exclude_flags(flags, excludes) local newflags = {} for _, flag in ipairs(flags) do local excluded = false for _, exclude in ipairs(excludes) do if flag:find("^[%-/]" .. exclude) then excluded = true break end end if not excluded then table.insert(newflags, vsutils.escape(flag)) end end return newflags end -- try split from nvcc -code flag -- e.g. nvcc -arch=compute_86 -code=\"sm_86,compute_86\" -- nvcc -gencode arch=compute_86,code=[sm_86,compute_86] function _split_gpucodes(flag) flag = flag:gsub("[%[\"]?(.-)[%]\"]?", "%1") return flag:split(",") end -- is module file? function _is_modulefile(sourcefile) local extension = path.extension(sourcefile) return extension == ".mpp" or extension == ".mxx" or extension == ".cppm" or extension == ".ixx" end -- make compiling command function _make_compcmd(compargv, sourcefile, objectfile, vcxprojdir) local argv = {} for i, v in ipairs(compargv) do if i == 1 then v = path.filename(v) -- C:\xxx\ml.exe -> ml.exe end v = v:gsub("__sourcefile__", sourcefile) v = v:gsub("__objectfile__", objectfile) -- -Idir or /Idir -- handle external includes as well for _, pattern in ipairs({"[%-/](I)(.*)", "[%-/](external:I)(.*)"}) do v = v:gsub(pattern, function (flag, dir) dir = _make_dirs(dir, vcxprojdir) return "/" .. flag .. dir end) end table.insert(argv, v) end return table.concat(argv, " ") end -- make compiling flags function _make_compflags(sourcefile, targetinfo, vcxprojdir) -- translate path for -Idir or /Idir local flags = {} for _, flag in ipairs(targetinfo.compflags[sourcefile]) do for _, pattern in ipairs({"[%-/](I)(.*)", "[%-/](external:I)(.*)"}) do -- -Idir or /Idir flag = flag:gsub(pattern, function (flag, dir) dir = _make_dirs(dir, vcxprojdir) return "/" .. flag .. dir end) end table.insert(flags, flag) end -- add -D__config_$(mode)__ and -D__config_$(arch)__ for the config header table.insert(flags, "-D__config_" .. targetinfo.mode .. "__") table.insert(flags, "-D__config_" .. targetinfo.arch .. "__") return flags end -- make linking flags function _make_linkflags(targetinfo, vcxprojdir) -- replace -libpath:dir or /libpath:dir local flags = {} for _, flag in ipairs(targetinfo.linkflags) do -- replace -libpath:dir or /libpath:dir flag = flag:gsub(string.ipattern("[%-/]libpath:(.*)"), function (dir) dir = _make_dirs(dir, vcxprojdir) return "/libpath:" .. dir end) -- replace -def:dir or /def:dir flag = flag:gsub(string.ipattern("[%-/]def:(.*)"), function (dir) dir = _make_dirs(dir, vcxprojdir) return "/def:" .. dir end) -- save flag table.insert(flags, flag) end -- ok? return flags end -- make header function _make_header(vcxprojfile, vsinfo) vcxprojfile:print("<?xml version=\"1.0\" encoding=\"utf-8\"?>") vcxprojfile:enter("<Project DefaultTargets=\"Build\" ToolsVersion=\"%s.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">", assert(vsinfo.project_version)) end -- make references function _make_references(vcxprojfile, vsinfo, target) vcxprojfile:print("<ItemGroup>") for dep_name, dep_vcxprojfile in pairs(target.deps) do vcxprojfile:print("<ProjectReference Include=\"%s\">", dep_vcxprojfile) vcxprojfile:print("<Project>{%s}</Project>", hash.uuid4(dep_name)) vcxprojfile:print("</ProjectReference>") end vcxprojfile:print("</ItemGroup>") end -- make tailer function _make_tailer(vcxprojfile, vsinfo, target) vcxprojfile:print("<Import Project=\"%$(VCTargetsPath)\\Microsoft.Cpp.targets\" />") vcxprojfile:enter("<ImportGroup Label=\"ExtensionTargets\">") local cuda = _check_cuda(target) if cuda then vcxprojfile:print("<Import Project=\"%s\" />", path.join(cuda.msbuildextensionsdir, format("CUDA %s.targets", cuda.version))) end vcxprojfile:leave("</ImportGroup>") vcxprojfile:leave("</Project>") end -- make Configurations function _make_configurations(vcxprojfile, vsinfo, target) -- the target name local targetname = target.name -- init configuration type local configuration_types = { binary = "Application" , shared = "DynamicLibrary" , static = "StaticLibrary" , moduleonly = "StaticLibrary" -- emulate moduleonly with staticlib } -- make ProjectConfigurations vcxprojfile:enter("<ItemGroup Label=\"ProjectConfigurations\">") for _, targetinfo in ipairs(target.info) do vcxprojfile:enter("<ProjectConfiguration Include=\"%s|%s\">", targetinfo.mode, targetinfo.arch) vcxprojfile:print("<Configuration>%s</Configuration>", targetinfo.mode) vcxprojfile:print("<Platform>%s</Platform>", targetinfo.arch) vcxprojfile:leave("</ProjectConfiguration>") end vcxprojfile:leave("</ItemGroup>") -- make Globals vcxprojfile:enter("<PropertyGroup Label=\"Globals\">") vcxprojfile:print("<ProjectGuid>{%s}</ProjectGuid>", hash.uuid4(targetname)) vcxprojfile:print("<RootNamespace>%s</RootNamespace>", targetname) if vsinfo.vstudio_version >= "2015" then vcxprojfile:print("<WindowsTargetPlatformVersion>%s</WindowsTargetPlatformVersion>", _get_platform_sdkver(target, vsinfo)) end vcxprojfile:leave("</PropertyGroup>") -- import Microsoft.Cpp.Default.props vcxprojfile:print("<Import Project=\"%$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />") -- make Configuration for _, targetinfo in ipairs(target.info) do vcxprojfile:enter("<PropertyGroup Condition=\"\'%$(Configuration)|%$(Platform)\'==\'%s|%s\'\" Label=\"Configuration\">", targetinfo.mode, targetinfo.arch) vcxprojfile:print("<ConfigurationType>%s</ConfigurationType>", configuration_types[target.kind] or "Unknown") vcxprojfile:print("<PlatformToolset>%s</PlatformToolset>", _get_toolset_ver(targetinfo, vsinfo)) vcxprojfile:print("<CharacterSet>%s</CharacterSet>", targetinfo.unicode and "Unicode" or "MultiByte") if targetinfo.usemfc then vcxprojfile:print("<UseOfMfc>%s</UseOfMfc>", targetinfo.usemfc) end vcxprojfile:leave("</PropertyGroup>") end -- import Microsoft.Cpp.props vcxprojfile:print("<Import Project=\"%$(VCTargetsPath)\\Microsoft.Cpp.props\" />") -- make ExtensionSettings vcxprojfile:enter("<ImportGroup Label=\"ExtensionSettings\">") local cuda = _check_cuda(target) if cuda then vcxprojfile:print("<Import Project=\"%s\" />", path.join(cuda.msbuildextensionsdir, format("CUDA %s.props", cuda.version))) end vcxprojfile:leave("</ImportGroup>") -- make PropertySheets for _, targetinfo in ipairs(target.info) do vcxprojfile:enter("<ImportGroup Condition=\"\'%$(Configuration)|%$(Platform)\'==\'%s|%s\'\" Label=\"PropertySheets\">", targetinfo.mode, targetinfo.arch) vcxprojfile:print("<Import Project=\"%$(UserRootDir)\\Microsoft.Cpp.%$(Platform).user.props\" Condition=\"exists(\'%$(UserRootDir)\\Microsoft.Cpp.%$(Platform).user.props\')\" Label=\"LocalAppDataPlatform\" />") vcxprojfile:leave("</ImportGroup>") end -- make UserMacros vcxprojfile:print("<PropertyGroup Label=\"UserMacros\" />") if not configuration_types[target.kind] then return end -- make OutputDirectory and IntermediateDirectory for _, targetinfo in ipairs(target.info) do vcxprojfile:enter("<PropertyGroup Condition=\"\'%$(Configuration)|%$(Platform)\'==\'%s|%s\'\">", targetinfo.mode, targetinfo.arch) vcxprojfile:print("<OutDir>%s\\</OutDir>", _make_dirs(targetinfo.targetdir, target.project_dir)) vcxprojfile:print("<IntDir>%s\\</IntDir>", _make_dirs(targetinfo.objectdir, target.project_dir)) if targetinfo.targetfile then vcxprojfile:print("<TargetName>%s</TargetName>", path.basename(targetinfo.targetfile)) vcxprojfile:print("<TargetExt>%s</TargetExt>", path.extension(targetinfo.targetfile)) end if target.kind == "binary" then vcxprojfile:print("<LinkIncremental>true</LinkIncremental>") end if targetinfo.manifest_embed ~= nil then vcxprojfile:print("<EmbedManifest>%s</EmbedManifest>", targetinfo.manifest_embed) end -- handle ExternalIncludePath (should we handle IncludePath here too?) local externaldirs = {} for _, flag in ipairs(targetinfo.commonflags.cl) do flag:gsub("[%-/]external:I(.*)", function (dir) table.insert(externaldirs, dir) end) end if #externaldirs > 0 then vcxprojfile:print("<ExternalIncludePath>%s;$(VC_IncludePath);$(WindowsSDK_IncludePath);</ExternalIncludePath>", table.concat(externaldirs, ";")) end vcxprojfile:leave("</PropertyGroup>") end -- make Debugger for _, targetinfo in ipairs(target.info) do vcxprojfile:enter("<PropertyGroup Condition=\"\'%$(Configuration)|%$(Platform)\'==\'%s|%s\'\" Label=\"Debugger\">", targetinfo.mode, targetinfo.arch) vcxprojfile:print("<LocalDebuggerWorkingDirectory>%s</LocalDebuggerWorkingDirectory>", _make_dirs(targetinfo.rundir, target.project_dir)) -- @note we use writef to avoid escape $() in runenvs, e.g. $([System.Environment]::Get ..) vcxprojfile:writef("<LocalDebuggerEnvironment>%s;%%(LocalDebuggerEnvironment)</LocalDebuggerEnvironment>\n", targetinfo.runenvs) vcxprojfile:leave("</PropertyGroup>") end end -- make source options for cl function _make_source_options_cl(vcxprojfile, flags, condition) -- exists condition? condition = condition or "" -- get flags string local flagstr = os.args(flags) -- make Optimization if flagstr:find("[%-/]Os") or flagstr:find("[%-/]O1") then vcxprojfile:print("<Optimization%s>MinSpace</Optimization>", condition) elseif flagstr:find("[%-/]O2") or flagstr:find("[%-/]Ot") then vcxprojfile:print("<Optimization%s>MaxSpeed</Optimization>", condition) elseif flagstr:find("[%-/]Ox") then vcxprojfile:print("<Optimization%s>Full</Optimization>", condition) else vcxprojfile:print("<Optimization%s>Disabled</Optimization>", condition) end -- make FloatingPointModel if flagstr:find("[%-/]fp:fast") then vcxprojfile:print("<FloatingPointModel%s>Fast</FloatingPointModel>", condition) elseif flagstr:find("[%-/]fp:strict") then vcxprojfile:print("<FloatingPointModel%s>Strict</FloatingPointModel>", condition) elseif flagstr:find("[%-/]fp:precise") then vcxprojfile:print("<FloatingPointModel%s>Precise</FloatingPointModel>", condition) end -- make WarningLevel if flagstr:find("[%-/]W1") then vcxprojfile:print("<WarningLevel%s>Level1</WarningLevel>", condition) elseif flagstr:find("[%-/]W2") then vcxprojfile:print("<WarningLevel%s>Level2</WarningLevel>", condition) elseif flagstr:find("[%-/]W3") then vcxprojfile:print("<WarningLevel%s>Level3</WarningLevel>", condition) elseif flagstr:find("[%-/]W4") then vcxprojfile:print("<WarningLevel%s>Level4</WarningLevel>", condition) elseif flagstr:find("[%-/]Wall") then vcxprojfile:print("<WarningLevel%s>EnableAllWarnings</WarningLevel>", condition) else vcxprojfile:print("<WarningLevel%s>TurnOffAllWarnings</WarningLevel>", condition) end if flagstr:find("[%-/]WX") then vcxprojfile:print("<TreatWarningAsError%s>true</TreatWarningAsError>", condition) end -- make ExternalWarningLevel if flagstr:find("[%-/]external:W1") then vcxprojfile:print("<ExternalWarningLevel%s>Level1</ExternalWarningLevel>", condition) elseif flagstr:find("[%-/]external:W2") then vcxprojfile:print("<ExternalWarningLevel%s>Level2</ExternalWarningLevel>", condition) elseif flagstr:find("[%-/]external:W3") then vcxprojfile:print("<ExternalWarningLevel%s>Level3</ExternalWarningLevel>", condition) elseif flagstr:find("[%-/]external:W4") then vcxprojfile:print("<ExternalWarningLevel%s>Level4</ExternalWarningLevel>", condition) else vcxprojfile:print("<ExternalWarningLevel%s>TurnOffAllWarnings</ExternalWarningLevel>", condition) end -- make ExternalTemplatesDiagnostics if flagstr:find("[%-/]external:templates%-") then vcxprojfile:print("<ExternalTemplatesDiagnostics%s>true</ExternalTemplatesDiagnostics>", condition) else vcxprojfile:print("<ExternalTemplatesDiagnostics%s>false</ExternalTemplatesDiagnostics>", condition) end -- make DisableSpecificWarnings local disabledwarnings = {} for _, flag in ipairs(flags) do flag:gsub("[%-/]wd(%d+)", function (warn) table.insert(disabledwarnings, warn) end) end if #disabledwarnings > 0 then vcxprojfile:print("<DisableSpecificWarnings>%s;%%(DisableSpecificWarnings)</DisableSpecificWarnings>", table.concat(disabledwarnings, ";")) end -- make PreprocessorDefinitions local defstr = "" for _, flag in ipairs(flags) do flag:gsub("^[%-/]D(.*)", function (def) defstr = defstr .. vsutils.escape(def) .. ";" end ) end defstr = defstr .. "%%(PreprocessorDefinitions)" vcxprojfile:print("<PreprocessorDefinitions%s>%s</PreprocessorDefinitions>", condition, defstr) -- make DebugInformationFormat if flagstr:find("[%-/]Zi") then vcxprojfile:print("<DebugInformationFormat%s>ProgramDatabase</DebugInformationFormat>", condition) elseif flagstr:find("[%-/]ZI") then vcxprojfile:print("<DebugInformationFormat%s>EditAndContinue</DebugInformationFormat>", condition) elseif flagstr:find("[%-/]Z7") then vcxprojfile:print("<DebugInformationFormat%s>OldStyle</DebugInformationFormat>", condition) else vcxprojfile:print("<DebugInformationFormat%s>None</DebugInformationFormat>", condition) end -- make RuntimeLibrary if flagstr:find("[%-/]MDd") then vcxprojfile:print("<RuntimeLibrary%s>MultiThreadedDebugDLL</RuntimeLibrary>", condition) elseif flagstr:find("[%-/]MD") then vcxprojfile:print("<RuntimeLibrary%s>MultiThreadedDLL</RuntimeLibrary>", condition) elseif flagstr:find("[%-/]MTd") then vcxprojfile:print("<RuntimeLibrary%s>MultiThreadedDebug</RuntimeLibrary>", condition) else vcxprojfile:print("<RuntimeLibrary%s>MultiThreaded</RuntimeLibrary>", condition) end -- make RuntimeTypeInfo if flagstr:find("[%-/]GR%-") then vcxprojfile:print("<RuntimeTypeInfo%s>false</RuntimeTypeInfo>", condition) elseif flagstr:find("[%-/]GR") then vcxprojfile:print("<RuntimeTypeInfo%s>true</RuntimeTypeInfo>", condition) end -- handle multi processor compilation if flagstr:find("[%-/]Gm%-") or not flagstr:find("[%-/]Gm") then vcxprojfile:print("<MinimalRebuild%s>false</MinimalRebuild>", condition) if not flagstr:find("[%-/]MP1") then vcxprojfile:print("<MultiProcessorCompilation%s>true</MultiProcessorCompilation>", condition) end end -- make AdditionalIncludeDirectories if flagstr:find("[%-/]I") then local dirs = {} for _, flag in ipairs(flags) do flag:gsub("^[%-/]I(.*)", function (dir) table.insert(dirs, vsutils.escape(dir)) end) end if #dirs > 0 then vcxprojfile:print("<AdditionalIncludeDirectories%s>%s</AdditionalIncludeDirectories>", condition, table.concat(dirs, ";")) end end -- compile as c++ if exists flag: /TP if flagstr:find("[%-/]TP") then vcxprojfile:print("<CompileAs%s>CompileAsCpp</CompileAs>", condition) end -- make SDLCheck flag: /sdl if flagstr:find("[%-/]sdl") then if flagstr:find("[%-/]sdl%-") then vcxprojfile:print("<SDLCheck%s>false</SDLCheck>", condition) else vcxprojfile:print("<SDLCheck%s>true</SDLCheck>", condition) end end -- make RemoveUnreferencedCodeData flag: Zc:inline if flagstr:find("[%-/]Zc:inline") then if flagstr:find("[%-/]Zc:inline%-") then vcxprojfile:print("<RemoveUnreferencedCodeData%s>false</RemoveUnreferencedCodeData>", condition) else vcxprojfile:print("<RemoveUnreferencedCodeData%s>true</RemoveUnreferencedCodeData>", condition) end end -- make ExceptionHandling flag: if flagstr:find("[%-/]EH[asc]+%-?") then local args = flagstr:match("[%-/]EH([asc]+%-?)") -- remove the last arg if flag endwith `-` if args and args:endswith("-") then args = args:sub(1, -2) end if args and args:find("a", 1, true) then -- a will overwrite s and c vcxprojfile:print("<ExceptionHandling%s>Async</ExceptionHandling>", condition) elseif args == "sc" or args == "cs" then vcxprojfile:print("<ExceptionHandling%s>Sync</ExceptionHandling>", condition) elseif args == "s" then vcxprojfile:print("<ExceptionHandling%s>SyncCThrow</ExceptionHandling>", condition) else -- if args == "c" -- c is ignored without s or a, do nothing here end end -- make AdditionalOptions local excludes = { "Od", "Os", "O0", "O1", "O2", "Ot", "Ox", "W0", "W1", "W2", "W3", "W4", "WX", "Wall", "Zi", "ZI", "Z7", "MT", "MTd", "MD", "MDd", "TP", "Fd", "fp", "I", "D", "Gm%-", "Gm", "GR%-", "GR", "MP", "external:W0", "external:W1", "external:W2", "external:W3", "external:W4", "external:templates%-?", "external:I", "std:c11", "std:c17", "std:c%+%+11", "std:c%+%+14", "std:c%+%+17", "std:c%+%+20", "std:c%+%+latest", "nologo", "wd(%d+)", "sdl%-?", "Zc:inline%-?", "EH[asc]+%-?" } local additional_flags = _exclude_flags(flags, excludes) if #additional_flags > 0 then vcxprojfile:print("<AdditionalOptions%s>%s %%(AdditionalOptions)</AdditionalOptions>", condition, os.args(additional_flags)) end end -- make source options for cl function _make_resource_options_cl(vcxprojfile, flags) -- get flags string local flagstr = os.args(flags) -- make PreprocessorDefinitions local defstr = "" for _, flag in ipairs(flags) do flag:gsub("^[%-/]D(.*)", function (def) defstr = defstr .. vsutils.escape(def) .. ";" end ) end defstr = defstr .. "%%(PreprocessorDefinitions)" vcxprojfile:print("<PreprocessorDefinitions>%s</PreprocessorDefinitions>", defstr) -- make AdditionalIncludeDirectories if flagstr:find("[%-/]I") then local dirs = {} for _, flag in ipairs(flags) do flag:gsub("^[%-/]I(.*)", function (dir) table.insert(dirs, vsutils.escape(dir)) end) end if #dirs > 0 then vcxprojfile:print("<AdditionalIncludeDirectories>%s</AdditionalIncludeDirectories>", table.concat(dirs, ";")) end end end -- make source options for cuda function _make_source_options_cuda(vcxprojfile, flags, opt) -- exists condition? condition = (opt and opt.condition) or "" -- combine successive commands flags = _combine_flags(flags, {"^%-gencode$", "^%-arch$", "^%-code$", "^%-%-machine$", "^%-rdc$", "^%-cudart$", "^%-%-keep%-dir$"}) -- get flags string local flagstr = os.args(flags) if not (opt and opt.link) then -- make Optimization if flagstr:find("[%-/]Od") then vcxprojfile:print("<Optimization%s>Od</Optimization>", condition) elseif flagstr:find("[%-/]O1") then vcxprojfile:print("<Optimization%s>O1</Optimization>", condition) elseif flagstr:find("[%-/]O2") then vcxprojfile:print("<Optimization%s>O2</Optimization>", condition) elseif flagstr:find("[%-/]O3") or flagstr:find("[%-/]Ox") then vcxprojfile:print("<Optimization%s>O3</Optimization>", condition) end -- make Warning if flagstr:find("[%-/]W[1234]") then local wlevel = flagstr:match("[%-/](W[1234])") vcxprojfile:print("<Warning%s>%s</Warning>", condition, wlevel) elseif flagstr:find("[%-/]Wall") then vcxprojfile:print("<Warning%s>Wall</Warning>", condition) end -- make Defines local defstr = "" for _, flag in ipairs(flags) do flag:gsub("^[%-/]D(.*)", function (def) defstr = defstr .. vsutils.escape(def) .. ";" end ) end defstr = defstr .. "%%(Defines)" vcxprojfile:print("<Defines%s>%s</Defines>", condition, defstr) -- make Include if flagstr:find("[%-/]I") then local dirs = {} for _, flag in ipairs(flags) do flag:gsub("^[%-/]I(.*)", function (dir) table.insert(dirs, vsutils.escape(dir)) end) end if #dirs > 0 then vcxprojfile:print("<Include%s>%s</Include>", condition, table.concat(dirs, ";")) end end end -- make TargetMachinePlatform local machinebitwidth for _, flag in ipairs(flags) do flag:gsub("^%-m(.+)", function (value) machinebitwidth = value end) flag:gsub("^%-%-machine[ =](.+)", function (value) machinebitwidth = value end) end if machinebitwidth and (machinebitwidth == "32" or machinebitwidth == "64") then vcxprojfile:print("<TargetMachinePlatform%s>%s</TargetMachinePlatform>", condition, machinebitwidth) end -- make CodeGeneration local gpucode_patterns = { "%-gencode[ =]arch=(.+),code=(.+)", "%-%-generate%-code[ =]arch=(.+),code=(.+)", "%-arch", "%-%-gpu%-architecture", "%-code", "%-%-gpu%-code" } local has_gpucode = false for _, pattern in ipairs(gpucode_patterns) do if flagstr:find(pattern) then has_gpucode = true break end end if has_gpucode then local arch local codes = {} local gencodes = {} for _, flag in ipairs(flags) do flag:gsub("^%-gencode[ =]arch=(.+),code=(.+)$", function (garch, gcodes) for _, gcode in ipairs(_split_gpucodes(gcodes)) do table.insert(gencodes, garch .. "," .. gcode) end end) flag:gsub("^%-%-generate%-code[ =]arch=(.+),code=(.+)", function (garch, gcodes) for _, gcode in ipairs(_split_gpucodes(gcodes)) do table.insert(gencodes, garch .. "," .. gcode) end end) flag:gsub("^%-arch[ =](.+)", function (garch) arch = garch end) flag:gsub("^%-%-gpu%-architecture[ =](.+)", function (garch) arch = garch end) flag:gsub("^%-code[ =](.+)", function (gcodes) table.join2(codes, _split_gpucodes(gcodes)) end) flag:gsub("^%-%-gpu%-code[ =](.+)", function (gcodes) table.join2(codes, _split_gpucodes(gcodes)) end) end if arch then if #codes == 0 then table.insert(codes, arch) arch = arch:gsub("sm", "compute") table.insert(gencodes, arch .. "," .. arch) end for _, code in ipairs(codes) do table.insert(gencodes, arch .. "," .. code) end end if #gencodes > 0 then gencodes = table.unique(gencodes) vcxprojfile:print("<CodeGeneration%s>%s</CodeGeneration>", condition, table.concat(gencodes, ";")) end end if not (opt and opt.link) then -- make CudaRuntime local cudart local cudaruntime = { none = "None", static = "Static", shared = "Shared" } for _, flag in ipairs(flags) do flag:gsub("%-cudart[ =](.+)", function (value) cudart = value end) end if cudart and cudaruntime[cudart] then vcxprojfile:print("<CudaRuntime%s>%s</CudaRuntime>", condition, cudaruntime[cudart]) end -- handle GPU debug info if flagstr:find("%-G") then vcxprojfile:print("<GPUDebugInfo%s>true</GPUDebugInfo>", condition) end -- handle fast math if flagstr:find("%-use_fast_math") then vcxprojfile:print("<FastMath%s>true</FastMath>", condition) end -- handle relocatable device code local rdc for _, flag in ipairs(flags) do flag:gsub("%-rdc[ =](.+)", function (value) rdc = value end) end if rdc then vcxprojfile:print("<GenerateRelocatableDeviceCode%s>%s</GenerateRelocatableDeviceCode>", condition, rdc) end -- handle keep preprocessed files or directories if flagstr:find("%-%-keep") then vcxprojfile:print("<Keep%s>true</Keep>", condition) end if flagstr:find("%-%-keep%-dir") then local dirs = {} for _, flag in ipairs(flags) do flag:gsub("%-%-keep%-dir[ =](.*)", function (dir) table.insert(dirs, dir) end) end if #dirs > 0 then vcxprojfile:print("<KeepDir%s>%s</KeepDir>", condition, table.concat(dirs, ";")) end end end -- make AdditionalOptions local excludes = { "Od", "O1", "O2", "O3", "Ox", "W1", "W2", "W3", "W4", "Wall", "I", "D", "L", "l", "m", "%-machine", "gencode", "arch", "code", "cudart", "G", "use_fast_math", "rdc", "%-keep", "%-keep%-dir" } local additional_flags = _exclude_flags(flags, excludes) if #additional_flags > 0 then vcxprojfile:print("<AdditionalOptions%s>%s %%(AdditionalOptions)</AdditionalOptions>", condition, os.args(additional_flags)) end end -- make custom commands item function _make_custom_commands_item(vcxprojfile, commands, suffix) if suffix == "after" or suffix == "after_link" then vcxprojfile:print("<PostBuildEvent>") elseif suffix == "before" then vcxprojfile:print("<PreBuildEvent>") elseif suffix == "before_link" then vcxprojfile:print("<PreLinkEvent>") end vcxprojfile:print("<Message></Message>") local cmdstr = "setlocal" for _, command in ipairs(commands) do cmdstr = cmdstr .. "\n" .. command cmdstr = cmdstr .. "\nif %errorlevel% neq 0 goto :xmEnd" end cmdstr = cmdstr .. "\n" .. [[:xmEnd endlocal &amp; call :xmErrorLevel %errorlevel% &amp; goto :xmDone :xmErrorLevel exit /b %1 :xmDone if %errorlevel% neq 0 goto :VCEnd]] vcxprojfile:print("<Command>%s</Command>", cmdstr:replace("<", " &lt;"):replace(">", "&gt;"):replace("/Fo ", "/Fo")) if suffix == "after" or suffix == "after_link" then vcxprojfile:print("</PostBuildEvent>") elseif suffix == "before" then vcxprojfile:print("</PreBuildEvent>") elseif suffix == "before_link" then vcxprojfile:print("</PreLinkEvent>") end end -- make custom commands function _make_custom_commands(vcxprojfile, target) for suffix, cmds in pairs(target.commands) do _make_custom_commands_item(vcxprojfile, cmds, suffix) end end -- make common item function _make_common_item(vcxprojfile, vsinfo, target, targetinfo) -- init the linker kinds local linkerkinds = { binary = "Link" , static = "Lib" , moduleonly = "Lib" -- emulate moduleonly with staticlib , shared = "Link" } if not linkerkinds[targetinfo.targetkind] then return end -- enter ItemDefinitionGroup vcxprojfile:enter("<ItemDefinitionGroup Condition=\"\'%$(Configuration)|%$(Platform)\'==\'%s|%s\'\">", targetinfo.mode, targetinfo.arch) -- for linker? vcxprojfile:enter("<%s>", linkerkinds[targetinfo.targetkind]) -- save subsystem local subsystem = "Console" -- make linker flags local flags = {} local excludes = { "nologo", "machine:%w+", "pdb:.+%.pdb", "debug" } local libdirs = {} local links = {} for _, flag in ipairs(_make_linkflags(targetinfo, target.project_dir)) do local flag_lower = flag:lower() -- remove "-subsystem:windows" if flag_lower:find("[%-/]subsystem:windows") then subsystem = "Windows" elseif flag_lower:find("[%-/]libpath") then -- link dir flag:gsub("[%-/]libpath:(.*)", function (dir) table.insert(libdirs, vsutils.escape(dir)) end) elseif flag_lower:find("[^%-/].+%.lib") then -- link file table.insert(links, flag) else local excluded = false for _, exclude in ipairs(excludes) do if flag:find("[%-/]" .. exclude) then excluded = true break end end if not excluded then table.insert(flags, flag) end end end -- make AdditionalLibraryDirectories if #libdirs > 0 then vcxprojfile:print("<AdditionalLibraryDirectories>%s;%%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>", table.concat(libdirs, ";")) end -- make AdditionalDependencies if #links > 0 then vcxprojfile:print("<AdditionalDependencies>%s;%%(AdditionalDependencies)</AdditionalDependencies>", table.concat(links, ";")) end -- make AdditionalOptions if #flags > 0 then flags = os.args(flags) vcxprojfile:print("<AdditionalOptions>%s %%(AdditionalOptions)</AdditionalOptions>", vsutils.escape(flags)) end -- generate debug infomation? if linkerkinds[targetinfo.targetkind] == "Link" then -- enable debug infomation? local debug = false for _, symbol in ipairs(targetinfo.symbols) do if symbol == "debug" then debug = true break end end vcxprojfile:print("<GenerateDebugInformation>%s</GenerateDebugInformation>", tostring(debug)) end -- make SubSystem if targetinfo.targetkind == "binary" then vcxprojfile:print("<SubSystem>%s</SubSystem>", subsystem) end -- make TargetMachine vcxprojfile:print("<TargetMachine>%s</TargetMachine>", (targetinfo.arch == "x64" and "MachineX64" or "MachineX86")) vcxprojfile:leave("</%s>", linkerkinds[targetinfo.targetkind]) -- for C/C++ compiler? vcxprojfile:enter("<ClCompile>") -- make source options _make_source_options_cl(vcxprojfile, targetinfo.commonflags.cl) -- add c and c++ standard local clangflags = { c11 = "stdc11", c17 = "stdc17", clatest = "stdc17", gnu11 = "stdc11", gnu17 = "stdc17", gnulatest = "stdc17", } local cxxlangflags = { cxx11 = "stdcpp11", cxx14 = "stdcpp14", cxx17 = "stdcpp17", cxx1z = "stdcpp17", cxx20 = "stdcpp20", cxx2a = "stdcpplatest", cxx23 = "stdcpplatest", cxx2b = "stdcpplatest", cxxlatest = "stdcpplatest", gnuxx11 = "stdcpp11", gnuxx14 = "stdcpp14", gnuxx17 = "stdcpp17", gnuxx1z = "stdcpp20", gnux20 = "stdcpp20", gnux2a = "stdcpplatest", } local cstandard local cxxstandard for _, lang in pairs(targetinfo.languages) do lang = lang:replace("c++", "cxx", {plain = true}) if cxxlangflags[lang] then cxxstandard = cxxlangflags[lang] elseif clangflags[lang] then cstandard = clangflags[lang] end end if cxxstandard then vcxprojfile:print("<LanguageStandard>%s</LanguageStandard>", cxxstandard) end if cstandard then vcxprojfile:print("<LanguageStandard_C>%s</LanguageStandard_C>", cstandard) end if targetinfo.has_modules then vcxprojfile:enter("<ScanSourceForModuleDependencies>true</ScanSourceForModuleDependencies>") end -- use c or c++ precompiled header local pcheader = target.pcxxheader or target.pcheader if pcheader then -- make precompiled header and outputfile vcxprojfile:print("<PrecompiledHeader>Use</PrecompiledHeader>") vcxprojfile:print("<PrecompiledHeaderFile>%s</PrecompiledHeaderFile>", vsutils.escape(path.filename(pcheader))) local pcoutputfile = targetinfo.pcxxoutputfile or targetinfo.pcoutputfile if pcoutputfile then vcxprojfile:print("<PrecompiledHeaderOutputFile>%s</PrecompiledHeaderOutputFile>", vsutils.escape(path.relative(path.absolute(pcoutputfile), target.project_dir))) end vcxprojfile:print("<ForcedIncludeFiles>%s;%%(ForcedIncludeFiles)</ForcedIncludeFiles>", vsutils.escape(path.filename(pcheader))) end vcxprojfile:leave("</ClCompile>") vcxprojfile:enter("<ResourceCompile>") -- make resource options _make_resource_options_cl(vcxprojfile, targetinfo.commonflags.cl) vcxprojfile:leave("</ResourceCompile>") local cuda = _check_cuda(target) if cuda then -- for CUDA linker? vcxprojfile:enter("<CudaLink>") -- make cuda link flags _make_source_options_cuda(vcxprojfile, targetinfo.culinkflags, {link = true}) -- make devlink if targetinfo.cudevlink then vcxprojfile:print("<PerformDeviceLink>%s</PerformDeviceLink>", targetinfo.cudevlink) end vcxprojfile:leave("</CudaLink>") -- for CUDA compiler? vcxprojfile:enter("<CudaCompile>") -- make source options _make_source_options_cuda(vcxprojfile, targetinfo.commonflags.cuda) vcxprojfile:leave("</CudaCompile>") end -- make custom commands _make_custom_commands(vcxprojfile, targetinfo) -- leave ItemDefinitionGroup vcxprojfile:leave("</ItemDefinitionGroup>") end -- build common items (doesn't print anything) function _build_common_items(vsinfo, target) -- for each mode and arch for _, targetinfo in ipairs(target.info) do -- make source flags local flags_stats = {cl = {}, cuda = {}} local files_count = {cl = 0, cuda = 0} local first_flags = {} targetinfo.sourceflags = {} for _, sourcebatch in pairs(targetinfo.sourcebatches) do local sourcekind = sourcebatch.sourcekind local rulename = sourcebatch.rulename if (rulename == "c.build" or rulename == "c++.build" or rulename == "c++.build.modules" or rulename == "asm.build" or sourcekind == "mrc") then for _, sourcefile in ipairs(sourcebatch.sourcefiles) do -- make compiler flags local flags = _make_compflags(sourcefile, targetinfo, target.project_dir) -- no common flags for asm/rc if sourcekind ~= "as" and sourcekind ~= "mrc" then for _, flag in ipairs(table.unique(flags)) do flags_stats.cl[flag] = (flags_stats.cl[flag] or 0) + 1 end -- update files count files_count.cl = files_count.cl + 1 -- save first flags if first_flags.cl == nil then first_flags.cl = flags end end -- save source flags targetinfo.sourceflags[sourcefile] = flags end elseif sourcekind == "cu" then for _, sourcefile in ipairs(sourcebatch.sourcefiles) do -- make compiler flags local flags = _make_compflags(sourcefile, targetinfo, target.project_dir) -- count flags for _, flag in ipairs(table.unique(flags)) do flags_stats.cuda[flag] = (flags_stats.cuda[flag] or 0) + 1 end -- update files count files_count.cuda = files_count.cuda + 1 -- save first flags if first_flags.cuda == nil then first_flags.cuda = flags end -- save source flags targetinfo.sourceflags[sourcefile] = flags end end end -- make common flags targetinfo.commonflags = {cl = {}, cuda = {}} for _, comp in ipairs({"cl", "cuda"}) do for _, flag in ipairs(first_flags[comp]) do if flags_stats[comp][flag] >= files_count[comp] then table.insert(targetinfo.commonflags[comp], flag) end end end -- remove common flags from source flags local sourceflags = {} for _, sourcebatch in pairs(targetinfo.sourcebatches) do local sourcekind = sourcebatch.sourcekind local rulename = sourcebatch.rulename if (sourcekind == "as" or sourcekind == "mrc") then -- no common flags for as/mrc files for _, sourcefile in ipairs(sourcebatch.sourcefiles) do sourceflags[sourcefile] = targetinfo.sourceflags[sourcefile] end elseif rulename == "c.build" or rulename == "c++.build" or rulename == "c++.build.modules" then -- sourcekind maybe bind multiple rules, e.g. c++modules for _, sourcefile in ipairs(sourcebatch.sourcefiles) do local flags = targetinfo.sourceflags[sourcefile] local otherflags = {} for _, flag in ipairs(flags) do if flags_stats.cl[flag] < files_count.cl then table.insert(otherflags, flag) end end sourceflags[sourcefile] = otherflags end elseif sourcekind == "cu" then for _, sourcefile in ipairs(sourcebatch.sourcefiles) do local flags = targetinfo.sourceflags[sourcefile] local otherflags = {} for _, flag in ipairs(flags) do if flags_stats.cuda[flag] < files_count.cuda then table.insert(otherflags, flag) end end sourceflags[sourcefile] = otherflags end end end targetinfo.sourceflags = sourceflags end end -- make common items function _make_common_items(vcxprojfile, vsinfo, target) -- for each mode and arch for _, targetinfo in ipairs(target.info) do -- make common item _make_common_item(vcxprojfile, vsinfo, target, targetinfo) end end -- make header file function _make_include_file(vcxprojfile, includefile, vcxprojdir) vcxprojfile:print("<ClInclude Include=\"%s\" />", path.relative(path.absolute(includefile), vcxprojdir)) end -- make source file for all modes function _make_source_file_forall(vcxprojfile, vsinfo, target, sourcefile, sourceinfo) -- get object file and source kind local sourcekind for _, info in ipairs(sourceinfo) do sourcekind = info.sourcekind break end -- enter it local nodename if sourcekind == "as" then nodename = "CustomBuild" elseif sourcekind == "mrc" then nodename = "ResourceCompile" elseif sourcekind == "cu" then nodename = "CudaCompile" elseif sourcekind == "cc" or sourcekind == "cxx" then nodename = "ClCompile" end sourcefile = path.relative(path.absolute(sourcefile), target.project_dir) vcxprojfile:enter("<%s Include=\"%s\">", nodename, sourcefile) -- for *.asm files if sourcekind == "as" then vcxprojfile:print("<ExcludedFromBuild>false</ExcludedFromBuild>") vcxprojfile:print("<FileType>Document</FileType>") for _, info in ipairs(sourceinfo) do local objectfile = path.relative(path.absolute(info.objectfile), target.project_dir) local compcmd = _make_compcmd(info.compargv, sourcefile, objectfile, target.project_dir) vcxprojfile:print("<Outputs Condition=\"\'%$(Configuration)|%$(Platform)\'==\'%s\'\">%s</Outputs>", info.mode .. '|' .. info.arch, objectfile) vcxprojfile:print("<Command Condition=\"\'%$(Configuration)|%$(Platform)\'==\'%s\'\">%s</Command>", info.mode .. '|' .. info.arch, compcmd) end vcxprojfile:print("<Message>%s</Message>", path.filename(sourcefile)) -- for *.rc files elseif sourcekind == "mrc" then for _, info in ipairs(sourceinfo) do local objectfile = path.relative(path.absolute(info.objectfile), target.project_dir) vcxprojfile:print("<ResourceOutputFileName Condition=\"\'%$(Configuration)|%$(Platform)\'==\'%s|%s\'\">%s</ResourceOutputFileName>", info.mode, info.arch, objectfile) end -- for *.c/cpp/cu files else -- compile as c++ modules if _is_modulefile(sourcefile) then vcxprojfile:print("<CompileAs>CompileAsCppModule</CompileAs>") end -- we need to use different object directory and allow parallel building -- -- @see https://github.com/xmake-io/xmake/issues/2016 -- https://github.com/xmake-io/xmake/issues/1062 for _, info in ipairs(sourceinfo) do local objectname = path.filename(info.objectfile) local targetinfo = info.targetinfo if not targetinfo.objectnames then targetinfo.objectnames = hashset:new() end if targetinfo.objectnames:has(objectname) then local outputnode = (sourcekind == "cu" and "CompileOut" or "ObjectFileName") local objectfile = path.relative(path.absolute(info.objectfile), target.project_dir) vcxprojfile:print("<%s Condition=\"\'%$(Configuration)|%$(Platform)\'==\'%s|%s\'\">%s</%s>", outputnode, info.mode, info.arch, objectfile, outputnode) else targetinfo.objectnames:insert(objectname) end end -- init items local items = { AdditionalOptions = { key = function (info) return os.args(info.flags) end , value = function (key) return key .. " %%(AdditionalOptions)" end } } -- make items for itemname, iteminfo in pairs(items) do -- make merge keys local mergekeys = {} for _, info in ipairs(sourceinfo) do local key = iteminfo.key(info) mergekeys[key] = mergekeys[key] or {} mergekeys[key][info.mode .. '|' .. info.arch] = true end for key, mergeinfos in pairs(mergekeys) do -- merge mode and arch first local count = 0 for _, mode in ipairs(vsinfo.modes) do if mergeinfos[mode .. "|Win32"] and mergeinfos[mode .. "|x64"] then mergeinfos[mode .. "|Win32"] = nil mergeinfos[mode .. "|x64"] = nil mergeinfos[mode] = true end if mergeinfos[mode] then count = count + 1 end end -- disable the precompiled header if sourcekind ~= headerkind local pcheader = target.pcxxheader or target.pcheader local pcheader_disable = false if sourcekind == "cu" or (pcheader and language.sourcekind_of(sourcefile) ~= (target.pcxxheader and "cxx" or "cc")) then pcheader_disable = true end -- all modes and archs exist? if count == #vsinfo.modes then if #key > 0 then vcxprojfile:print("<%s>%s</%s>", itemname, iteminfo.value(key), itemname) if pcheader_disable then vcxprojfile:print("<PrecompiledHeader>NotUsing</PrecompiledHeader>") end end else for cond, _ in pairs(mergeinfos) do if cond:find('|', 1, true) then -- for mode | arch if #key > 0 then vcxprojfile:print("<%s Condition=\"\'%$(Configuration)|%$(Platform)\'==\'%s\'\">%s</%s>", itemname, cond, iteminfo.value(key), itemname) if pcheader_disable then vcxprojfile:print("<PrecompiledHeader Condition=\"\'%$(Configuration)|%$(Platform)\'==\'%s\'\">NotUsing</PrecompiledHeader>", cond) end end else -- only for mode if #key > 0 then vcxprojfile:print("<%s Condition=\"\'%$(Configuration)\'==\'%s\'\">%s</%s>", itemname, cond, iteminfo.value(key), itemname) if pcheader_disable then vcxprojfile:print("<PrecompiledHeader Condition=\"\'%$(Configuration)\'==\'%s\'\">NotUsing</PrecompiledHeader>", cond) end end end end end end end end -- leave it vcxprojfile:leave("</%s>", nodename) end -- make source file for specific modes function _make_source_file_forspec(vcxprojfile, vsinfo, target, sourcefile, sourceinfo) -- add source file sourcefile = path.relative(path.absolute(sourcefile), target.project_dir) for _, info in ipairs(sourceinfo) do -- enter it local nodename if info.sourcekind == "as" then nodename = "CustomBuild" elseif info.sourcekind == "mrc" then nodename = "ResourceCompile" elseif info.sourcekind == "cu" then nodename = "CudaCompile" elseif info.sourcekind == "cc" or info.sourcekind == "cxx" then nodename = "ClCompile" end vcxprojfile:enter("<%s Condition=\"\'%$(Configuration)|%$(Platform)\'==\'%s|%s\'\" Include=\"%s\">", nodename, info.mode, info.arch, sourcefile) -- for *.asm files local objectfile = path.relative(path.absolute(info.objectfile), target.project_dir) if info.sourcekind == "as" then local compcmd = _make_compcmd(info.compargv, sourcefile, objectfile, target.project_dir) vcxprojfile:print("<ExcludedFromBuild>false</ExcludedFromBuild>") vcxprojfile:print("<FileType>Document</FileType>") vcxprojfile:print("<Outputs>%s</Outputs>", objectfile) vcxprojfile:print("<Command>%s</Command>", compcmd) -- for *.rc files elseif info.sourcekind == "mrc" then vcxprojfile:print("<ResourceOutputFileName Condition=\"\'%$(Configuration)|%$(Platform)\'==\'%s|%s\'\">%s</ResourceOutputFileName>", info.mode, info.arch, objectfile) -- for *.c/cpp/cu files else -- compile as c++ modules if _is_modulefile(sourcefile) then vcxprojfile:print("<CompileAs>CompileAsCppModule</CompileAs>") end -- we need to use different object directory and allow parallel building -- -- @see https://github.com/xmake-io/xmake/issues/2016 -- https://github.com/xmake-io/xmake/issues/1062 local objectname = path.filename(objectfile) local targetinfo = info.targetinfo if not targetinfo.objectnames then targetinfo.objectnames = hashset:new() end local targetinfo = info.targetinfo local outputnode = (info.sourcekind == "cu" and "CompileOut" or "ObjectFileName") if targetinfo.objectnames:has(objectname) then vcxprojfile:print("<%s Condition=\"\'%$(Configuration)|%$(Platform)\'==\'%s|%s\'\">%s</%s>", outputnode, info.mode, info.arch, objectfile, outputnode) else targetinfo.objectnames:insert(objectname) end -- disable the precompiled header if sourcekind ~= headerkind local pcheader = target.pcxxheader or target.pcheader if pcheader and info.sourcekind ~= "cu" and language.sourcekind_of(sourcefile) ~= (target.pcxxheader and "cxx" or "cc") then vcxprojfile:print("<PrecompiledHeader>NotUsing</PrecompiledHeader>") end vcxprojfile:print("<AdditionalOptions>%s %%(AdditionalOptions)</AdditionalOptions>", os.args(info.flags)) end -- leave it vcxprojfile:leave("</%s>", nodename) end end -- make source file for precompiled header function _make_source_file_forpch(vcxprojfile, vsinfo, target) -- add precompiled source file local pcheader = target.pcxxheader or target.pcheader if pcheader then local sourcefile = path.relative(path.absolute(pcheader), target.project_dir) vcxprojfile:enter("<ClCompile Include=\"%s\">", sourcefile) vcxprojfile:print("<PrecompiledHeader>Create</PrecompiledHeader>") vcxprojfile:print("<PrecompiledHeaderFile></PrecompiledHeaderFile>") vcxprojfile:print("<AdditionalOptions> %%(AdditionalOptions)</AdditionalOptions>") for _, info in ipairs(target.info) do -- compile as c/c++ local compileas = (target.pcxxheader and "CompileAsCpp" or "CompileAsC") vcxprojfile:print("<CompileAs Condition=\"\'%$(Configuration)|%$(Platform)\'==\'%s|%s\'\">%s</CompileAs>", info.mode, info.arch, compileas) -- add object file local pcoutputfile = info.pcxxoutputfile or info.pcoutputfile if pcoutputfile then local objectfile = path.relative(path.absolute(pcoutputfile .. ".obj"), target.project_dir) vcxprojfile:print("<ObjectFileName Condition=\"\'%$(Configuration)|%$(Platform)\'==\'%s|%s\'\">%s</ObjectFileName>", info.mode, info.arch, objectfile) end end vcxprojfile:leave("</ClCompile>") end end -- make source files function _make_source_files(vcxprojfile, vsinfo, target) -- add source files vcxprojfile:enter("<ItemGroup>") -- make source file infos local sourceinfos = {} for _, targetinfo in ipairs(target.info) do for _, sourcebatch in pairs(targetinfo.sourcebatches) do local sourcekind = sourcebatch.sourcekind local rulename = sourcebatch.rulename if (rulename == "c.build" or rulename == "c++.build" or sourcekind == "as" or sourcekind == "mrc" or sourcekind == "cu") then local objectfiles = sourcebatch.objectfiles for idx, sourcefile in ipairs(sourcebatch.sourcefiles) do local objectfile = objectfiles[idx] local flags = targetinfo.sourceflags[sourcefile] sourceinfos[sourcefile] = sourceinfos[sourcefile] or {} table.insert(sourceinfos[sourcefile], {targetinfo = targetinfo, mode = targetinfo.mode, arch = targetinfo.arch, sourcekind = sourcekind, objectfile = objectfile, flags = flags, compargv = targetinfo.compargvs[sourcefile]}) end elseif rulename == "c++.build.modules" then local builder_batch = targetinfo.sourcebatches["c++.build.modules.builder"] table.sort(builder_batch.objectfiles) local objectfiles = builder_batch.objectfiles for idx, sourcefile in ipairs(sourcebatch.sourcefiles) do local is_named_module = table.contains(builder_batch.sourcefiles, sourcefile) if is_named_module then local objectfile = objectfiles[idx] local flags = targetinfo.sourceflags[sourcefile] sourceinfos[sourcefile] = sourceinfos[sourcefile] or {} table.insert(sourceinfos[sourcefile], {targetinfo = targetinfo, mode = targetinfo.mode, arch = targetinfo.arch, sourcekind = "cxx", objectfile = objectfile, flags = flags, compargv = targetinfo.compargvs[sourcefile]}) end end end end end -- make source files for sourcefile, sourceinfo in table.orderpairs(sourceinfos) do if #sourceinfo == #target.info then _make_source_file_forall(vcxprojfile, vsinfo, target, sourcefile, sourceinfo) else _make_source_file_forspec(vcxprojfile, vsinfo, target, sourcefile, sourceinfo) end end -- make precompiled source file _make_source_file_forpch(vcxprojfile, vsinfo, target) vcxprojfile:leave("</ItemGroup>") -- add include files local pcheader = target.pcxxheader or target.pcheader vcxprojfile:enter("<ItemGroup>") for _, includefile in ipairs(table.join(target.headerfiles or {}, target.extrafiles)) do -- we need to ignore pcheader file to fix https://github.com/xmake-io/xmake/issues/1171 if not pcheader or includefile ~= pcheader then _make_include_file(vcxprojfile, includefile, target.project_dir) end end vcxprojfile:leave("</ItemGroup>") end -- make vcxproj function make(vsinfo, target) -- the target name local targetname = target.name -- the vcxproj directory local vcxprojdir = target.project_dir -- build common flags _build_common_items(vsinfo, target) -- open vcxproj file local vcxprojpath = path.join(vcxprojdir, targetname .. ".vcxproj") local vcxprojfile = vsfile.open(vcxprojpath, "w") -- init indent character vsfile.indentchar(' ') -- make header _make_header(vcxprojfile, vsinfo) -- make Configurations _make_configurations(vcxprojfile, vsinfo, target) -- make common items _make_common_items(vcxprojfile, vsinfo, target) -- make source files _make_source_files(vcxprojfile, vsinfo, target) -- make deps references _make_references(vcxprojfile, vsinfo, target) -- make tailer _make_tailer(vcxprojfile, vsinfo, target) -- exit solution file vcxprojfile:close() end
0
repos/xmake/xmake/plugins/project/vstudio
repos/xmake/xmake/plugins/project/vstudio/impl/vsinfo.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 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 vsinfo.lua -- local vsinfo = { [2002] = { vstudio_version = "2002" , solution_version = "7" , project_version = "7.0" } , [2003] = { vstudio_version = "2003" , solution_version = "8" , project_version = "7.1" } , [2005] = { vstudio_version = "2005" , solution_version = "9" , project_version = "8.0" } , [2008] = { vstudio_version = "2008" , solution_version = "10" , project_version = "9.0" } , [2010] = { vstudio_version = "2010" , project_version = "4" , filters_version = "4.0" , solution_version = "11" , toolset_version = "v100" } , [2012] = { vstudio_version = "2012" , project_version = "4" , filters_version = "4.0" , solution_version = "12" , toolset_version = "v110" } , [2013] = { vstudio_version = "2013" , project_version = "12" , filters_version = "4.0" , solution_version = "12" , toolset_version = "v120" } , [2015] = { vstudio_version = "2015" , project_version = "14" , filters_version = "4.0" , solution_version = "12" , toolset_version = "v140" , sdk_version = "10.0.10240.0" } , [2017] = { vstudio_version = "2017" , project_version = "15" , filters_version = "4.0" , solution_version = "12" , toolset_version = "v141" , sdk_version = "10.0.14393.0" } , [2019] = { vstudio_version = "2019" , project_version = "16" , filters_version = "4.0" , solution_version = "12" , toolset_version = "v142" , sdk_version = "10.0.17763.0" } , [2022] = { vstudio_version = "2022" , project_version = "17" , filters_version = "4.0" , solution_version = "12" , toolset_version = "v143" , sdk_version = "10.0.19041.0" } } function main(version) assert(version) return assert(vsinfo[version], "unsupported vs version (%d)", version); end
0
repos/xmake/xmake/plugins/project/vstudio
repos/xmake/xmake/plugins/project/vstudio/impl/vsutils.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author xq114 -- @file vsutils.lua -- -- escape special chars in msbuild file function escape(str) if not str then return nil end local map = { ["%"] = "%25" -- Referencing metadata , ["$"] = "%24" -- Referencing properties , ["@"] = "%40" -- Referencing item lists , ["'"] = "%27" -- Conditions and other expressions , [";"] = "%3B" -- List separator , ["?"] = "%3F" -- Wildcard character for file names in Include and Exclude attributes , ["*"] = "%2A" -- Wildcard character for use in file names in Include and Exclude attributes -- html entities , ["\""] = "&quot;" , ["<"] = "&lt;" , [">"] = "&gt;" , ["&"] = "&amp;" } return (string.gsub(str, "[%%%$@';%?%*\"<>&]", function (c) return assert(map[c]) end)) end -- get vs arch function vsarch(arch) if arch == 'x86' or arch == 'i386' then return "Win32" end if arch == 'x86_64' then return "x64" end if arch:startswith('arm64') then return "ARM64" end if arch:startswith('arm') then return "ARM" end return arch end
0
repos/xmake/xmake/plugins/project/vstudio
repos/xmake/xmake/plugins/project/vstudio/impl/vs200x.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file vs200x.lua -- -- imports import("core.project.project") import("vs200x_solution") import("vs200x_vcproj") -- make vstudio project function make(outputdir, vsinfo) -- enter project directory local oldir = os.cd(project.directory()) -- init solution directory vsinfo.solution_dir = path.join(outputdir, "vs" .. vsinfo.vstudio_version) -- make solution vs200x_solution.make(vsinfo) -- TODO -- disable precompiled header first for _, target in pairs(project.targets()) do target:set("pcheader", nil) target:set("pcxxheader", nil) end -- make vsprojs for _, target in pairs(project.targets()) do if not target:is_phony() then vs200x_vcproj.make(vsinfo, target) end end -- leave project directory os.cd(oldir) end
0
repos/xmake/xmake/plugins/project/vstudio
repos/xmake/xmake/plugins/project/vstudio/impl/vsfile.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file vsfile.lua -- -- init the default indent character _g.indentchar = '\t' -- print file function _print_impl(self, ...) -- print indent for i = 1, self._indent do self:_write_impl(_g.indentchar) end -- print it self:_print_impl(...) end -- printf file function _printf_impl(self, ...) -- print indent for i = 1, self._indent do self:_write_impl(_g.indentchar) end -- printf it self:_printf_impl(...) end -- write file function _write_impl(self, ...) -- print indent for i = 1, self._indent do self:_write_impl(_g.indentchar) end -- write it self:_write_impl(...) end -- writef file function _writef_impl(self, ...) -- print indent for i = 1, self._indent do self:_write_impl(_g.indentchar) end -- writef it self:_writef_impl(...) end -- enter and print file function _enter(self, ...) -- print it self:print(...) -- increase indent self._indent = self._indent + 1 end -- leave and print file function _leave(self, ...) -- decrease indent if self._indent >= 1 then self._indent = self._indent - 1 else self._indent = 0 end -- print it self:print(...) end -- open file function open(filepath, mode) -- open it local file = io.open(filepath, mode, {encoding = "utf8bom"}) -- hook print, printf and write file._print_impl = file.print file._printf_impl = file.printf file._write_impl = file.write file._writef_impl = file.writef file.print = _print_impl file.printf = _printf_impl file.write = _write_impl file.writef = _writef_impl -- add enter and leave interfaces file.enter = _enter file.leave = _leave -- init indent file._indent = 0 -- ok? return file end -- set indent character function indentchar(ch) _g.indentchar = ch or '\t' end
0
repos/xmake/xmake/plugins/project/vstudio
repos/xmake/xmake/plugins/project/vstudio/impl/vs200x_solution.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file vs200x_solution.lua -- -- imports import("core.project.project") import("vsfile") -- make header function _make_header(slnfile, vsinfo) slnfile:print("Microsoft Visual Studio Solution File, Format Version %s.00", vsinfo.solution_version) slnfile:print("# Visual Studio %s", vsinfo.vstudio_version) end -- make projects function _make_projects(slnfile, vsinfo) -- the vstudio tool uuid for vc project local vctool = "8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942" -- make all targets for targetname, target in pairs(project.targets()) do if not target:is_phony() then -- enter project slnfile:enter("Project(\"{%s}\") = \"%s\", \"%s\\%s.vcproj\", \"{%s}\"", vctool, targetname, targetname, targetname, hash.uuid4(targetname)) -- add dependencies for _, dep in ipairs(target:get("deps")) do slnfile:enter("ProjectSection(ProjectDependencies) = postProject") slnfile:print("{%s} = {%s}", hash.uuid4(dep), hash.uuid4(dep)) slnfile:leave("EndProjectSection") end -- leave project slnfile:leave("EndProject") end end end -- make global function _make_global(slnfile, vsinfo) -- enter global slnfile:enter("Global") -- add solution configuration platforms slnfile:enter("GlobalSection(SolutionConfigurationPlatforms) = preSolution") slnfile:print("$(mode)|Win32 = $(mode)|Win32") slnfile:leave("EndGlobalSection") -- add project configuration platforms slnfile:enter("GlobalSection(ProjectConfigurationPlatforms) = postSolution") for targetname, target in pairs(project.targets()) do if not target:is_phony() then slnfile:print("{%s}.$(mode)|Win32.ActiveCfg = $(mode)|Win32", hash.uuid4(targetname)) slnfile:print("{%s}.$(mode)|Win32.Build.0 = $(mode)|Win32", hash.uuid4(targetname)) end end slnfile:leave("EndGlobalSection") -- add solution properties slnfile:enter("GlobalSection(SolutionProperties) = preSolution") slnfile:print("HideSolutionNode = FALSE") slnfile:leave("EndGlobalSection") -- leave global slnfile:leave("EndGlobal") end -- make solution function make(vsinfo) -- init solution name vsinfo.solution_name = project.name() or ("vs" .. vsinfo.vstudio_version) -- open solution file local slnfile = vsfile.open(path.join(vsinfo.solution_dir, vsinfo.solution_name .. ".sln"), "w") -- init indent character vsfile.indentchar('\t') -- make header _make_header(slnfile, vsinfo) -- make projects _make_projects(slnfile, vsinfo) -- make global _make_global(slnfile, vsinfo) -- exit solution file slnfile:close() end
0
repos/xmake/xmake/plugins/project
repos/xmake/xmake/plugins/project/utils/target_cmds.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file target_cmds.lua -- -- imports import("core.project.project") import("core.project.config") import("core.base.hashset") import("core.project.rule") import("private.utils.batchcmds") import("private.utils.rule_groups") -- this sourcebatch is built? function _sourcebatch_is_built(sourcebatch) -- we can only use rulename to filter them because sourcekind may be bound to multiple rules local rulename = sourcebatch.rulename if rulename == "c.build" or rulename == "c++.build" or rulename == "asm.build" or rulename == "cuda.build" or rulename == "objc.build" or rulename == "objc++.build" or rulename == "win.sdk.resource" then return true end end -- get target buildcmd commands function get_target_buildcmd(target, cmds, opt) opt = opt or {} local suffix = opt.suffix local ignored_rules = hashset.from(opt.ignored_rules or {}) for _, ruleinst in ipairs(target:orderules()) do if not ignored_rules:has(ruleinst:name()) then local scriptname = "buildcmd" .. (suffix and ("_" .. suffix) or "") local script = ruleinst:script(scriptname) if script then local batchcmds_ = batchcmds.new({target = target}) script(target, batchcmds_, {}) if not batchcmds_:empty() then table.join2(cmds, batchcmds_:cmds()) end end end end end -- get target buildcmd_files commands function get_target_buildcmd_files(target, cmds, sourcebatch, opt) opt = opt or {} -- get rule local rulename = assert(sourcebatch.rulename, "unknown rule for sourcebatch!") local ruleinst = assert(target:rule(rulename) or project.rule(rulename) or rule.rule(rulename), "unknown rule: %s", rulename) local ignored_rules = hashset.from(opt.ignored_rules or {}) if ignored_rules:has(ruleinst:name()) then return end -- generate commands for xx_buildcmd_files local suffix = opt.suffix local scriptname = "buildcmd_files" .. (suffix and ("_" .. suffix) or "") local script = ruleinst:script(scriptname) if script then local batchcmds_ = batchcmds.new({target = target}) script(target, batchcmds_, sourcebatch, {}) if not batchcmds_:empty() then table.join2(cmds, batchcmds_:cmds()) end end -- generate commands for xx_buildcmd_file if not script then scriptname = "buildcmd_file" .. (suffix and ("_" .. suffix) or "") script = ruleinst:script(scriptname) if script then local sourcekind = sourcebatch.sourcekind for _, sourcefile in ipairs(sourcebatch.sourcefiles) do local batchcmds_ = batchcmds.new({target = target}) script(target, batchcmds_, sourcefile, {}) if not batchcmds_:empty() then table.join2(cmds, batchcmds_:cmds()) end end end end end -- get target buildcmd commands of source group function get_target_buildcmd_sourcegroups(target, cmds, sourcegroups, opt) for idx, group in irpairs(sourcegroups) do for _, item in pairs(group) do -- buildcmd scripts are always in rule, so we need to ignore target item (item.target). local sourcebatch = item.sourcebatch if item.rule then if not _sourcebatch_is_built(sourcebatch) then get_target_buildcmd_files(target, cmds, sourcebatch, opt) end end end end end
0
repos/xmake/xmake/plugins/project
repos/xmake/xmake/plugins/project/clang/compile_commands.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file compile_commands.lua -- -- imports import("core.base.option") import("core.tool.compiler") import("core.project.rule") import("core.project.project") import("core.language.language") import("private.utils.batchcmds") import("private.utils.executable_path") import("private.utils.rule_groups") import("plugins.project.utils.target_cmds", {rootdir = os.programdir()}) import("actions.test.main", {rootdir = os.programdir(), alias = "test_action"}) -- escape path function _escape_path(p) return os.args(p, {escape = true, nowrap = true}) end -- this sourcebatch is built? function _sourcebatch_is_built(sourcebatch) -- we can only use rulename to filter them because sourcekind may be bound to multiple rules local rulename = sourcebatch.rulename if rulename == "c.build" or rulename == "c++.build" or rulename == "asm.build" or rulename == "cuda.build" or rulename == "objc.build" or rulename == "objc++.build" then return true end end -- get LSP, clangd, ccls, ... function _get_lsp() local lsp = option.get("lsp") if lsp == nil then lsp = os.getenv("XMAKE_GENERATOR_COMPDB_LSP") end return lsp end -- specify windows sdk verison function _get_windows_sdk_arguments(target) local args = {} local msvc = target:toolchain("msvc") if msvc then local envs = msvc:runenvs() local WindowsSdkDir = envs.WindowsSdkDir local WindowsSDKVersion = envs.WindowsSDKVersion local VCToolsInstallDir = envs.VCToolsInstallDir if WindowsSdkDir and WindowsSDKVersion then local includedirs = os.dirs(path.join(WindowsSdkDir, "Include", envs.WindowsSDKVersion, "*")) for _, tool in ipairs({"atlmfc", "diasdk"}) do local tool_dir = path.join(WindowsSdkDir, tool, "include") if os.isdir(tool_dir) then table.insert(includedirs, tool_dir) end end if VCToolsInstallDir then table.insert(includedirs, path.join(VCToolsInstallDir, "include")) end for _, dir in ipairs(includedirs) do table.insert(args, "-imsvc") table.insert(args, dir) end end end return args end -- translate external/system include flags, because some tools (vscode) do not support them yet. -- https://github.com/xmake-io/xmake/issues/1050 function _translate_arguments(arguments) local args = {} local cc = path.basename(arguments[1]):lower() local is_include = false local lsp = _get_lsp() for idx, arg in ipairs(arguments) do -- convert path to string, maybe we need to convert path, but not supported now. arg = tostring(arg) -- see https://github.com/xmake-io/xmake/issues/1721 if idx == 1 and is_host("windows") and path.extension(arg) == "" then arg = arg .. ".exe" end if arg:startswith("-isystem-after", 1, true) then arg = "-I" .. arg:sub(15) elseif arg:startswith("-isystem", 1, true) then -- clangd support `-isystem`, we don't need to translate it -- @see https://github.com/xmake-io/xmake/issues/3020 if not lsp or lsp ~= "clangd" then arg = "-I" .. arg:sub(9) end elseif arg:find("[%-/]external:I") then arg = arg:gsub("[%-/]external:I", "-I") elseif arg:find("[%-/]external:W") or arg:find("[%-/]experimental:external") then arg = nil end -- @see use msvc-style flags for msvc to support language-server better -- https://github.com/xmake-io/xmake/issues/1284 if cc == "cl" and arg and arg:startswith("-") then arg = arg:gsub("^%-", "/") elseif cc == "nvcc" and arg then -- support -I path with spaces for nvcc -- https://github.com/xmake-io/xmake/issues/1726 if is_include then if arg and arg:find(' ', 1, true) then arg = "\"" .. arg .. "\"" end is_include = false elseif arg:startswith("-I") then local f = arg:sub(1, 2) local v = arg:sub(3) if v and v:find(' ', 1, true) then arg = f .. "\"" .. v .. "\"" end elseif arg:startswith("-ccbin=") then -- @see https://github.com/xmake-io/xmake/issues/4716 local f = arg:sub(1, 7) local v = arg:sub(8) if v then arg = f .. v:gsub("\\\\", "\\") end end end if arg == "-I" then is_include = true end if arg then -- improve to support for "/usr/bin/xcrun -sdk macosx clang" -- @see -- https://github.com/xmake-io/xmake/issues/3159 -- https://github.com/xmake-io/xmake/issues/3286 if idx == 1 then arg = executable_path(arg) end table.insert(args, arg) end end return args end -- make command function _make_arguments(jsonfile, arguments, opt) -- attempt to get source file from arguments opt = opt or {} local sourcefile = opt.sourcefile if not sourcefile then for _, arg in ipairs(arguments) do local sourcekind = try {function () return language.sourcekind_of(path.filename(arg)) end} if sourcekind and os.isfile(arg) then sourcefile = tostring(arg) break end end if not sourcefile then return end end -- translate some unsupported arguments arguments = _translate_arguments(arguments) local lsp = _get_lsp() local target = opt.target if lsp and lsp == "clangd" and target and target:is_plat("windows") then table.join2(arguments, _get_windows_sdk_arguments(target)) end -- escape '"', '\' local arguments_escape = {} for _, arg in ipairs(arguments) do table.insert(arguments_escape, _escape_path(arg)) end -- remove repeat -- this is because some rules will repeatedly bind the same sourcekind, e.g. `rule("c++.build.modules.builder")` local key = hash.uuid(os.args(arguments_escape) .. sourcefile) local map = _g.map or {} _g.map = map if map[key] then return end -- make body jsonfile:printf( [[%s{ "directory": "%s", "arguments": ["%s"], "file": "%s" }]], (_g.firstline and "" or ",\n"), _escape_path(os.projectdir()), table.concat(arguments_escape, "\", \""), _escape_path(sourcefile)) -- clear first line marks _g.firstline = false map[key] = true end -- add target custom commands function _add_target_custom_commands(jsonfile, target, suffix, cmds) for _, cmd in ipairs(cmds) do if cmd.program then _make_arguments(jsonfile, table.join(cmd.program, cmd.argv), {target = target}) end end end -- add target source commands function _add_target_source_commands(jsonfile, target) for _, sourcebatch in pairs(target:sourcebatches()) do local sourcekind = sourcebatch.sourcekind if sourcekind and _sourcebatch_is_built(sourcebatch) then for index, sourcefile in ipairs(sourcebatch.sourcefiles) do local objectfile = sourcebatch.objectfiles[index] local arguments = table.join(compiler.compargv(sourcefile, objectfile, {target = target, sourcekind = sourcekind, rawargs=true})) _make_arguments(jsonfile, arguments, {sourcefile = sourcefile, target = target}) end end end end -- add target commands function _add_target_commands(jsonfile, target) -- build sourcebatch groups first local sourcegroups = rule_groups.build_sourcebatch_groups(target, target:sourcebatches()) -- add before commands -- we use irpairs(groups), because the last group that should be given the highest priority. local cmds_before = {} target_cmds.get_target_buildcmd(target, cmds_before, {suffix = "before"}) target_cmds.get_target_buildcmd_sourcegroups(target, cmds_before, sourcegroups, {suffix = "before"}) -- rule.on_buildcmd_files should also be executed before building the target, as cmake PRE_BUILD does not work. target_cmds.get_target_buildcmd_sourcegroups(target, cmds_before, sourcegroups) _add_target_custom_commands(jsonfile, target, "before", cmds_before) -- add target source commands _add_target_source_commands(jsonfile, target) -- add after commands local cmds_after = {} target_cmds.get_target_buildcmd_sourcegroups(target, cmds_after, sourcegroups, {suffix = "after"}) target_cmds.get_target_buildcmd(target, cmds_after, {suffix = "after"}) _add_target_custom_commands(jsonfile, target, "after", cmds_after) end -- add target function _add_target(jsonfile, target) -- https://github.com/xmake-io/xmake/issues/2337 target:data_set("plugin.project.kind", "compile_commands") -- enter package environments local oldenvs = os.addenvs(target:pkgenvs()) -- we enable it for clangd, @see https://github.com/xmake-io/xmake/issues/2818 local lsp = _get_lsp() if not lsp or lsp ~= "clangd" then target:set("pcheader", nil) target:set("pcxxheader", nil) end -- add target commands _add_target_commands(jsonfile, target) -- restore package environments os.setenvs(oldenvs) end -- add targets function _add_targets(jsonfile) jsonfile:print("[") _g.firstline = true for _, target in pairs(project.targets()) do if not target:is_phony() then _add_target(jsonfile, target) end end -- https://github.com/xmake-io/xmake/issues/4750 for _, test in pairs(test_action.get_tests()) do local target = test.target if not target:is_phony() then _add_target(jsonfile, target) end end jsonfile:print("]") end -- generate compilation databases for clang-based tools(compile_commands.json) -- -- references: -- - https://clang.llvm.org/docs/JSONCompilationDatabase.html -- - https://sarcasm.github.io/notes/dev/compilation-database.html -- - http://eli.thegreenplace.net/2014/05/21/compilation-databases-for-clang-based-tools -- function make(outputdir) local oldir = os.cd(os.projectdir()) local jsonfile = io.open(path.join(outputdir, "compile_commands.json"), "w") _add_targets(jsonfile) jsonfile:close() os.cd(oldir) end
0
repos/xmake/xmake/plugins/project
repos/xmake/xmake/plugins/project/clang/compile_flags.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author luzhlon -- @file compile_flags.lua -- -- imports import("core.tool.compiler") import("core.project.project") import("core.language.language") -- make the object function _make_object(target, flags, sourcefile, objectfile) -- get the source file kind local sourcekind = language.sourcekind_of(sourcefile) -- get compile arguments local arguments = compiler.compflags(sourcefile, {target = target}) for i, flag in ipairs(arguments) do -- only export the -I*/-D* flags if flag == "-I" or flag == "/I" or flag == "-isystem" then table.insert(flags, flag .. arguments[i + 1]) elseif flag:find('^-[ID]') or flag:find("-isystem", 1, true) then table.insert(flags, flag) end end -- clear first line marks _g.firstline = false end -- make objects function _make_objects(target, flags, sourcekind, sourcebatch) for index, objectfile in ipairs(sourcebatch.objectfiles) do _make_object(target, flags, sourcebatch.sourcefiles[index], objectfile) end end -- make target function _make_target(target, flags) -- TODO -- disable precompiled header first target:set("pcheader", nil) target:set("pcxxheader", nil) -- build source batches for _, sourcebatch in pairs(target:sourcebatches()) do local sourcekind = sourcebatch.sourcekind if sourcekind then _make_objects(target, flags, sourcekind, sourcebatch) end end end -- make all function _make_all(flags) _g.firstline = true for _, target in pairs(project.targets()) do if not target:is_phony() and target:is_default() then _make_target(target, flags) end end return table.unique(flags) end -- generate compilation databases for clang-based tools(compile_flags.txt) -- -- references: -- - https://clang.llvm.org/docs/JSONCompilationDatabase.html -- function make(outputdir) -- enter project directory local oldir = os.cd(os.projectdir()) -- make all local flags = {} flags = _make_all(flags) -- write to file local flagfile = io.open(path.join(outputdir, "compile_flags.txt"), "w") for i, flag in ipairs(flags) do flagfile:write(flag, '\n') end flagfile:close() -- leave project directory os.cd(oldir) end
0
repos/xmake/xmake/plugins/project
repos/xmake/xmake/plugins/project/cmake/cmakelists.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file cmakelists.lua -- -- imports import("core.base.colors") import("core.project.project") import("core.project.config") import("core.tool.compiler") import("core.base.semver") import("core.base.hashset") import("core.project.rule") import("core.platform.platform") import("lib.detect.find_tool") import("private.utils.batchcmds") import("private.utils.rule_groups") import("private.utils.target", {alias = "target_utils"}) import("plugins.project.utils.target_cmds", {rootdir = os.programdir()}) import("rules.c++.modules.modules_support.compiler_support", {alias = "module_compiler_support", rootdir = os.programdir()}) -- get cmake version function _get_cmake_version() local cmake_version = _g.cmake_version if not cmake_version then local cmake = find_tool("cmake", {version = true}) if cmake and cmake.version then cmake_version = semver.new(cmake.version) end _g.cmake_version = cmake_version end return cmake_version end -- has c++ modules sources function _has_cxxmodules_sources() for _, target in ipairs(project.ordertargets()) do if module_compiler_support.contains_modules(target) then return true end end end -- get minimal cmake version function _get_cmake_minver() local cmake_minver = _g.cmake_minver if not cmake_minver then cmake_minver = _get_cmake_version() if cmake_minver then if _has_cxxmodules_sources() and cmake_minver:gt("3.28.0") then cmake_minver = semver.new("3.28.0") elseif cmake_minver:gt("3.15.0") then cmake_minver = semver.new("3.15.0") end end if not cmake_minver then cmake_minver = semver.new("3.15.0") end _g.cmake_minver = cmake_minver end return cmake_minver end -- tranlate path function _translate_path(filepath, outputdir) filepath = path.translate(filepath) if filepath == "" then return "" end if path.is_absolute(filepath) then if filepath:startswith(project.directory()) then return path.relative(filepath, outputdir) end return filepath else return path.relative(path.absolute(filepath), outputdir) end end -- escape path function _escape_path(filepath) if is_host("windows") then filepath = path.unix(filepath) filepath = filepath:gsub(' ', '\\ ') end return filepath end -- escape path in flag -- @see https://github.com/xmake-io/xmake/issues/3161 function _escape_path_in_flag(target, flag) if is_host("windows") and target:has_tool("cc", "cl") then -- e.g. /ManifestInput:xx, /def:xxx if flag:find(":", 1, true) then flag = _escape_path(flag) end end return flag end -- get relative unix path function _get_relative_unix_path(filepath, outputdir) filepath = _translate_path(filepath, outputdir) filepath = _escape_path(path.translate(filepath)) return os.args(filepath) end -- get relative unix path to the cmake path -- @see https://github.com/xmake-io/xmake/issues/2026 function _get_relative_unix_path_to_cmake(filepath, outputdir) filepath = _translate_path(filepath, outputdir) filepath = path.unix(path.translate(filepath)) if filepath and not path.is_absolute(filepath) then filepath = "${CMAKE_SOURCE_DIR}/" .. filepath end return os.args(filepath) end -- get enabled languages function _get_project_languages() local languages = {} for _, target in ipairs(project.ordertargets()) do for _, sourcekind in ipairs(target:sourcekinds()) do if sourcekind == "cc" then table.insert(languages, "C") elseif sourcekind == "cxx" then table.insert(languages, "CXX") elseif sourcekind == "as" then table.insert(languages, "ASM") elseif sourcekind == "cu" then table.insert(languages, "CUDA") end end end languages = table.unique(languages) return languages end -- get configs from target function _get_configs_from_target(target, name) local values = {} if name:find("flags", 1, true) then table.join2(values, target:toolconfig(name)) end for _, value in ipairs((target:get_from(name, "*"))) do table.join2(values, value) end if not name:find("flags", 1, true) then -- for includedirs, links .. table.join2(values, target:toolconfig(name)) end return table.unique(values) end -- Did the current cmake native support for c++ modules? function _can_native_support_for_cxxmodules() local cmake_minver = _get_cmake_minver() if cmake_minver and cmake_minver:ge("3.28") then return true end end -- this sourcebatch is built? function _sourcebatch_is_built(sourcebatch) -- we can only use rulename to filter them because sourcekind may be bound to multiple rules local rulename = sourcebatch.rulename if rulename == "c.build" or rulename == "c++.build" or rulename == "asm.build" or rulename == "cuda.build" or rulename == "objc.build" or rulename == "objc++.build" or rulename == "win.sdk.resource" then return true end if _can_native_support_for_cxxmodules() then if rulename == "c++.build.modules" then return true end end end -- get c++ modules rules function _get_cxxmodules_rules() return {"c++.build.modules", "c++.build.modules.builder"} end -- translate flag function _translate_flag(flag, outputdir) if flag then if path.instance_of(flag) then flag = flag:clone():set(_get_relative_unix_path_to_cmake(flag:rawstr(), outputdir)):str() -- it may be table, https://github.com/xmake-io/xmake/issues/4816 elseif type(flag) == "string" then if path.is_absolute(flag) then flag = _get_relative_unix_path_to_cmake(flag, outputdir) elseif flag:startswith("-fmodule-file=") then flag = "-fmodule-file=" .. _get_relative_unix_path_to_cmake(flag:sub(15), outputdir) elseif flag:startswith("-fmodule-mapper=") then flag = "-fmodule-mapper=" .. _get_relative_unix_path_to_cmake(flag:sub(17), outputdir) elseif flag:match("(.+)=(.+)") then local k, v = flag:match("(.+)=(.+)") if v and (v:endswith(".ifc") or v:endswith(".map")) then -- e.g. hello=xxx/hello.ifc flag = k .. "=" .. _get_relative_unix_path_to_cmake(v, outputdir) end end end end return flag end -- translate flags function _translate_flags(flags, outputdir) if not flags then return end local result = {} for _, flag in ipairs(flags) do if type(flag) == "table" and not path.instance_of(flag) then for _, v in ipairs(flag) do table.insert(result, _translate_flag(v, outputdir)) end else table.insert(result, _translate_flag(flag, outputdir)) end end return result end -- map compiler flags function _map_compflags(toolname, langkind, name, values) local fake_target = { is_shared = function() return false end, tool = function() local program if toolname == "cl" then program = "cl.exe" elseif toolname == "gcc" then program = "gcc" elseif toolname == "clang" then program = "clang" end return program, toolname end, sourcekinds = function() return langkind == "c" and "cc" or "cxx" end } return compiler.map_flags(langkind, name, values, {target = fake_target}) end -- split flag with tool prefix, e.g. clang::-Dclang function _split_flag_with_tool_prefix(flag) local prefix local splitinfo = flag:split("::") if #splitinfo == 2 then prefix = splitinfo[1] flag = splitinfo[2] end return prefix, flag end -- get flags from fileconfig function _get_flags_from_fileconfig(fileconfig, outputdir, name) local flags = {} table.join2(flags, fileconfig[name]) if fileconfig.force then table.join2(flags, fileconfig.force[name]) end flags = _translate_flags(flags, outputdir) if #flags > 0 then return flags end end -- get flags from target -- @see https://github.com/xmake-io/xmake/issues/3594 function _get_flags_from_target(target, flagkind) local results = {} local flags = _get_configs_from_target(target, flagkind) for _, flag in ipairs(flags) do local tools = target:extraconf(flagkind, flag, "tools") if not flag:find("::", 1, true) and tools then for _, toolname in ipairs(tools) do table.insert(results, toolname .. "::" .. flag) end else table.insert(results, flag) end end return results end -- set compiler function _set_compiler(cmakelists) if config.get("toolchain") then local cc = platform.tool("cc") if cc then cc = path.unix(cc) cmakelists:print("set(CMAKE_C_COMPILER \"%s\")", cc) end local cxx, cxx_name = platform.tool("cxx") if cxx then if cxx_name == "clang" or cxx_name == "gcc" then local dir = path.directory(cxx) local name = path.filename(cxx) name = name:gsub("clang$", "clang++") name = name:gsub("clang%-", "clang++-") name = name:gsub("gcc$", "g++") name = name:gsub("gcc%-", "g++-") if dir ~= '.' then cxx = path.join(dir, name) else cxx = name end end cxx = path.unix(cxx) cmakelists:print("set(CMAKE_CXX_COMPILER \"%s\")", cxx) end end end -- add project info function _add_project(cmakelists, outputdir) local cmake_minver = _get_cmake_minver() cmakelists:print([[# this is the build file for project %s # it is autogenerated by the xmake build system. # do not edit by hand. ]], project.name() or "") cmakelists:print("# project") cmakelists:print("cmake_minimum_required(VERSION %s)", cmake_minver) if cmake_minver:ge("3.15.0") then -- for MSVC_RUNTIME_LIBRARY cmakelists:print("cmake_policy(SET CMP0091 NEW)") end -- set compilers, we need set it before project( LANGUAGES..) -- @see https://github.com/xmake-io/xmake/issues/5448 _set_compiler(cmakelists) -- set project name local project_name = project.name() if not project_name then for _, target in table.orderpairs(project.targets()) do project_name = target:name() break end end if project_name then local project_info = "" local project_version = project.version() if project_version then project_info = project_info .. " VERSION " .. project_version end local languages = _get_project_languages() if languages then cmakelists:print("project(%s%s LANGUAGES %s)", project_name, project_info, table.concat(languages, " ")) else cmakelists:print("project(%s%s)", project_name, project_info) end end if _can_native_support_for_cxxmodules() then cmakelists:print("set(CMAKE_CXX_SCAN_FOR_MODULES ON)") end cmakelists:print("") end -- add target: phony function _add_target_phony(cmakelists, target) -- https://github.com/xmake-io/xmake/issues/2337 target:data_set("plugin.project.kind", "cmakelist") cmakelists:printf("add_custom_target(%s", target:name()) local deps = target:get("deps") if deps then cmakelists:write(" DEPENDS") for _, dep in ipairs(deps) do cmakelists:write(" " .. dep) end end cmakelists:print(")") cmakelists:print("") end -- add target: binary function _add_target_binary(cmakelists, target, outputdir) cmakelists:print("add_executable(%s \"\")", target:name()) cmakelists:print("set_target_properties(%s PROPERTIES OUTPUT_NAME \"%s\")", target:name(), target:basename()) cmakelists:print("set_target_properties(%s PROPERTIES RUNTIME_OUTPUT_DIRECTORY \"%s\")", target:name(), _get_relative_unix_path_to_cmake(target:targetdir(), outputdir)) end -- add target: static function _add_target_static(cmakelists, target, outputdir) cmakelists:print("add_library(%s STATIC \"\")", target:name()) cmakelists:print("set_target_properties(%s PROPERTIES OUTPUT_NAME \"%s\")", target:name(), target:basename()) cmakelists:print("set_target_properties(%s PROPERTIES ARCHIVE_OUTPUT_DIRECTORY \"%s\")", target:name(), _get_relative_unix_path_to_cmake(target:targetdir(), outputdir)) end -- add target: shared function _add_target_shared(cmakelists, target, outputdir) cmakelists:print("add_library(%s SHARED \"\")", target:name()) cmakelists:print("set_target_properties(%s PROPERTIES OUTPUT_NAME \"%s\")", target:name(), target:basename()) if target:is_plat("windows") then -- @see https://github.com/xmake-io/xmake/issues/2192 cmakelists:print("set_target_properties(%s PROPERTIES RUNTIME_OUTPUT_DIRECTORY \"%s\")", target:name(), _get_relative_unix_path_to_cmake(target:targetdir(), outputdir)) cmakelists:print("set_target_properties(%s PROPERTIES ARCHIVE_OUTPUT_DIRECTORY \"%s\")", target:name(), _get_relative_unix_path_to_cmake(target:targetdir(), outputdir)) else cmakelists:print("set_target_properties(%s PROPERTIES LIBRARY_OUTPUT_DIRECTORY \"%s\")", target:name(), _get_relative_unix_path_to_cmake(target:targetdir(), outputdir)) end end -- add target: headeronly function _add_target_headeronly(cmakelists, target) cmakelists:print("add_library(%s INTERFACE)", target:name()) end -- add target: headeronly function _add_target_moduleonly(cmakelists, target) cmakelists:print("add_custom_target(%s)", target:name()) end -- add target dependencies function _add_target_dependencies(cmakelists, target) local deps = target:get("deps") if deps then cmakelists:printf("add_dependencies(%s", target:name()) for _, dep in ipairs(deps) do cmakelists:write(" " .. dep) end cmakelists:print(")") end end -- add target sources function _add_target_sources(cmakelists, target, outputdir) local has_cuda = false cmakelists:print("target_sources(%s PRIVATE", target:name()) local sourcebatches = target:sourcebatches() for name, sourcebatch in table.orderpairs(sourcebatches) do if _sourcebatch_is_built(sourcebatch) then for _, sourcefile in ipairs(sourcebatch.sourcefiles) do cmakelists:print(" " .. _get_relative_unix_path(sourcefile, outputdir)) end end if sourcebatch.sourcekind == "cu" then has_cuda = true end end for _, headerfile in ipairs(target:headerfiles()) do cmakelists:print(" " .. _get_relative_unix_path(headerfile, outputdir)) end cmakelists:print(")") if has_cuda then cmakelists:print("set_target_properties(%s PROPERTIES CUDA_SEPARABLE_COMPILATION ON)", target:name()) local devlink = target:policy("build.cuda.devlink") or target:values("cuda.build.devlink") if devlink ~= nil then cmakelists:print("set_target_properties(%s PROPERTIES CUDA_RESOLVE_DEVICE_SYMBOLS %s)", target:name(), devlink and "ON" or "OFF") end end end -- add target source groups -- @see https://github.com/xmake-io/xmake/issues/1149 function _add_target_source_groups(cmakelists, target, outputdir) local filegroups = target:get("filegroups") for _, filegroup in ipairs(filegroups) do local files = target:extraconf("filegroups", filegroup, "files") or "**" local mode = target:extraconf("filegroups", filegroup, "mode") local rootdir = target:extraconf("filegroups", filegroup, "rootdir") assert(rootdir, "please set root directory, e.g. add_filegroups(%s, {rootdir = 'xxx'})", filegroup) local sources = {} local recurse_sources = {} if path.is_absolute(rootdir) then rootdir = _get_relative_unix_path(rootdir, outputdir) else rootdir = string.format("${CMAKE_CURRENT_SOURCE_DIR}/%s", _get_relative_unix_path(rootdir, outputdir)) end for _, filepattern in ipairs(files) do if filepattern:find("**", 1, true) then filepattern = filepattern:gsub("%*%*", "*") table.insert(recurse_sources, _get_relative_unix_path(path.join(rootdir, filepattern), outputdir)) else table.insert(sources, _get_relative_unix_path(path.join(rootdir, filepattern), outputdir)) end end if #sources > 0 then cmakelists:print("FILE(GLOB %s_GROUP_SOURCE_LIST %s)", target:name(), table.concat(sources, " ")) if mode and mode == "plain" then cmakelists:print("source_group(%s FILES ${%s_GROUP_SOURCE_LIST})", _get_relative_unix_path(filegroup, outputdir), target:name()) else cmakelists:print("source_group(TREE %s PREFIX %s FILES ${%s_GROUP_SOURCE_LIST})", rootdir, _get_relative_unix_path(filegroup, outputdir), target:name()) end end if #recurse_sources > 0 then cmakelists:print("FILE(GLOB_RECURSE %s_GROUP_RECURSE_SOURCE_LIST %s)", target:name(), table.concat(recurse_sources, " ")) if mode and mode == "plain" then cmakelists:print("source_group(%s FILES ${%s_GROUP_RECURSE_SOURCE_LIST})", _get_relative_unix_path(filegroup, outputdir), target:name()) else cmakelists:print("source_group(TREE %s PREFIX %s FILES ${%s_GROUP_RECURSE_SOURCE_LIST})", rootdir, _get_relative_unix_path(filegroup, outputdir), target:name()) end end end end -- add target precompiled header function _add_target_precompiled_header(cmakelists, target, outputdir) local precompiled_header = target:get("pcheader") or target:get("pcxxheader") if precompiled_header then cmakelists:print("target_precompile_headers(%s PRIVATE", target:name()) cmakelists:print(" $<$<COMPILE_LANGUAGE:%s>:${CMAKE_CURRENT_SOURCE_DIR}/%s>", target:get("pcxxheader") and "CXX" or "C", _get_relative_unix_path(precompiled_header, outputdir)) cmakelists:print(")") end end -- add target include directories function _add_target_include_directories(cmakelists, target, outputdir) local includedirs = _get_configs_from_target(target, "includedirs") if #includedirs > 0 then local access_type = target:kind() == "headeronly" and "INTERFACE" or "PRIVATE" cmakelists:print("target_include_directories(%s %s", target:name(), access_type) for _, includedir in ipairs(includedirs) do cmakelists:print(" " .. _get_relative_unix_path(includedir, outputdir)) end cmakelists:print(")") end local includedirs_interface = target:get("includedirs", {interface = true}) if includedirs_interface then cmakelists:print("target_include_directories(%s INTERFACE", target:name()) for _, headerdir in ipairs(includedirs_interface) do cmakelists:print(" " .. _get_relative_unix_path(headerdir, outputdir)) end cmakelists:print(")") end end -- add target system include directories -- we disable system/external includes first, because cmake doesn’t seem to be able to support msvc /external:I -- https://github.com/xmake-io/xmake/issues/1050 function _add_target_sysinclude_directories(cmakelists, target, outputdir) local includedirs = _get_configs_from_target(target, "sysincludedirs") if #includedirs > 0 then cmakelists:print("target_include_directories(%s SYSTEM PRIVATE", target:name()) for _, includedir in ipairs(includedirs) do cmakelists:print(" " .. _get_relative_unix_path(includedir, outputdir)) end cmakelists:print(")") end local includedirs_interface = target:get("sysincludedirs", {interface = true}) if includedirs_interface then cmakelists:print("target_include_directories(%s SYSTEM INTERFACE", target:name()) for _, headerdir in ipairs(includedirs_interface) do cmakelists:print(" " .. _get_relative_unix_path(headerdir, outputdir)) end cmakelists:print(")") end end -- add target framework directories function _add_target_framework_directories(cmakelists, target, outputdir) local frameworkdirs = _get_configs_from_target(target, "frameworkdirs") if #frameworkdirs > 0 then cmakelists:print("target_compile_options(%s PRIVATE", target:name()) for _, frameworkdir in ipairs(frameworkdirs) do cmakelists:print(" $<$<COMPILE_LANGUAGE:C>:-F" .. _get_relative_unix_path(frameworkdir, outputdir) .. ">") cmakelists:print(" $<$<COMPILE_LANGUAGE:CXX>:-F" .. _get_relative_unix_path(frameworkdir, outputdir) .. ">") cmakelists:print(" $<$<COMPILE_LANGUAGE:OBJC>:-F" .. _get_relative_unix_path(frameworkdir, outputdir) .. ">") cmakelists:print(" $<$<COMPILE_LANGUAGE:OBJCXX>:-F" .. _get_relative_unix_path(frameworkdir, outputdir) .. ">") end cmakelists:print(")") local cmake_minver = _get_cmake_minver() if cmake_minver:ge("3.13.0") then cmakelists:print("target_link_options(%s PRIVATE", target:name()) else cmakelists:print("target_link_libraries(%s PRIVATE", target:name()) end for _, frameworkdir in ipairs(frameworkdirs) do cmakelists:print(" -F" .. _get_relative_unix_path(frameworkdir, outputdir)) end cmakelists:print(")") end local frameworkdirs_interface = target:get("frameworkdirs", {interface = true}) if frameworkdirs_interface then cmakelists:print("target_compile_options(%s PRIVATE", target:name()) for _, frameworkdir in ipairs(frameworkdirs_interface) do cmakelists:print(" $<$<COMPILE_LANGUAGE:C>:-F" .. _get_relative_unix_path(frameworkdir, outputdir) .. ">") cmakelists:print(" $<$<COMPILE_LANGUAGE:CXX>:-F" .. _get_relative_unix_path(frameworkdir, outputdir) .. ">") cmakelists:print(" $<$<COMPILE_LANGUAGE:OBJC>:-F" .. _get_relative_unix_path(frameworkdir, outputdir) .. ">") cmakelists:print(" $<$<COMPILE_LANGUAGE:OBJCXX>:-F" .. _get_relative_unix_path(frameworkdir, outputdir) .. ">") end cmakelists:print(")") end end -- add target compile definitions function _add_target_compile_definitions(cmakelists, target) local defines = _get_configs_from_target(target, "defines") if #defines > 0 then cmakelists:print("target_compile_definitions(%s PRIVATE", target:name()) for _, define in ipairs(defines) do cmakelists:print(" " .. define) end cmakelists:print(")") end end -- add target source files flags function _add_target_sourcefiles_flags(cmakelists, target, sourcefile, name, outputdir) local fileconfig = target:fileconfig(sourcefile) if fileconfig then local flags = _get_flags_from_fileconfig(fileconfig, outputdir, name) if flags and #flags > 0 then cmakelists:print("set_source_files_properties(" .. _get_relative_unix_path_to_cmake(sourcefile, outputdir) .. " PROPERTIES COMPILE_OPTIONS") local flagstrs = {} for _, flag in ipairs(flags) do if name == "cxxflags" then table.insert(flagstrs, "$<$<COMPILE_LANGUAGE:CXX>:" .. flag .. ">") elseif name == "cflags" then table.insert(flagstrs, "$<$<COMPILE_LANGUAGE:C>:" .. flag .. ">") elseif name == "cxflags" then table.insert(flagstrs, "$<$<COMPILE_LANGUAGE:C>:" .. flag .. ">") table.insert(flagstrs, "$<$<COMPILE_LANGUAGE:CXX>:" .. flag .. ">") elseif name == "cuflags" then table.insert(flagstrs, "$<$<COMPILE_LANGUAGE:CUDA>:" .. flag .. ">") end end cmakelists:print(" \"%s\"", table.concat(flagstrs, ";")) cmakelists:print(")") end end end -- add target compile options function _add_target_compile_options(cmakelists, target, outputdir) local cflags = _get_flags_from_target(target, "cflags") local cxflags = _get_flags_from_target(target, "cxflags") local cxxflags = _get_flags_from_target(target, "cxxflags") local cuflags = _get_flags_from_target(target, "cuflags") local toolnames = hashset.new() local function _add_target_compile_options_for_compiler(toolname) if #cflags > 0 or #cxflags > 0 or #cxxflags > 0 or #cuflags > 0 then cmakelists:print("target_compile_options(%s PRIVATE", target:name()) for _, flag in ipairs(_translate_flags(cflags, outputdir)) do local prefix prefix, flag = _split_flag_with_tool_prefix(flag) if prefix == toolname then flag = _escape_path_in_flag(target, flag) cmakelists:print(" $<$<COMPILE_LANGUAGE:C>:" .. flag .. ">") end if prefix then toolnames:insert(prefix) end end for _, flag in ipairs(_translate_flags(cxflags, outputdir)) do local prefix prefix, flag = _split_flag_with_tool_prefix(flag) if prefix == toolname then flag = _escape_path_in_flag(target, flag) cmakelists:print(" $<$<COMPILE_LANGUAGE:C>:" .. flag .. ">") cmakelists:print(" $<$<COMPILE_LANGUAGE:CXX>:" .. flag .. ">") end if prefix then toolnames:insert(prefix) end end for _, flag in ipairs(_translate_flags(cxxflags, outputdir)) do local prefix prefix, flag = _split_flag_with_tool_prefix(flag) if prefix == toolname then flag = _escape_path_in_flag(target, flag) cmakelists:print(" $<$<COMPILE_LANGUAGE:CXX>:" .. flag .. ">") end if prefix then toolnames:insert(prefix) end end for _, flag in ipairs(_translate_flags(cuflags, outputdir)) do local prefix prefix, flag = _split_flag_with_tool_prefix(flag) if prefix == toolname then flag = _escape_path_in_flag(target, flag) cmakelists:print(" $<$<COMPILE_LANGUAGE:CUDA>:" .. flag .. ">") end if prefix then toolnames:insert(prefix) end end cmakelists:print(")") end end _add_target_compile_options_for_compiler() local compilernames = { clang = "Clang", clangxx = "Clang", gcc = "Gcc", gxx = "Gcc", cl = "MSVC", link = "MSVC" } for _, toolname in toolnames:keys() do local name = compilernames[toolname] if name then cmakelists:print("if(%s)", name) _add_target_compile_options_for_compiler(toolname) cmakelists:print("endif()") end end -- add cflags/cxxflags for the specific source files local sourcebatches = target:sourcebatches() for _, sourcebatch in table.orderpairs(sourcebatches) do if _sourcebatch_is_built(sourcebatch) then for _, sourcefile in ipairs(sourcebatch.sourcefiles) do _add_target_sourcefiles_flags(cmakelists, target, sourcefile, "cxxflags", outputdir) _add_target_sourcefiles_flags(cmakelists, target, sourcefile, "cflags", outputdir) _add_target_sourcefiles_flags(cmakelists, target, sourcefile, "cxflags", outputdir) _add_target_sourcefiles_flags(cmakelists, target, sourcefile, "cuflags", outputdir) end end end end -- add target values function _add_target_values(cmakelists, target, name) local values = target:get(name) if values then if name:endswith("s") then name = name:sub(1, #name - 1) end cmakelists:print("if(MSVC)") local flags_cl = _map_compflags("cl", "c", name, values) for _, flag in ipairs(flags_cl) do cmakelists:print(" target_compile_options(%s PRIVATE %s)", target:name(), flag) end cmakelists:print("elseif(Clang)") local flags_clang = _map_compflags("clang", "c", name, values) for _, flag in ipairs(flags_clang) do cmakelists:print(" target_compile_options(%s PRIVATE %s)", target:name(), flag) end cmakelists:print("elseif(Gcc)") local flags_gcc = _map_compflags("gcc", "c", name, values) for _, flag in ipairs(flags_gcc) do cmakelists:print(" target_compile_options(%s PRIVATE %s)", target:name(), flag) end cmakelists:print("endif()") end end -- add target warnings function _add_target_warnings(cmakelists, target) _add_target_values(cmakelists, target, "warnings") end -- add target encodings function _add_target_encodings(cmakelists, target) _add_target_values(cmakelists, target, "encodings") end -- add target exceptions function _add_target_exceptions(cmakelists, target) local exceptions = target:get("exceptions") if exceptions then if exceptions == "none" then cmakelists:print("string(REPLACE \"/EHsc\" \"\" CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS}\")") else _add_target_values(cmakelists, target, "exceptions") end end end -- add target languages function _add_target_languages(cmakelists, target) local features = { c89 = "c_std_90" , c99 = "c_std_99" , c11 = "c_std_11" , c17 = "c_std_17" , c23 = "c_std_23" , clatest = "c_std_latest" , cxx98 = "cxx_std_98" , cxx11 = "cxx_std_11" , cxx14 = "cxx_std_14" , cxx17 = "cxx_std_17" , cxx20 = "cxx_std_20" , cxx23 = "cxx_std_23" , cxx26 = "cxx_std_26" , cxxlatest = "cxx_std_latest" } local languages = target:get("languages") if languages then for _, lang in ipairs(languages) do local has_ext = false -- c | c++ | gnu | gnu++ local flag = lang:replace('xx', '++'):replace('latest', ''):gsub('%d', '') if lang:startswith("gnu") then lang = 'c' .. lang:sub(4) has_ext = true end local feature = features[lang] or (features[lang:replace("++", "xx")]) if feature then cmakelists:print("set_target_properties(%s PROPERTIES %s_EXTENSIONS %s)", target:name(), flag:endswith('++') and 'CXX' or 'C', has_ext and "ON" or "OFF") if feature:endswith('_latest') then if flag:endswith('++') then cmakelists:print('foreach(standard 26 23 20 17 14 11 98)') cmakelists:print(' include(CheckCXXCompilerFlag)') cmakelists:print(' if(MSVC)') cmakelists:print(' check_cxx_compiler_flag("/std:%s${standard}" %s_support_%s_standard_${standard})', flag, target:name(), flag) cmakelists:print(' else()') cmakelists:print(' check_cxx_compiler_flag("-std=%s${standard}" %s_support_%s_standard_${standard})', flag, target:name(), flag) cmakelists:print(' endif()') cmakelists:print(' if(%s_support_%s_standard_${standard})', target:name(), flag) cmakelists:print(' target_compile_features(%s PRIVATE cxx_std_${standard})', target:name()) cmakelists:print(' break()') cmakelists:print(' endif()') cmakelists:print('endforeach()') else cmakelists:print('foreach(standard 23 17 11 99 90)') cmakelists:print(' include(CheckCCompilerFlag)') cmakelists:print(' if(MSVC)') cmakelists:print(' check_c_compiler_flag("/std:%s${standard}" %s_support_%s_standard_${standard})', flag, target:name(), flag) cmakelists:print(' else()') cmakelists:print(' check_c_compiler_flag("-std=%s${standard}" %s_support_%s_standard_${standard})', flag, target:name(), flag) cmakelists:print(' endif()') cmakelists:print(' if(%s_support_%s_standard_${standard})', target:name(), flag) cmakelists:print(' target_compile_features(%s PRIVATE c_std_${standard})', target:name()) cmakelists:print(' break()') cmakelists:print(' endif()') cmakelists:print('endforeach()') end else cmakelists:print('target_compile_features(%s PRIVATE %s)', target:name(), feature) end end end end end -- add target optimization function _add_target_optimization(cmakelists, target) local flags_gcc = { none = "-O0" , fast = "-O1" , faster = "-O2" , fastest = "-O3" , smallest = "-Os" , aggressive = "-Ofast" } local flags_msvc = { none = "$<$<CONFIG:Debug>:-Od>" , faster = "$<$<CONFIG:Release>:-Ox>" , fastest = "$<$<CONFIG:Release>:-O2>" , smallest = "$<$<CONFIG:Release>:-O1>" , aggressive = "$<$<CONFIG:Release>:-O2>" } local optimization = target:get("optimize") if optimization then cmakelists:print("if(MSVC)") cmakelists:print(" target_compile_options(%s PRIVATE %s)", target:name(), flags_msvc[optimization]) cmakelists:print("else()") cmakelists:print(" target_compile_options(%s PRIVATE %s)", target:name(), flags_gcc[optimization]) cmakelists:print("endif()") end end -- add target symbols function _add_target_symbols(cmakelists, target) local symbols = target:get("symbols") if symbols then local flags_gcc = {} local flags_msvc = {} local levels = hashset.from(table.wrap(symbols)) if levels:has("debug") then table.insert(flags_gcc, "-g") if levels:has("edit") then table.insert(flags_msvc, "-ZI") elseif levels:has("embed") then table.insert(flags_msvc, "-Z7") else table.insert(flags_msvc, "-Zi") end end if levels:has("hidden") then table.insert(flags_gcc, "-fvisibility=hidden") end cmakelists:print("if(MSVC)") if #flags_msvc > 0 then cmakelists:print(" target_compile_options(%s PRIVATE %s)", target:name(), table.concat(flags_msvc, " ")) end cmakelists:print("else()") if #flags_gcc > 0 then cmakelists:print(" target_compile_options(%s PRIVATE %s)", target:name(), table.concat(flags_gcc, " ")) end cmakelists:print("endif()") end end -- add target runtimes -- -- https://github.com/xmake-io/xmake/issues/1661#issuecomment-927979489 -- https://cmake.org/cmake/help/latest/prop_tgt/MSVC_RUNTIME_LIBRARY.html -- function _add_target_runtimes(cmakelists, target) local cmake_minver = _get_cmake_minver() if cmake_minver:ge("3.15.0") then local runtimes = target:get("runtimes") cmakelists:print("if(MSVC)") if runtimes then if runtimes == "MT" then runtimes = "MultiThreaded" elseif runtimes == "MTd" then runtimes = "MultiThreadedDebug" elseif runtimes == "MD" then runtimes = "MultiThreadedDLL" elseif runtimes == "MDd" then runtimes = "MultiThreadedDebugDLL" end else runtimes = "MultiThreaded$<$<CONFIG:Debug>:Debug>" end cmakelists:print(' set_property(TARGET %s PROPERTY', target:name()) cmakelists:print(' MSVC_RUNTIME_LIBRARY "%s")', runtimes) cmakelists:print("endif()") end end -- add target link libraries function _add_target_link_libraries(cmakelists, target, outputdir) -- add links local links = _get_configs_from_target(target, "links") local syslinks = _get_configs_from_target(target, "syslinks") local frameworks = _get_configs_from_target(target, "frameworks") if #frameworks > 0 then for _, framework in ipairs(frameworks) do table.insert(links, "\"-framework " .. framework .. "\"") end end table.join2(links, syslinks) if #links > 0 then cmakelists:print("target_link_libraries(%s PRIVATE", target:name()) for _, link in ipairs(links) do cmakelists:print(" " .. link) end cmakelists:print(")") end -- get c++ modules rules local cxxmodules_rules if _can_native_support_for_cxxmodules() then cxxmodules_rules = _get_cxxmodules_rules() end if cxxmodules_rules then cxxmodules_rules = hashset.from(cxxmodules_rules) else cxxmodules_rules = hashset.new() end -- add other object files, maybe from custom rules local objectfiles_set = hashset.new() local sourcebatches = target:sourcebatches() for _, sourcebatch in table.orderpairs(sourcebatches) do if _sourcebatch_is_built(sourcebatch) or cxxmodules_rules:has(sourcebatch.rulename) then for _, objectfile in ipairs(sourcebatch.objectfiles) do objectfiles_set:insert(objectfile) end end end if #target:objectfiles() > objectfiles_set:size() then cmakelists:print("target_link_libraries(%s PRIVATE", target:name()) for _, objectfile in ipairs(target:objectfiles()) do if not objectfiles_set:has(objectfile) then cmakelists:print(" " .. _get_relative_unix_path_to_cmake(objectfile, outputdir)) end end cmakelists:print(")") end end -- add target link directories function _add_target_link_directories(cmakelists, target, outputdir) local linkdirs = _get_configs_from_target(target, "linkdirs") if #linkdirs > 0 then local cmake_minver = _get_cmake_minver() if cmake_minver:ge("3.13.0") then cmakelists:print("target_link_directories(%s PRIVATE", target:name()) for _, linkdir in ipairs(linkdirs) do cmakelists:print(" " .. _get_relative_unix_path(linkdir, outputdir)) end cmakelists:print(")") else cmakelists:print("if(MSVC)") cmakelists:print(" target_link_libraries(%s PRIVATE", target:name()) for _, linkdir in ipairs(linkdirs) do cmakelists:print(" -libpath:" .. _get_relative_unix_path(linkdir, outputdir)) end cmakelists:print(" )") cmakelists:print("else()") cmakelists:print(" target_link_libraries(%s PRIVATE", target:name()) for _, linkdir in ipairs(linkdirs) do cmakelists:print(" -L" .. _get_relative_unix_path(linkdir, outputdir)) end cmakelists:print(" )") cmakelists:print("endif()") end end end -- add target link options function _add_target_link_options(cmakelists, target, outputdir) local ldflags = _get_flags_from_target(target, "ldflags") local shflags = _get_flags_from_target(target, "shflags") local toolnames = hashset.new() local function _add_target_link_options_for_linker(toolname) if #ldflags > 0 or #shflags > 0 then local flags = {} for _, flag in ipairs(table.unique(table.join(ldflags, shflags))) do table.insert(flags, _translate_flag(flag, outputdir)) end if #flags > 0 then local cmake_minver = _get_cmake_minver() if cmake_minver:ge("3.13.0") then cmakelists:print("target_link_options(%s PRIVATE", target:name()) else cmakelists:print("target_link_libraries(%s PRIVATE", target:name()) end for _, flag in ipairs(flags) do local prefix prefix, flag = _split_flag_with_tool_prefix(flag) if prefix == toolname then flag = _escape_path_in_flag(target, flag) -- @see https://github.com/xmake-io/xmake/issues/4196 if cmake_minver:ge("3.12.0") and #os.argv(flag) > 1 then cmakelists:print(" " .. os.args("SHELL:" .. flag)) else cmakelists:print(" " .. flag) end end if prefix then toolnames:insert(prefix) end end cmakelists:print(")") end end end _add_target_link_options_for_linker() local linkernames = { clang = "Clang", clangxx = "Clang", gcc = "Gcc", gxx = "Gcc", cl = "MSVC", link = "MSVC" } for _, toolname in toolnames:keys() do local name = linkernames[toolname] if name then cmakelists:print("if(%s)", name) _add_target_link_options_for_linker(toolname) cmakelists:print("endif()") end end end -- get command string function _get_command_string(cmd, outputdir) local kind = cmd.kind local opt = cmd.opt if cmd.program then -- @see https://github.com/xmake-io/xmake/discussions/2156 local argv = {} for _, v in ipairs(cmd.argv) do table.insert(argv, _translate_flag(v, outputdir)) end local command = _escape_path(cmd.program) .. " " .. os.args(argv) if opt and opt.curdir then command = "${CMAKE_COMMAND} -E chdir " .. _get_relative_unix_path_to_cmake(opt.curdir, outputdir) .. " " .. command end return command elseif kind == "cp" then if os.isdir(cmd.srcpath) then return string.format("${CMAKE_COMMAND} -E copy_directory %s %s", _get_relative_unix_path_to_cmake(cmd.srcpath, outputdir), _get_relative_unix_path_to_cmake(cmd.dstpath, outputdir)) else return string.format("${CMAKE_COMMAND} -E copy %s %s", _get_relative_unix_path_to_cmake(cmd.srcpath, outputdir), _get_relative_unix_path_to_cmake(cmd.dstpath, outputdir)) end elseif kind == "rm" then return string.format("${CMAKE_COMMAND} -E rm -rf %s", _get_relative_unix_path_to_cmake(cmd.filepath, outputdir)) elseif kind == "rmdir" then return string.format("${CMAKE_COMMAND} -E rm -rf %s", _get_relative_unix_path_to_cmake(cmd.dir, outputdir)) elseif kind == "mv" then return string.format("${CMAKE_COMMAND} -E rename %s %s", _get_relative_unix_path_to_cmake(cmd.srcpath, outputdir), _get_relative_unix_path_to_cmake(cmd.dstpath, outputdir)) elseif kind == "cd" then return string.format("cd %s", _get_relative_unix_path_to_cmake(cmd.dir, outputdir)) elseif kind == "mkdir" then return string.format("${CMAKE_COMMAND} -E make_directory %s", _get_relative_unix_path_to_cmake(cmd.dir, outputdir)) elseif kind == "show" then return string.format("echo %s", colors.ignore(cmd.showtext)) end end -- add target custom commands for batchcmds function _add_target_custom_commands_for_batchcmds(cmakelists, target, outputdir, suffix, cmds) if #cmds == 0 then return end if suffix == "before" then -- ADD_CUSTOM_COMMAND and PRE_BUILD did not work as I expected, -- so we need to use add_dependencies and fake target to support it. -- -- @see https://gitlab.kitware.com/cmake/cmake/-/issues/17802 -- local key = target:name() .. "_" .. hash.uuid():split("-", {plain = true})[1] cmakelists:print("add_custom_command(OUTPUT output_%s", key) for _, cmd in ipairs(cmds) do local command = _get_command_string(cmd, outputdir) if command then cmakelists:print(" COMMAND %s", command) end end cmakelists:print(" VERBATIM") cmakelists:print(")") cmakelists:print("add_custom_target(target_%s", key) cmakelists:print(" DEPENDS output_%s", key) cmakelists:print(")") cmakelists:print("add_dependencies(%s target_%s)", target:name(), key) elseif suffix == "after" then cmakelists:print("add_custom_command(TARGET %s", target:name()) cmakelists:print(" POST_BUILD") for _, cmd in ipairs(cmds) do local command = _get_command_string(cmd, outputdir) if command then cmakelists:print(" COMMAND %s", command) end end cmakelists:print(" VERBATIM") cmakelists:print(")") end end -- add target custom commands function _add_target_custom_commands(cmakelists, target, outputdir) -- build sourcebatch groups first local sourcegroups = rule_groups.build_sourcebatch_groups(target, target:sourcebatches()) -- ignore c++ modules rules local ignored_rules if _can_native_support_for_cxxmodules() then ignored_rules = _get_cxxmodules_rules() end -- add before commands -- we use irpairs(groups), because the last group that should be given the highest priority. local cmds_before = {} target_cmds.get_target_buildcmd(target, cmds_before, {suffix = "before", ignored_rules = ignored_rules}) target_cmds.get_target_buildcmd_sourcegroups(target, cmds_before, sourcegroups, {suffix = "before", ignored_rules = ignored_rules}) -- rule.on_buildcmd_files should also be executed before building the target, as cmake PRE_BUILD does not work. target_cmds.get_target_buildcmd_sourcegroups(target, cmds_before, sourcegroups, {ignored_rules = ignored_rules}) _add_target_custom_commands_for_batchcmds(cmakelists, target, outputdir, "before", cmds_before) -- add after commands local cmds_after = {} target_cmds.get_target_buildcmd_sourcegroups(target, cmds_after, sourcegroups, {suffix = "after", ignored_rules = ignored_rules}) target_cmds.get_target_buildcmd(target, cmds_after, {suffix = "after", ignored_rules = ignored_rules}) _add_target_custom_commands_for_batchcmds(cmakelists, target, outputdir, "after", cmds_after) end -- add target function _add_target(cmakelists, target, outputdir) -- add comment cmakelists:print("# target") -- is phony target? if target:is_phony() then return _add_target_phony(cmakelists, target) elseif target:is_binary() then _add_target_binary(cmakelists, target, outputdir) elseif target:is_static() then _add_target_static(cmakelists, target, outputdir) elseif target:is_shared() then _add_target_shared(cmakelists, target, outputdir) elseif target:is_headeronly() then _add_target_headeronly(cmakelists, target) _add_target_include_directories(cmakelists, target, outputdir) return elseif target:is_moduleonly() then _add_target_moduleonly(cmakelists, target) return else raise("unknown target kind %s", target:kind()) end -- add target dependencies _add_target_dependencies(cmakelists, target) -- add target custom commands -- we need to call it first for running all rules, these rules will change some flags, e.g. c++modules _add_target_custom_commands(cmakelists, target, outputdir) -- add target precompilied header _add_target_precompiled_header(cmakelists, target, outputdir) -- add target include directories _add_target_include_directories(cmakelists, target, outputdir) -- add target system include directories _add_target_sysinclude_directories(cmakelists, target, outputdir) -- add target framework directories _add_target_framework_directories(cmakelists, target, outputdir) -- add target compile definitions _add_target_compile_definitions(cmakelists, target) -- add target compile options _add_target_compile_options(cmakelists, target, outputdir) -- add target warnings _add_target_warnings(cmakelists, target) -- add target exceptions _add_target_encodings(cmakelists, target) -- add target exceptions _add_target_exceptions(cmakelists, target) -- add target languages _add_target_languages(cmakelists, target) -- add target optimization _add_target_optimization(cmakelists, target) -- add target symbols _add_target_symbols(cmakelists, target) -- add target runtimes _add_target_runtimes(cmakelists, target) -- add target link libraries _add_target_link_libraries(cmakelists, target, outputdir) -- add target link directories _add_target_link_directories(cmakelists, target, outputdir) -- add target link options _add_target_link_options(cmakelists, target, outputdir) -- add target sources _add_target_sources(cmakelists, target, outputdir) -- add target source groups _add_target_source_groups(cmakelists, target, outputdir) -- end cmakelists:print("") end -- generate cmakelists function _generate_cmakelists(cmakelists, outputdir) -- add project info _add_project(cmakelists, outputdir) -- add targets for _, target in table.orderpairs(project.targets()) do _add_target(cmakelists, target, outputdir) end end -- make function make(outputdir) -- enter project directory local oldir = os.cd(os.projectdir()) -- open the cmakelists local cmakelists = io.open(path.join(outputdir, "CMakeLists.txt"), "w") -- generate cmakelists _generate_cmakelists(cmakelists, outputdir) -- close the cmakelists cmakelists:close() -- leave project directory os.cd(oldir) end
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/macro/main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.project.config") import("core.cache.localcache") -- the macro directories function _directories() return { path.join(config.directory(), "macros") , path.join(os.scriptdir(), "macros")} end -- the macro directory function _directory(macroname) -- find macro directory local macrodir = nil for _, dir in ipairs(_directories()) do -- found? if os.isfile(path.join(dir, macroname .. ".lua")) then macrodir = dir break end end -- check assert(macrodir, "macro(%s) not found!", macroname) return macrodir end -- the readable macro file function _rfile(macroname) if macroname == '.' then macroname = "anonymous" end return path.join(_directory(macroname), macroname .. ".lua") end -- the writable macro file function _wfile(macroname) if macroname == '.' then macroname = "anonymous" end return path.join(path.join(config.directory(), "macros"), macroname .. ".lua") end -- get all macros function macros(anonymousname) local results = {} -- find all macros for _, dir in ipairs(_directories()) do local macrofiles = os.match(path.join(dir, "*.lua")) for _, macrofile in ipairs(macrofiles) do -- get macro name local macroname = path.basename(macrofile) if macroname == "anonymous" and anonymousname then macroname = anonymousname end table.insert(results, macroname) end end return results end -- list macros function _list() cprint("${bright}macros:") for _, macroname in ipairs(macros(".<anonymous>")) do print(" " .. macroname) end end -- show macro function _show(macroname) local file = _rfile(macroname) if os.isfile(file) then io.cat(file) else raise("macro(%s) not found!", macroname) end end -- clear all macros function _clear() os.rm(path.join(config.directory(), "macros")) end -- delete macro function _delete(macroname) -- remove it if os.isfile(_wfile(macroname)) then os.rm(_wfile(macroname)) elseif os.isfile(_rfile(macroname)) then raise("macro(%s) cannot be deleted!", macroname) else raise("macro(%s) not found!", macroname) end -- trace cprint("${color.success}delete macro(%s) ok!", macroname) end -- import macro function _import(macrofile, macroname) -- import all macros if os.isdir(macrofile) then -- the macro directory local macrodir = macrofile local macrofiles = os.match(path.join(macrodir, "*.lua")) for _, macrofile in ipairs(macrofiles) do -- the macro name macroname = path.basename(macrofile) -- import it os.cp(macrofile, _wfile(macroname)) -- trace cprint("${color.success}import macro(%s) ok!", macroname) end else -- import it os.cp(macrofile, _wfile(macroname)) -- trace cprint("${color.success}import macro(%s) ok!", macroname) end end -- export macro function _export(macrofile, macroname) -- export all macros if os.isdir(macrofile) then -- the output directory local outputdir = macrofile -- export all macros for _, dir in ipairs(_directories()) do local macrofiles = os.match(path.join(dir, "*.lua")) for _, macrofile in ipairs(macrofiles) do -- export it os.cp(macrofile, outputdir) -- trace cprint("${color.success}export macro(%s) ok!", path.basename(macrofile)) end end else -- export it os.cp(_rfile(macroname), macrofile) -- trace cprint("${color.success}export macro(%s) ok!", macroname) end end -- begin to record macro function _begin() localcache.set("history", "cmdlines", "__macro_begin__") localcache.save("history") end -- end to record macro function _end(macroname) -- load the history: cmdlines local cmdlines = table.wrap(localcache.get("history", "cmdlines")) -- get the last macro block local begin = false local block = {} local total = #cmdlines local index = total while index ~= 0 do -- the command line local cmdline = cmdlines[index] -- found begin? break it if cmdline == "__macro_begin__" then begin = true break end -- found end? break it if cmdline == "__macro_end__" then break end -- ignore "xmake m .." and "xmake macro .." if not cmdline:find("xmake%s+macro%s*") and not cmdline:find("xmake%s+m%s*") then -- save this command line to block table.insert(block, 1, cmdline) end -- the previous line index = index - 1 end -- the begin tag not found? if not begin then raise("please run: 'xmake macro --begin' first!") end -- patch end tag to the history: cmdlines table.insert(cmdlines, "__macro_end__") localcache.set("history", "cmdlines", cmdlines) localcache.save("history") -- open the macro file local file = io.open(_wfile(macroname), "w") -- save the macro begin file:print("function main(argv)") -- save the macro block for _, cmdline in ipairs(block) do file:print(" os.exec(\"%s\")", (cmdline:gsub("[\\\"]", function (w) return "\\" .. w end))) end -- save the macro end file:print("end") -- exit the macro file file:close() -- show this macro _show(macroname) -- trace cprint("${color.success}define macro(%s) ok!", macroname) end -- run macro function _run(macroname) -- run last command? if macroname == ".." then -- load the history: cmdlines local cmdlines = localcache.get("history", "cmdlines") -- get the last command local lastcmd = nil if cmdlines then local total = #cmdlines local index = total while index ~= 0 do -- ignore "xmake m .." and "xmake macro .." local cmdline = cmdlines[index] if not cmdline:startswith("__macro_") and not cmdline:find("xmake%s+macro%s*") and not cmdline:find("xmake%s+m%s*") then lastcmd = cmdline break end -- the previous line index = index - 1 end end -- run the last command if lastcmd then os.exec(lastcmd) end return end -- is anonymous? if macroname == '.' then macroname = "anonymous" end -- run macro import(macroname, {rootdir = _directory(macroname), anonymous = true})(option.get("arguments") or {}) end -- main function main() -- list macros if option.get("list") then _list() -- show macro elseif option.get("show") then _show(option.get("name")) -- clear macro elseif option.get("clear") then _clear() -- delete macro elseif option.get("delete") then _delete(option.get("name")) -- import macro elseif option.get("import") then _import(option.get("import"), option.get("name")) -- export macro elseif option.get("export") then _export(option.get("export"), option.get("name")) -- begin to record macro elseif option.get("begin") then _begin() -- end to record macro elseif option.get("end") then _end(option.get("name")) -- run macro else _run(option.get("name")) end end
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/macro/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 macro.lua -- -- define task task("macro") -- set category set_category("plugin") -- on run on_run("main") -- set menu set_menu { -- usage usage = "xmake macro|m [options] [name] [arguments]" -- description , description = "Run the given macro." -- xmake m , shortname = 'm' -- options , options = { {'b', "begin", "k", nil, "Start to record macro." , "e.g." , "Record macro with name: test" , " xmake macro --begin" , " xmake config --plat=macosx" , " xmake clean" , " xmake -r" , " xmake package" , " xmake macro --end test" } , {'e', "end", "k", nil, "Stop to record macro." } , {} , {nil, "show", "k", nil, "Show the content of the given macro." } , {'l', "list", "k", nil, "List all macros." } , {'d', "delete", "k", nil, "Delete the given macro." } , {'c', "clear", "k", nil, "Clear the all macros." } , {} , {nil, "import", "kv", nil, "Import the given macro file or directory." , "e.g." , " xmake macro --import=/xxx/macro.lua test" , " xmake macro --import=/xxx/macrodir" } , {nil, "export", "kv", nil, "Export the given macro to file or directory." , "e.g." , " xmake macro --export=/xxx/macro.lua test" , " xmake macro --export=/xxx/macrodir" } , {} , {nil, "name", "v", ".", "Set the macro name." , "e.g." , " Run the given macro: xmake macro test" , " Run the anonymous macro: xmake macro ." , " Run the last command: xmake macro .." , values = function (complete, opt) -- hide in help menu if not complete then return end -- don't need name if opt.begin or opt.list or opt.clear then return end -- name should be given by user if opt["end"] or opt.import then return end return import("main.macros")(".") end } , {nil, "arguments", "vs", nil, "Set the macro arguments." } } }
0
repos/xmake/xmake/plugins/macro
repos/xmake/xmake/plugins/macro/macros/package.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file package.lua -- -- imports import("core.base.option") import("core.project.config") import("core.project.project") import("core.platform.platform") -- the options local options = { {'p', "plat", "kv", os.host(), "Set the platform." } , {'a', "arch", "kv", nil, "Set the architectures. e.g. 'armv7, arm64'" } , {'f', "config", "kv", nil, "Pass the config arguments to \"xmake config\" .." } , {'o', "outputdir", "kv", nil, "Set the output directory of the package." } , {nil, "target", "v", nil, "The target name. It will package all default targets if this parameter is not specified."} } -- package all -- -- e.g. -- xmake m package -- xmake m package -f "-m debug" -- xmake m package -p linux -- xmake m package -p iphoneos -f "-m debug --xxx ..." -o /tmp/xxx -- xmake m package -f \"--mode=debug\" -- function main(argv) -- parse arguments local args = option.parse(argv, options, "Package all architectures for the given the platform." , "" , "Usage: xmake macro package [options]") -- package all archs local plat = args.plat local archs = args.arch and args.arch:split(',') or platform.archs(plat) for _, arch in ipairs(archs) do local argv = {"f", "-cy", "-p", plat, "-a", arch} if args.config then table.join2(argv, os.argv(args.config)) end if option.get("verbose") then table.insert(argv, "-v") end if option.get("diagnosis") then table.insert(argv, "-D") end os.execv(os.programfile(), argv) argv = {"p", "-f", "oldpkg"} if args.outputdir then table.insert(argv, "-o") table.insert(argv, args.outputdir) end if option.get("verbose") then table.insert(argv, "-v") end if option.get("diagnosis") then table.insert(argv, "-D") end if option.get("target") then table.insert(argv, option.get("target")) end os.execv(os.programfile(), argv) end -- package universal for iphoneos, watchos ... if plat == "iphoneos" or plat == "watchos" or plat == "macosx" then config.load() os.cd(project.directory()) local outputdir = args.outputdir or config.get("buildir") local targets = {} if option.get("target") then local target = project.target(option.get("target")) if target then table.insert(targets, target) end else for _, target in pairs(project.targets()) do table.insert(targets, target) end end for _, target in ipairs(targets) do local modes = {} for _, modedir in ipairs(os.dirs(format("%s/%s.pkg/*/*/lib/*", outputdir, target:name()))) do table.insert(modes, path.basename(modedir)) end for _, mode in ipairs(table.unique(modes)) do local lipoargs = nil for _, arch in ipairs(archs) do local archfile = format("%s/%s.pkg/%s/%s/lib/%s/%s", outputdir, target:name(), plat, arch:trim(), mode, path.filename(target:targetfile())) if os.isfile(archfile) then lipoargs = format("%s -arch %s %s", lipoargs or "", arch, archfile) end end if lipoargs then lipoargs = format("-create %s -output %s/%s.pkg/%s/universal/lib/%s/%s", lipoargs, outputdir, target:name(), plat, mode, path.filename(target:targetfile())) os.mkdir(format("%s/%s.pkg/%s/universal/lib/%s", outputdir, target:name(), plat, mode)) os.execv(os.programfile(), {"l", "lipo", lipoargs}) end end end end end
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/lua/main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.sandbox.module") import("core.sandbox.sandbox") import("core.project.project") -- get all lua scripts function scripts() local names = {} local files = os.files(path.join(os.scriptdir(), "scripts/*.lua")) for _, file in ipairs(files) do table.insert(names, path.basename(file)) end return names end -- list all lua scripts function _list() print("scripts:") for _, file in ipairs(scripts()) do print(" " .. file) end end -- print verbose log function _print_vlog(script_type, script_name, args) if not option.get("verbose") then return end cprintf("running %s ${underline}%s${reset}", script_type, script_name) if args.n > 0 then print(" with args:") if not option.get("diagnosis") then for i = 1, args.n do print(" - " .. todisplay(args[i])) end else utils.dump(table.unpack(args, 1, args.n)) end else print(".") end end function _run_commanad(command, args) local tmpfile = os.tmpfile() .. ".lua" io.writefile(tmpfile, "function main(...)\n" .. command .. "\nend") return _run_script(tmpfile, args) end function _is_callable(func) if type(func) == "function" then return true elseif type(func) == "table" then local meta = debug.getmetatable(func) if meta and meta.__call then return true end end end function _run_script(script, args) local func local printresult = false local script_type, script_name -- import and run script if path.extension(script) == ".lua" and os.isfile(script) then -- run the given lua script file (xmake lua /tmp/script.lua) script_type, script_name = "given lua script file", path.relative(script) func = import(path.basename(script), {rootdir = path.directory(script), anonymous = true}) elseif os.isfile(path.join(os.scriptdir(), "scripts", script .. ".lua")) then -- run builtin lua script (xmake lua echo "hello xmake") script_type, script_name = "builtin lua script", script func = import("scripts." .. script, {anonymous = true}) else -- attempt to find the builtin module local object = nil for _, name in ipairs(script:split("%.")) do object = object and object[name] or module.get(name) if not object then break end end if object then -- run builtin modules (xmake lua core.xxx.xxx) script_type, script_name = "builtin module", script func = object else -- run imported modules (xmake lua core.xxx.xxx) script_type, script_name = "imported module", script func = import(script, {anonymous = true}) end printresult = true end -- print verbose log _print_vlog(script_type or "script", script_name or "", args) -- dump func() result if _is_callable(func) then local result = table.pack(func(table.unpack(args, 1, args.n))) if printresult and result and result.n ~= 0 then utils.dump(table.unpack(result, 1, result.n)) end else -- dump variables directly utils.dump(func) end end function _get_args() -- get arguments local args = option.get("arguments") or {} args.n = #args -- get deserialize tag local deserialize = option.get("deserialize") if not deserialize then return args end deserialize = tostring(deserialize) -- deserialize prefixed arguments for i, value in ipairs(args) do if value:startswith(deserialize) then local v, err = string.deserialize(value:sub(#deserialize + 1)) if err then raise(err) else args[i] = v end end end return args end function main() -- restore to the current working directory os.cd(os.workingdir()) -- list builtin scripts if option.get("list") then return _list() end -- run command? local script = option.get("script") if option.get("command") and script then return _run_commanad(script, _get_args()) end -- get script if script then return _run_script(script, _get_args()) end -- enter interactive mode sandbox.interactive() end
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/lua/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 task task("lua") -- set category set_category("plugin") -- on run on_run("main") -- set menu set_menu { -- usage usage = "xmake lua|l [options] [script] [arguments]" -- description , description = "Run the lua script." -- xmake l , shortname = 'l' -- options , options = { {'l', "list" , "k" , nil , "List all scripts." } , {'c', "command" , "k" , nil , "Run script as command" } , {'d', "deserialize" , "kv" , nil , "Deserialize arguments starts with given prefix" } , {nil, "script" , "v" , nil , "Run the given lua script name, file or module and enter interactive mode if no given script.", "e.g.", " - xmake lua (enter interactive mode)", " - xmake lua /tmp/script.lua", " - xmake lua echo 'hello xmake'", " - xmake lua core.xxx.xxx", " - xmake lua -c 'print(...)' hello xmake!" , values = function (complete, opt) if not complete or opt.command or opt.list then return end local list = import("main.scripts")() if list and complete then local result = {} for _, item in ipairs(list) do if item:startswith(complete) then table.insert(result, item) end end if #result > 0 then return result end end -- we just return nil and fallback to system autocomplete -- it will complete file path, e.g. `xmake l scripts/test.lua` end } , {nil, "arguments" , "vs" , nil , "The script arguments, use '--deserialize' option to enable deserializing.", "e.g.", " - xmake lua -d@ lib.detect.find_tool tar @{version=true}" } } }
0
repos/xmake/xmake/plugins/lua
repos/xmake/xmake/plugins/lua/scripts/cat.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file cat.lua -- -- main function main(...) for _, v in ipairs(table.pack(...)) do if os.isfile(v) then io.cat(v) end end print("") end
0
repos/xmake/xmake/plugins/lua
repos/xmake/xmake/plugins/lua/scripts/rm.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file rm.lua -- -- main function main(...) os.rm(...) end
0
repos/xmake/xmake/plugins/lua
repos/xmake/xmake/plugins/lua/scripts/time.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file time.lua -- -- main function main(...) local argv = {...} local program = argv[1] if program then local t = os.mclock() os.execv(program, table.slice(argv, 2)) t = os.mclock() - t print("time %0.3fs", t / 1000.) else raise("program not found!") end end
0
repos/xmake/xmake/plugins/lua
repos/xmake/xmake/plugins/lua/scripts/rmdir.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file rmdir.lua -- -- main function main(...) os.rmdir(...) end
0
repos/xmake/xmake/plugins/lua
repos/xmake/xmake/plugins/lua/scripts/echo.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file echo.lua -- -- main function main(...) for _, v in ipairs(table.pack(...)) do printf("%s ", v) end print("") end
0
repos/xmake/xmake/plugins/lua
repos/xmake/xmake/plugins/lua/scripts/mkdir.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file mkdir.lua -- -- main function main(...) os.mkdir(...) end
0
repos/xmake/xmake/plugins/lua
repos/xmake/xmake/plugins/lua/scripts/lipo.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file lipo.lua -- -- imports import("detect.tools.find_lipo") -- main -- -- e.g.. -- -- xmake l lipo "-create -arch armv7 file -arch arm64 file -output file" function main(...) -- get arguments local args = {...} if not args or #args ~= 1 then raise("invalid arguments!") end args = args[1] -- find the lipo local lipo = find_lipo() assert(lipo, "lipo not found!") -- run it os.run("%s %s", lipo, args) end
0
repos/xmake/xmake/plugins/lua
repos/xmake/xmake/plugins/lua/scripts/cp.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file cp.lua -- -- main function main(...) os.cp(...) end
0
repos/xmake/xmake/plugins/lua
repos/xmake/xmake/plugins/lua/scripts/mv.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file mv.lua -- -- main function mv.main(...) os.mv(...) end
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/watch/main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.base.fwatcher") import("core.project.config") -- add watchdir function _add_watchdir(watchdir, opt) opt = opt or {} cprint("watching ${bright}%s/%s${clear} ..", watchdir, opt.recursion and "**" or "*") fwatcher.add(watchdir, opt) end -- add watchdirs function _add_watchdirs() local watchdirs = option.get("watchdirs") local plaindirs = option.get("plaindirs") if watchdirs or plaindirs then if watchdirs then for _, watchdir in ipairs(path.splitenv(watchdirs)) do for _, dir in ipairs(os.dirs(watchdir)) do _add_watchdir(dir, {recursion = true}) end end end if plaindirs then for _, watchdir in ipairs(path.splitenv(plaindirs)) do for _, dir in ipairs(os.dirs(watchdir)) do _add_watchdir(dir) end end end elseif os.isfile(os.projectfile()) then watchdirs = os.dirs(path.join(os.projectdir(), "*|.*")) for _, watchdir in ipairs(watchdirs) do local buildir = path.absolute(config.buildir()) if path.absolute(watchdir) ~= buildir then _add_watchdir(watchdir, {recursion = true}) end end _add_watchdir(os.projectdir()) else _add_watchdir(watchdir, {recursion = true}) end end -- run command function _run_command(events) try { function () local commands = option.get("commands") local scriptfile = option.get("script") local arbitrary = option.get("arbitrary") if commands then for _, command in ipairs(commands:split(";")) do os.exec(command) end elseif arbitrary then local program = arbitrary[1] local argv = #arbitrary > 1 and table.slice(arbitrary, 2) or {} os.execv(program, argv) elseif scriptfile and os.isfile(scriptfile) and path.extension(scriptfile) == ".lua" then local script = import(path.basename(scriptfile), {rootdir = path.directory(scriptfile), anonymous = true}) script(events) elseif os.isfile(os.projectfile()) then local argv = {"build", "-y"} if option.get("verbose") then table.insert(argv, "-v") end if option.get("diagnosis") then table.insert(argv, "-D") end local target = option.get("target") if target then table.insert(argv, target) end os.execv(os.programfile(), argv) if option.get("run") then argv[1] = "run" os.execv(os.programfile(), argv) end end end, catch { function (errors) cprint(tostring(errors)) end } } end function main() -- add watchdirs _add_watchdirs() -- do watch local count = 0 local events = {} while true do local ok, event = fwatcher.wait(300) if ok > 0 then local status if event.type == fwatcher.ET_CREATE then status = "created" elseif event.type == fwatcher.ET_MODIFY then status = "modified" elseif event.type == fwatcher.ET_DELETE then status = "deleted" end print(event.path, status) -- we use map to remove repeat events events[event.path .. tostring(event.type)] = event count = count + 1 elseif count > 0 then _run_command(table.values(events)) count = 0 end end end
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/watch/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 -- task("watch") set_category("plugin") on_run("main") set_menu { usage = "xmake watch [options] [arguments]" , description = "Watch the project directories and run command." , options = { {'c', "commands" , "kv" , nil , "Run the multiple commands instead of the default build command.", "e.g.", " $ xmake watch -c 'xmake -rv'", " $ xmake watch -c 'xmake -vD; xmake run hello'"}, {'s', "script" , "kv" , nil , "Run the given lua script file.", "e.g.", " $ xmake watch -s /tmp/watch.lua"}, {'d', "watchdirs" , "kv" , nil , "Set the given recursive watch directories, the project directories will be watched by default.", "e.g.", " $ xmake watch -d src", " $ xmake watch -d 'src/*" .. path.envsep() .. "tests/**/subdir'"}, {'p', "plaindirs" , "kv" , nil , "Set the given non-recursive watch directories, the project directories will be watched by default.", "e.g.", " $ xmake watch -p src", " $ xmake watch -p 'src/*" .. path.envsep() .. "tests/**/subdir'"}, {'r', "run" , "k" , nil , "Build and run target."}, {'t', "target" , "kv" , nil , "Build the given target.", values = function (complete, opt) return import("private.utils.complete_helper.targets")(complete, opt) end }, {'-', "arbitrary" , "vs" , nil , "Run an arbitrary command.", "e.g.", " $ xmake watch -- echo hello xmake!", " $ xmake watch -- xmake run", " $ xmake watch -- xmake -rv"} } }
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/format/main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.base.hashset") import("core.project.config") import("core.project.project") import("lib.detect.find_tool") import("private.action.require.impl.packagenv") import("private.action.require.impl.install_packages") -- match source files function _match_sourcefiles(sourcefile, filepatterns) for _, filepattern in ipairs(filepatterns) do if sourcefile:match(filepattern.pattern) == sourcefile then if filepattern.excludes then if filepattern.rootdir and sourcefile:startswith(filepattern.rootdir) then sourcefile = sourcefile:sub(#filepattern.rootdir + 2) end for _, exclude in ipairs(filepattern.excludes) do if sourcefile:match(exclude) == sourcefile then return false end end end return true end end end -- convert all sourcefiles to lua pattern function _get_file_patterns(sourcefiles) local patterns = {} for _, sourcefile in ipairs(path.splitenv(sourcefiles)) do -- get the excludes local pattern = sourcefile:trim() 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("|.*$", ""))) -- 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) -- convert to lua path pattern pattern = path.pattern(pattern) table.insert(patterns, {pattern = pattern, excludes = excludes, rootdir = rootdir}) end return patterns end -- get all the targets that match the group or targetname function _get_targets(targetname, group_pattern) local targets = {} if targetname then table.insert(targets, project.target(targetname)) else for _, target in pairs(project.targets()) do local group = target:get("group") if (target:is_default() and not group_pattern) or option.get("all") or (group_pattern and group and group:match(group_pattern)) then table.insert(targets, target) end end end return targets end -- main function main() -- load configuration config.load() -- enter the environments of llvm local oldenvs = packagenv.enter("llvm") -- find clang-format local packages = {} local clang_format = find_tool("clang-format") if not clang_format then table.join2(packages, install_packages("llvm")) end -- enter the environments of installed packages for _, instance in ipairs(packages) do instance:envs_enter() end -- we need to force detect and flush detect cache after loading all environments if not clang_format then clang_format = find_tool("clang-format", {force = true}) end assert(clang_format, "clang-format not found!") -- create style file local argv = {} local projectdir = project.directory() if option.get("create") then table.insert(argv, "--style=" .. (option.get("style") or "Google")) table.insert(argv, "--dump-config") os.execv(clang_format.program, argv, {stdout = path.join(projectdir, ".clang-format"), curdir = projectdir}) return end -- set style file if option.get("style") then table.insert(argv, "--style=" .. option.get("style")) end -- inplace flag table.insert(argv, "-i") local targetname local group_pattern = option.get("group") if group_pattern then group_pattern = "^" .. path.pattern(group_pattern) .. "$" else targetname = option.get("target") end local targets = _get_targets(targetname, group_pattern) if option.get("files") then local filepatterns = _get_file_patterns(option.get("files")) for _, target in ipairs(targets) do for _, source in ipairs(target:sourcefiles()) do if _match_sourcefiles(source, filepatterns) then table.insert(argv, path.join(projectdir, source)) end end for _, header in ipairs(target:headerfiles()) do if _match_sourcefiles(header, filepatterns) then table.insert(argv, path.join(projectdir, header)) end end end else for _, target in ipairs(targets) do for _, source in ipairs(target:sourcefiles()) do table.insert(argv, path.join(projectdir, source)) end for _, header in ipairs(target:headerfiles()) do table.insert(argv, path.join(projectdir, header)) end end end -- format files os.vrunv(clang_format.program, argv, {curdir = projectdir}) cprint("${color.success}format ok!") -- done os.setenvs(oldenvs) end
0
repos/xmake/xmake/plugins
repos/xmake/xmake/plugins/format/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 format.lua -- task("format") set_category("plugin") on_run("main") set_menu { usage = "xmake format [options] [arguments]", description = "Format the current project.", options = { {'s', "style", "kv", nil, "Set the path of .clang-format file, a coding style", values = {"LLVM", "Google", "Chromium", "Mozilla", "WebKit"}}, {nil, "create", "k", nil, "Create a .clang-format file from a coding style"}, {'a', "all", "k", nil, "Format all targets."}, {'g', "group", "kv", nil, "Format all targets of the given group. It support path pattern matching.", "e.g.", " xmake format -g test", " xmake format -g test_*", " xmake format --group=benchmark/*"}, {'f', "files", "kv", nil, "Build the given source files.", "e.g.", " - xmake format --files=src/main.c", " - xmake format --files='src/*.c' [target]", " - xmake format --files='src/**.c|excluded_file.c", " - xmake format --files='src/main.c" .. path.envsep() .. "src/test.c'" }, {}, {nil, "target", "v", nil, "The target name. It will format all default targets if this parameter is not specified." , values = function (complete, opt) return import("private.utils.complete_helper.targets")(complete, opt) end } } }
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/nim/load.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- function _get_apis() local apis = {} apis.values = { -- target.add_xxx "target.add_ncflags" , "target.add_ldflags" , "target.add_arflags" , "target.add_shflags" , "target.add_rpathdirs" -- @note do not translate path, it's usually an absolute path or contains $ORIGIN/@loader_path -- option.add_xxx , "option.add_ncflags" , "option.add_ldflags" , "option.add_arflags" , "option.add_shflags" , "option.add_rpathdirs" -- toolchain.add_xxx , "toolchain.add_ncflags" , "toolchain.add_ldflags" , "toolchain.add_arflags" , "toolchain.add_shflags" , "toolchain.add_rpathdirs" } apis.paths = { -- target.add_xxx "target.add_linkdirs" -- option.add_xxx , "option.add_linkdirs" } return apis end function main() return {apis = _get_apis()} end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/nim/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 -- language("nim") add_rules("nim") set_sourcekinds {nc = ".nim"} set_sourceflags {nc = "ncflags"} set_targetkinds {binary = "ncld", static = "ncar", shared = "ncsh"} set_targetflags {binary = "ldflags", static = "arflags", shared = "shflags"} set_langkinds {nim = "nc"} set_mixingkinds("nc") on_load("load") set_nameflags { object = { "config.includedirs" , "target.symbols" , "target.warnings" , "target.defines" , "target.undefines" , "target.optimize:check" , "target.vectorexts:check" , "target.includedirs" , "toolchain.includedirs" } , binary = { "config.linkdirs" , "target.linkdirs" , "target.rpathdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "toolchain.rpathdirs" , "config.links" , "target.links" , "toolchain.links" } , shared = { "config.linkdirs" , "target.linkdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "config.links" , "target.links" , "toolchain.links" } , static = { "target.strip" , "target.symbols" } } set_menu { config = { {category = "Cross Complation Configuration/Compiler Configuration" } , {nil, "nc", "kv", nil, "The Nim Compiler" } , {category = "Cross Complation Configuration/Linker Configuration" } , {nil, "ncld", "kv", nil, "The Nim Linker" } , {nil, "ncar", "kv", nil, "The Nim Static Library Archiver" } , {nil, "ncsh", "kv", nil, "The Nim Shared Library Linker" } , {category = "Cross Complation Configuration/Builtin Flags Configuration" } , {nil, "linkdirs", "kv", nil, "The Link Search Directories" } } }
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/pascal/check_main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file check_main.lua -- -- check it function main(sourcefile) -- load source code local sourcecode = io.readfile(sourcefile) -- remove comment first sourcecode = sourcecode:gsub("{%*.-%*}", "") sourcecode = sourcecode:gsub("//.-\n", "\n") -- find 'program xxx' if sourcecode:find("program%s*%(.-%)") then return true end -- no main function return false end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/pascal/load.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- function _get_apis() local apis = {} apis.values = { -- target.add_xxx "target.add_links" , "target.add_frameworks" , "target.add_syslinks" , "target.add_pcflags" , "target.add_ldflags" , "target.add_arflags" , "target.add_shflags" , "target.add_rpathdirs" -- @note do not translate path, it's usually an absolute path or contains $ORIGIN/@loader_path -- option.add_xxx , "option.add_links" , "option.add_syslinks" , "option.add_pcflags" , "option.add_ldflags" , "option.add_arflags" , "option.add_shflags" , "option.add_rpathdirs" -- package.add_xxx , "package.add_links" , "package.add_syslinks" , "package.add_pcflags" , "package.add_ldflags" , "package.add_arflags" , "package.add_shflags" , "package.add_rpathdirs" , "package.add_linkdirs" -- toolchain.add_xxx , "toolchain.add_links" , "toolchain.add_syslinks" , "toolchain.add_pcflags" , "toolchain.add_ldflags" , "toolchain.add_arflags" , "toolchain.add_shflags" , "toolchain.add_rpathdirs" , "toolchain.add_linkdirs" } apis.paths = { -- target.add_xxx "target.add_linkdirs" , "target.add_frameworkdirs" -- option.add_xxx , "option.add_linkdirs" } return apis end function main() return {apis = _get_apis()} end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/pascal/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 -- language("pascal") add_rules("pascal") set_sourcekinds {pc = {".pas", ".pp", ".ppu", ".lpr"}} set_sourceflags {pc = "pcflags"} set_targetkinds {binary = "pcld", shared = "pcsh"} set_targetflags {binary = "ldflags", shared = "shflags"} set_langkinds {pascal = "pc"} set_mixingkinds("pc") on_load("load") on_check_main("check_main") set_nameflags { object = { "target.symbols" , "target.warnings" , "target.optimize:check" , "target.vectorexts:check" } , binary = { "config.linkdirs" , "target.linkdirs" , "target.rpathdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "toolchain.rpathdirs" , "config.links" , "target.links" , "target.frameworks" , "target.frameworkdirs" , "toolchain.links" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , shared = { "config.linkdirs" , "target.linkdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "config.links" , "target.links" , "target.frameworks" , "target.frameworkdirs" , "toolchain.links" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } } set_menu { config = { {category = "Cross Complation Configuration/Compiler Configuration" } , {nil, "pc", "kv", nil, "The Pascal Compiler" } , {category = "Cross Complation Configuration/Linker Configuration" } , {nil, "pcld", "kv", nil, "The Pascal Linker" } , {nil, "pcsh", "kv", nil, "The Pascal Shared Library Linker" } , {category = "Cross Complation Configuration/Builtin Flags Configuration" } , {nil, "links", "kv", nil, "The Link Libraries" } , {nil, "syslinks", "kv", nil, "The System Link Libraries" } , {nil, "linkdirs", "kv", nil, "The Link Search Directories" } } }
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/cuda/check_main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file check_main.lua -- -- check it function main(sourcefile) -- load source code local sourcecode = io.readfile(sourcefile) -- remove comment first sourcecode = sourcecode:gsub("/%*.-%*/", "") sourcecode = sourcecode:gsub("//.-\n", "\n") -- find int main(int argc, char** argv) {} if sourcecode:find("%s+main%s*%(.-%)") then return true end -- no main function return false end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/cuda/load.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- function _get_apis() local apis = {} apis.values = { -- target.add_xxx "target.add_links" , "target.add_syslinks" , "target.add_cugencodes" , "target.add_cuflags" , "target.add_culdflags" , "target.add_ldflags" , "target.add_arflags" , "target.add_shflags" , "target.add_defines" , "target.add_undefines" , "target.add_rpathdirs" -- @note do not translate path, it's usually an absolute path or contains $ORIGIN/@loader_path -- option.add_xxx , "option.add_links" , "option.add_syslinks" , "option.add_cugencodes" , "option.add_cuflags" , "option.add_culdflags" , "option.add_ldflags" , "option.add_arflags" , "option.add_shflags" , "option.add_defines" , "option.add_undefines" , "option.add_rpathdirs" -- package.add_xxx , "package.add_links" , "package.add_syslinks" , "package.add_cuflags" , "package.add_culdflags" , "package.add_arflags" , "package.add_shflags" , "package.add_defines" , "package.add_undefines" , "package.add_rpathdirs" -- toolchain.add_xxx , "toolchain.add_links" , "toolchain.add_syslinks" , "toolchain.add_cugencodes" , "toolchain.add_cuflags" , "toolchain.add_culdflags" , "toolchain.add_ldflags" , "toolchain.add_arflags" , "toolchain.add_shflags" , "toolchain.add_defines" , "toolchain.add_undefines" , "toolchain.add_rpathdirs" } apis.paths = { -- target.add_xxx "target.add_linkdirs" , "target.add_includedirs" , "target.add_sysincludedirs" -- option.add_xxx , "option.add_linkdirs" , "option.add_sysincludedirs" } return apis end function main() return {apis = _get_apis()} end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/cuda/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 -- language("cuda") add_rules("cuda") set_sourcekinds {cu = ".cu"} set_sourceflags {cu = "cuflags"} set_targetkinds {gpucode = "culd", binary = "ld", static = "ar", shared = "sh"} set_targetflags {gpucode = "culdflags", binary = "ldflags", static = "arflags", shared = "shflags"} set_langkinds {cu = "cu"} set_mixingkinds("cu", "cc", "cxx", "as") on_load("load") on_check_main("check_main") set_nameflags { object = { "config.includedirs" , "target.symbols" , "target.warnings" , "target.optimize:check" , "target.vectorexts:check" , "target.includedirs" , "target.languages" , "target.runtimes" , "target.defines" , "target.undefines" , "toolchain.includedirs" , "toolchain.defines" , "toolchain.undefines" , "target.sysincludedirs" , "toolchain.sysincludedirs" } , binary = { "config.linkdirs" , "target.linkdirs" , "target.rpathdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "toolchain.rpathdirs" , "config.links" , "target.links" , "toolchain.links" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , shared = { "config.linkdirs" , "target.linkdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "config.links" , "target.links" , "toolchain.links" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , static = { "target.strip" , "target.symbols" } , gpucode = { "config.linkdirs" , "target.linkdirs" , "toolchain.linkdirs" , "config.links" , "target.links" , "toolchain.links" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } } set_menu { config = { {category = "Cross Complation Configuration/Compiler Configuration" } , {nil, "cu", "kv", nil, "The Cuda Compiler" } , {nil, "cu-ccbin", "kv", nil, "The Cuda Host C++ Compiler" } , {nil, "culd", "kv", nil, "The Cuda Linker" } , {category = "Cross Complation Configuration/Compiler Flags Configuration" } , {nil, "cuflags", "kv", nil, "The Cuda Compiler Flags" } , {nil, "culdflags", "kv", nil, "The Cuda Linker Flags" } , {category = "Cross Complation Configuration/Builtin Flags Configuration" } , {nil, "links", "kv", nil, "The Link Libraries" } , {nil, "syslinks", "kv", nil, "The System Link Libraries" } , {nil, "linkdirs", "kv", nil, "The Link Search Directories" } , {nil, "includedirs","kv", nil, "The Include Search Directories" } } }
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/asm/load.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- function _get_apis() local apis = {} apis.values = { -- target.add_xxx "target.add_links" , "target.add_syslinks" , "target.add_asflags" , "target.add_ldflags" , "target.add_arflags" , "target.add_shflags" , "target.add_defines" , "target.add_undefines" , "target.add_rpathdirs" -- @note do not translate path, it's usually an absolute path or contains $ORIGIN/@loader_path -- option.add_xxx , "option.add_links" , "option.add_syslinks" , "option.add_asflags" , "option.add_ldflags" , "option.add_arflags" , "option.add_shflags" , "option.add_defines" , "option.add_undefines" , "option.add_rpathdirs" -- package.add_xxx , "package.add_links" , "package.add_syslinks" , "package.add_asflags" , "package.add_ldflags" , "package.add_arflags" , "package.add_shflags" , "package.add_defines" , "package.add_undefines" , "package.add_rpathdirs" , "package.add_linkdirs" , "package.add_includedirs" , "package.add_sysincludedirs" -- toolchain.add_xxx , "toolchain.add_links" , "toolchain.add_syslinks" , "toolchain.add_asflags" , "toolchain.add_ldflags" , "toolchain.add_arflags" , "toolchain.add_shflags" , "toolchain.add_defines" , "toolchain.add_undefines" , "toolchain.add_rpathdirs" , "toolchain.add_linkdirs" , "toolchain.add_includedirs" , "toolchain.add_sysincludedirs" } apis.groups = { -- target.add_xxx "target.add_linkorders" , "target.add_linkgroups" } apis.paths = { -- target.add_xxx "target.add_headerfiles" , "target.add_linkdirs" , "target.add_includedirs" , "target.add_sysincludedirs" -- option.add_xxx , "option.add_linkdirs" , "option.add_includedirs" , "option.add_sysincludedirs" } return apis end function main() return {apis = _get_apis()} end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/asm/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 -- language("asm") add_rules("asm") set_sourcekinds {as = {".s", ".asm"}} set_sourceflags {as = "asflags"} set_targetkinds {binary = "ld", static = "ar", shared = "sh"} set_targetflags {binary = "ldflags", static = "arflags", shared = "shflags"} set_langkinds {as = "as"} set_mixingkinds("as") on_load("load") set_nameflags { object = { "config.includedirs" , "target.symbols" , "target.warnings" , "target.optimize:check" , "target.vectorexts:check" , "target.languages" , "target.includedirs" , "target.defines" , "target.undefines" , "target.runtimes" , "toolchain.includedirs" , "toolchain.defines" , "toolchain.undefines" , "target.sysincludedirs" , "toolchain.sysincludedirs" } , binary = { "config.linkdirs" , "target.linkdirs" , "target.rpathdirs" , "target.strip" , "target.symbols" , "target.runtimes" , "toolchain.linkdirs" , "toolchain.rpathdirs" , "config.links" , "target.links" , "toolchain.links" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , shared = { "config.linkdirs" , "target.linkdirs" , "target.strip" , "target.symbols" , "target.runtimes" , "toolchain.linkdirs" , "config.links" , "target.links" , "toolchain.links" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , static = { "target.strip" , "target.symbols" } } set_menu { config = { {category = "Cross Complation Configuration/Compiler Configuration" } , {nil, "as", "kv", nil, "The Assembler" } , {category = "Cross Complation Configuration/Linker Configuration" } , {nil, "ar", "kv", nil, "The Static Library Linker" } , {nil, "ld", "kv", nil, "The Linker" } , {nil, "sh", "kv", nil, "The Shared Library Linker" } , {category = "Cross Complation Configuration/Compiler Flags Configuration" } , {nil, "asflags", "kv", nil, "The Assembler Flags" } , {category = "Cross Complation Configuration/Linker Flags Configuration" } , {nil, "ldflags", "kv", nil, "The Binary Linker Flags" } , {nil, "arflags", "kv", nil, "The Static Library Linker Flags" } , {nil, "shflags", "kv", nil, "The Shared Library Linker Flags" } , {category = "Cross Complation Configuration/Builin Flags Configuration" } , {nil, "links", "kv", nil, "The Link Libraries" } , {nil, "syslinks", "kv", nil, "The System Link Libraries" } , {nil, "linkdirs", "kv", nil, "The Link Search Directories" } , {nil, "includedirs","kv", nil, "The Include Search Directories" } } }
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/swift/load.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- function _get_apis() local apis = {} apis.values = { -- target.add_xxx "target.add_links" , "target.add_syslinks" , "target.add_scflags" , "target.add_ldflags" , "target.add_arflags" , "target.add_shflags" , "target.add_frameworks" , "target.add_rpathdirs" -- @note do not translate path, it's usually an absolute path or contains $ORIGIN/@loader_path -- option.add_xxx , "option.add_links" , "option.add_syslinks" , "option.add_scflags" , "option.add_ldflags" , "option.add_arflags" , "option.add_shflags" , "option.add_frameworks" , "option.add_rpathdirs" -- toolchain.add_xxx , "toolchain.add_links" , "toolchain.add_syslinks" , "toolchain.add_scflags" , "toolchain.add_ldflags" , "toolchain.add_arflags" , "toolchain.add_shflags" , "toolchain.add_frameworks" , "toolchain.add_rpathdirs" } apis.paths = { -- target.add_xxx "target.add_linkdirs" , "target.add_frameworkdirs" -- option.add_xxx , "option.add_linkdirs" , "option.add_frameworkdirs" } return apis end function main() return {apis = _get_apis()} end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/swift/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 -- language("swift") add_rules("swift") set_sourcekinds {sc = ".swift"} set_sourceflags {sc = "scflags"} set_targetkinds {binary = "scld", static = "ar", shared = "scsh"} set_targetflags {binary = "ldflags", static = "arflags", shared = "shflags"} set_langkinds {swift = "sc"} set_mixingkinds("sc", "mm", "mxx", "cc", "cxx") on_load("load") set_nameflags { object = { "config.includedirs" , "config.frameworkdirs" , "config.Frameworks" , "target.symbols" , "target.warnings" , "target.optimize:check" , "target.vectorexts:check" , "target.languages" , "target.includedirs" , "target.defines" , "target.undefines" , "target.frameworkdirs" , "target.frameworks" , "toolchain.includedirs" , "toolchain.defines" , "toolchain.undefines" , "toolchain.frameworkdirs" , "toolchain.frameworks" } , binary = { "config.linkdirs" , "config.frameworkdirs" , "target.linkdirs" , "target.rpathdirs" , "target.frameworkdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "toolchain.rpathdirs" , "toolchain.frameworkdirs" , "config.links" , "target.links" , "toolchain.links" , "config.frameworks" , "target.frameworks" , "toolchain.frameworks" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , shared = { "config.linkdirs" , "config.frameworkdirs" , "target.linkdirs" , "target.frameworkdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "toolchain.frameworkdirs" , "config.links" , "target.links" , "toolchain.links" , "config.frameworks" , "target.frameworks" , "toolchain.frameworks" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , static = { "target.strip" , "target.symbols" } } set_menu { config = { {category = "Cross Complation Configuration/Compiler Configuration" } , { nil, "sc", "kv", nil, "The Swift Compiler" } , {category = "Cross Complation Configuration/Linker Configuration" } , { nil, "scld", "kv", nil, "The Swift Linker" } , { nil, "scsh", "kv", nil, "The Swift Shared Library Linker" } , { category = "Cross Complation Configuration/Builtin Flags Configuration" } , { nil, "links", "kv", nil, "The Link Libraries" } , { nil, "syslinks", "kv", nil, "The System Link Libraries" } , { nil, "linkdirs", "kv", nil, "The Link Search Directories" } , { nil, "includedirs", "kv", nil, "The Include Search Directories" } , { nil, "frameworks", "kv", nil, "The Frameworks" } , { nil, "frameworkdirs", "kv", nil, "The Frameworks Search Directories" } } }
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/dlang/check_main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file check_main.lua -- -- check it function main(sourcefile) -- load source code local sourcecode = io.readfile(sourcefile) -- remove comment first sourcecode = sourcecode:gsub("/%*.-%*/", "") sourcecode = sourcecode:gsub("/%+.-%+/", "") sourcecode = sourcecode:gsub("//.-\n", "\n") -- find func main() { if sourcecode:find("void%s+main%s*%(.-%)") then return true end -- no main function return false end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/dlang/load.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- function _get_apis() local apis = {} apis.values = { -- target.add_xxx "target.add_links" , "target.add_syslinks" , "target.add_dcflags" , "target.add_ldflags" , "target.add_arflags" , "target.add_shflags" , "target.add_frameworks" , "target.add_rpathdirs" -- @note do not translate path, it's usually an absolute path or contains $ORIGIN/@loader_path -- option.add_xxx , "option.add_links" , "option.add_syslinks" , "option.add_dcflags" , "option.add_ldflags" , "option.add_arflags" , "option.add_shflags" , "option.add_frameworks" , "option.add_rpathdirs" -- package.add_xxx , "package.add_links" , "package.add_syslinks" , "package.add_dcflags" , "package.add_ldflags" , "package.add_arflags" , "package.add_shflags" , "package.add_frameworks" , "package.add_rpathdirs" , "package.add_linkdirs" , "package.add_includedirs" , "package.add_sysincludedirs" , "package.add_frameworkdirs" -- toolchain.add_xxx , "toolchain.add_links" , "toolchain.add_syslinks" , "toolchain.add_dcflags" , "toolchain.add_ldflags" , "toolchain.add_arflags" , "toolchain.add_shflags" , "toolchain.add_frameworks" , "toolchain.add_rpathdirs" , "toolchain.add_linkdirs" , "toolchain.add_includedirs" , "toolchain.add_sysincludedirs" , "toolchain.add_frameworkdirs" } apis.groups = { -- target.add_xxx "target.add_linkorders" , "target.add_linkgroups" } apis.paths = { -- target.add_xxx "target.add_linkdirs" , "target.add_includedirs" , "target.add_sysincludedirs" -- option.add_xxx , "option.add_linkdirs" , "option.add_includedirs" , "option.add_sysincludedirs" } return apis end function main() return {apis = _get_apis()} end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/dlang/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 -- language("dlang") add_rules("dlang") set_sourcekinds {dc = ".d"} set_sourceflags {dc = "dcflags"} set_targetkinds {binary = "dcld", static = "dcar", shared = "dcsh"} set_targetflags {binary = "ldflags", static = "arflags", shared = "shflags"} set_langkinds {d = "dc"} set_mixingkinds("dc", "cc", "cxx", "as") on_load("load") on_check_main("check_main") set_nameflags { object = { "config.includedirs" , "config.frameworkdirs" , "config.frameworks" , "target.symbols" , "target.warnings" , "target.optimize:check" , "target.vectorexts:check" , "target.includedirs" , "target.frameworkdirs" , "target.frameworks" , "toolchain.includedirs" , "target.sysincludedirs" , "toolchain.sysincludedirs" , "toolchain.frameworkdirs" , "toolchain.frameworks" } , binary = { "config.linkdirs" , "config.frameworkdirs" , "target.linkdirs" , "target.frameworkdirs" , "target.rpathdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "toolchain.rpathdirs" , "toolchain.frameworkdirs" , "config.links" , "target.links" , "target.linkgroups" , "toolchain.links" , "config.frameworks" , "target.frameworks" , "toolchain.frameworks" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , shared = { "config.linkdirs" , "config.frameworkdirs" , "target.linkdirs" , "target.frameworkdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "toolchain.frameworkdirs" , "config.links" , "target.links" , "target.linkgroups" , "toolchain.links" , "config.frameworks" , "target.frameworks" , "toolchain.frameworks" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , static = { "target.strip" , "target.symbols" } } set_menu { config = { {category = "Cross Complation Configuration/Compiler Configuration" } , {nil, "dc", "kv", nil, "The Dlang Compiler" } , {category = "Cross Complation Configuration/Linker Configuration" } , {nil, "dcld", "kv", nil, "The Dlang Linker" } , {nil, "dcar", "kv", nil, "The Dlang Static Library Archiver" } , {nil, "dcsh", "kv", nil, "The Dlang Shared Library Linker" } , {category = "Cross Complation Configuration/Builtin Flags Configuration" } , {nil, "links", "kv", nil, "The Link Libraries" } , {nil, "syslinks", "kv", nil, "The System Link Libraries" } , {nil, "linkdirs", "kv", nil, "The Link Search Directories" } , {nil, "includedirs","kv", nil, "The Include Search Directories" } } }
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/c++/check_main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file check_main.lua -- -- check it function main(sourcefile) -- load source code local sourcecode = io.readfile(sourcefile) -- remove comment first sourcecode = sourcecode:gsub("/%*.-%*/", "") sourcecode = sourcecode:gsub("//.-\n", "\n") -- find int main(int argc, char** argv) {} if sourcecode:find("%s+main%s*%(.-%)") then return true end -- no main function return false end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/c++/load.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- -- get apis function _get_apis() local apis = {} apis.values = { -- target.add_xxx "target.add_links" , "target.add_syslinks" , "target.add_cxflags" , "target.add_cxxflags" , "target.add_ldflags" , "target.add_arflags" , "target.add_shflags" , "target.add_defines" , "target.add_undefines" , "target.add_frameworks" , "target.add_rpathdirs" -- @note do not translate path, it's usually an absolute path or contains $ORIGIN/@loader_path , "target.add_forceincludes" -- option.add_xxx , "option.add_cxxincludes" , "option.add_cxxfuncs" , "option.add_cxxtypes" , "option.add_links" , "option.add_syslinks" , "option.add_cxflags" , "option.add_cxxflags" , "option.add_ldflags" , "option.add_arflags" , "option.add_shflags" , "option.add_defines" , "option.add_undefines" , "option.add_frameworks" , "option.add_rpathdirs" -- package.add_xxx , "package.add_links" , "package.add_syslinks" , "package.add_cxflags" , "package.add_cxxflags" , "package.add_ldflags" , "package.add_arflags" , "package.add_shflags" , "package.add_defines" , "package.add_undefines" , "package.add_frameworks" , "package.add_rpathdirs" , "package.add_linkdirs" , "package.add_includedirs" --@note we need not uses paths for package, see https://github.com/xmake-io/xmake/issues/717 , "package.add_sysincludedirs" , "package.add_frameworkdirs" -- toolchain.add_xxx , "toolchain.add_links" , "toolchain.add_syslinks" , "toolchain.add_cxflags" , "toolchain.add_cxxflags" , "toolchain.add_ldflags" , "toolchain.add_arflags" , "toolchain.add_shflags" , "toolchain.add_defines" , "toolchain.add_undefines" , "toolchain.add_frameworks" , "toolchain.add_rpathdirs" , "toolchain.add_linkdirs" , "toolchain.add_includedirs" , "toolchain.add_sysincludedirs" , "toolchain.add_frameworkdirs" } apis.groups = { -- target.add_xxx "target.add_linkorders" , "target.add_linkgroups" -- package.add_xxx , "package.add_linkorders" , "package.add_linkgroups" } apis.paths = { -- target.set_xxx "target.set_pcxxheader" -- target.add_xxx , "target.add_headerfiles" , "target.add_linkdirs" , "target.add_includedirs" , "target.add_sysincludedirs" , "target.add_frameworkdirs" -- option.add_xxx , "option.add_linkdirs" , "option.add_includedirs" , "option.add_sysincludedirs" , "option.add_frameworkdirs" } apis.dictionary = { -- option.add_xxx "option.add_cxxsnippets" } return apis end function main() return {apis = _get_apis()} end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/c++/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 -- language("c++") add_rules("c++") set_sourcekinds {cxx = {".cpp", ".cc", ".cxx", ".c++", ".cppm", ".ccm", ".cxxm", ".c++m", ".mpp", ".mxx", ".ixx"}} set_sourceflags {cxx = {"cxxflags", "cxflags"}} set_targetkinds {binary = "ld", static = "ar", shared = "sh"} set_targetflags {binary = "ldflags", static = "arflags", shared = "shflags"} set_langkinds {cxx = "cxx"} set_mixingkinds("cc", "cxx", "as", "mrc") on_load("load") on_check_main("check_main") set_nameflags { object = { "config.includedirs" , "config.frameworkdirs" , "config.frameworks" , "target.symbols" , "target.warnings" , "target.fpmodels" , "target.optimize:check" , "target.vectorexts:check" , "target.languages" , "target.runtimes" , "target.includedirs" , "target.defines" , "target.undefines" , "target.frameworkdirs" , "target.frameworks" , "target.exceptions" , "target.encodings" , "target.pcxxheader" , "target.forceincludes" , "toolchain.includedirs" , "toolchain.defines" , "toolchain.undefines" , "toolchain.frameworkdirs" , "toolchain.frameworks" , "target.sysincludedirs" , "toolchain.sysincludedirs" } , binary = { "config.linkdirs" , "config.frameworkdirs" , "target.linkdirs" , "target.frameworkdirs" , "target.rpathdirs" , "target.strip" , "target.symbols" , "target.optimize:check" , "target.runtimes" , "toolchain.linkdirs" , "toolchain.rpathdirs" , "toolchain.frameworkdirs" , "config.links" , "target.linkgroups" -- we must move it before target.links, because we need sort correct order for package and its deps , "target.links" , "toolchain.links" , "config.frameworks" , "target.frameworks" , "toolchain.frameworks" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , shared = { "config.linkdirs" , "config.frameworkdirs" , "target.linkdirs" , "target.frameworkdirs" , "target.rpathdirs" , "target.strip" , "target.symbols" , "target.optimize:check" , "target.runtimes" , "toolchain.linkdirs" , "toolchain.rpathdirs" , "toolchain.frameworkdirs" , "config.links" , "target.links" , "target.linkgroups" , "toolchain.links" , "config.frameworks" , "target.frameworks" , "toolchain.frameworks" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , static = { "target.strip" , "target.symbols" } } set_menu { config = { {category = "Cross Complation Configuration/Compiler Configuration" } , {nil, "cxx", "kv", nil, "The C++ Compiler" } , {nil, "cpp", "kv", nil, "The C/C++ Preprocessor" } , {category = "Cross Complation Configuration/Linker Configuration" } , {nil, "ld", "kv", nil, "The Linker" } , {nil, "ar", "kv", nil, "The Static Library Linker" } , {nil, "sh", "kv", nil, "The Shared Library Linker" } , {nil, "ranlib", "kv", nil, "The Static Library Index Generator" } , {category = "Cross Complation Configuration/Compiler Flags Configuration" } , {nil, "cxflags", "kv", nil, "The C/C++ compiler Flags" } , {nil, "cxxflags", "kv", nil, "The C++ Compiler Flags" } , {category = "Cross Complation Configuration/Linker Flags Configuration" } , {nil, "ldflags", "kv", nil, "The Binary Linker Flags" } , {nil, "arflags", "kv", nil, "The Static Library Linker Flags" } , {nil, "shflags", "kv", nil, "The Shared Library Linker Flags" } , {category = "Cross Complation Configuration/Builtin Flags Configuration" } , {nil, "links", "kv", nil, "The Link Libraries" } , {nil, "syslinks", "kv", nil, "The System Link Libraries" } , {nil, "linkdirs", "kv", nil, "The Link Search Directories" } , {nil, "includedirs", "kv", nil, "The Include Search Directories" } , {nil, "frameworks", "kv", nil, "The Frameworks" } , {nil, "frameworkdirs", "kv", nil, "The Frameworks Search Directories" } } }
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/objc++/check_main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file check_main.lua -- -- check it function main(sourcefile) -- load source code local sourcecode = io.readfile(sourcefile) -- remove comment first sourcecode = sourcecode:gsub("/%*.-%*/", "") sourcecode = sourcecode:gsub("//.-\n", "\n") -- find int main(int argc, char** argv) {} if sourcecode:find("%s+main%s*%(.-%)") then return true end -- no main function return false end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/objc++/load.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- function _get_apis() local apis = {} apis.values = { -- target.add_xxx "target.add_links" , "target.add_syslinks" , "target.add_mflags" , "target.add_mxflags" , "target.add_mxxflags" , "target.add_ldflags" , "target.add_arflags" , "target.add_shflags" , "target.add_defines" , "target.add_undefines" , "target.add_frameworks" , "target.add_rpathdirs" -- @note do not translate path, it's usually an absolute path or contains $ORIGIN/@loader_path , "target.add_forceincludes" -- option.add_xxx , "option.add_cincludes" , "option.add_cxxincludes" , "option.add_cfuncs" , "option.add_cxxfuncs" , "option.add_ctypes" , "option.add_cxxtypes" , "option.add_links" , "option.add_syslinks" , "option.add_mflags" , "option.add_mxflags" , "option.add_mxxflags" , "option.add_ldflags" , "option.add_arflags" , "option.add_shflags" , "option.add_defines" , "option.add_undefines" , "option.add_frameworks" , "option.add_rpathdirs" -- package.add_xxx , "package.add_links" , "package.add_syslinks" , "package.add_mflags" , "package.add_mxflags" , "package.add_mxxflags" , "package.add_ldflags" , "package.add_arflags" , "package.add_shflags" , "package.add_defines" , "package.add_undefines" , "package.add_frameworks" , "package.add_rpathdirs" , "package.add_linkdirs" , "package.add_includedirs" --@note we don't need to use paths for package, see https://github.com/xmake-io/xmake/issues/717 , "package.add_sysincludedirs" , "package.add_frameworkdirs" -- toolchain.add_xxx , "toolchain.add_links" , "toolchain.add_syslinks" , "toolchain.add_mflags" , "toolchain.add_mxflags" , "toolchain.add_mxxflags" , "toolchain.add_ldflags" , "toolchain.add_arflags" , "toolchain.add_shflags" , "toolchain.add_defines" , "toolchain.add_undefines" , "toolchain.add_frameworks" , "toolchain.add_rpathdirs" , "toolchain.add_linkdirs" , "toolchain.add_includedirs" , "toolchain.add_sysincludedirs" , "toolchain.add_frameworkdirs" } apis.groups = { -- target.add_xxx "target.add_linkorders" , "target.add_linkgroups" } apis.paths = { -- target.set_xxx "target.set_pmheader" , "target.set_pmxxheader" -- target.add_xxx , "target.add_headerfiles" , "target.add_linkdirs" , "target.add_includedirs" , "target.add_sysincludedirs" , "target.add_frameworkdirs" -- option.add_xxx , "option.add_linkdirs" , "option.add_includedirs" , "option.add_sysincludedirs" , "option.add_frameworkdirs" } return apis end function main() return {apis = _get_apis()} end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/objc++/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 language language("objc++") -- set source file kinds set_sourcekinds {mm = ".m", mxx = ".mm"} -- set source file flags set_sourceflags {mm = {"mflags", "mxflags"}, mxx = {"mxxflags", "mxflags"}} -- set target kinds set_targetkinds {binary = "ld", static = "ar", shared = "sh"} -- set target flags set_targetflags {binary = "ldflags", static = "arflags", shared = "shflags"} -- set language kinds set_langkinds {m = "mm", mxx = "mxx"} -- set mixing kinds set_mixingkinds("mm", "mxx", "cc", "cxx", "as") -- add rules add_rules("objc++") -- on load on_load("load") -- on check_main on_check_main("check_main") -- set name flags set_nameflags { object = { "config.includedirs" , "config.frameworkdirs" , "config.frameworks" , "target.symbols" , "target.warnings" , "target.optimize:check" , "target.vectorexts:check" , "target.languages" , "target.includedirs" , "target.defines" , "target.undefines" , "target.frameworkdirs" , "target.frameworks" , "target.exceptions" , "target.encodings" , "target.pmheader" , "target.pmxxheader" , "target.forceincludes" , "toolchain.includedirs" , "toolchain.defines" , "toolchain.undefines" , "toolchain.frameworkdirs" , "toolchain.frameworks" , "target.sysincludedirs" , "toolchain.sysincludedirs" } , binary = { "config.linkdirs" , "config.frameworkdirs" , "target.linkdirs" , "target.rpathdirs" , "target.frameworkdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "toolchain.rpathdirs" , "toolchain.frameworkdirs" , "config.links" , "target.links" , "target.linkgroups" , "toolchain.links" , "config.frameworks" , "target.frameworks" , "toolchain.frameworks" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , shared = { "config.linkdirs" , "config.frameworkdirs" , "target.linkdirs" , "target.frameworkdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "toolchain.frameworkdirs" , "config.links" , "target.links" , "target.linkgroups" , "toolchain.links" , "config.frameworks" , "target.frameworks" , "toolchain.frameworks" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , static = { "target.strip" , "target.symbols" } } -- set menu set_menu { config = { {category = "Cross Complation Configuration/Compiler Configuration" } , {nil, "mm", "kv", nil, "The Objc Compiler" } , {nil, "mxx", "kv", nil, "The Objc++ Compiler" } , {category = "Cross Complation Configuration/Linker Configuration" } , {nil, "ld", "kv", nil, "The Linker" } , {nil, "ar", "kv", nil, "The Static Library Linker" } , {nil, "sh", "kv", nil, "The Shared Library Linker" } , {category = "Cross Complation Configuration/Compiler Flags Configuration" } , {nil, "mflags", "kv", nil, "The Objc Compiler Flags" } , {nil, "mxflags", "kv", nil, "The Objc/c++ Compiler Flags" } , {nil, "mxxflags", "kv", nil, "The Objc++ Compiler Flags" } , {category = "Cross Complation Configuration/Linker Flags Configuration" } , {nil, "ldflags", "kv", nil, "The Binary Linker Flags" } , {nil, "arflags", "kv", nil, "The Static Library Linker Flags" } , {nil, "shflags", "kv", nil, "The Shared Library Linker Flags" } , {category = "Cross Complation Configuration/Builtin Flags Configuration" } , {nil, "links", "kv", nil, "The Link Libraries" } , {nil, "syslinks", "kv", nil, "The System Link Libraries" } , {nil, "linkdirs", "kv", nil, "The Link Search Directories" } , {nil, "includedirs", "kv", nil, "The Include Search Directories" } , {nil, "frameworks", "kv", nil, "The Frameworks" } , {nil, "frameworkdirs", "kv", nil, "The Frameworks Search Directories" } } }
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/zig/check_main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file check_main.lua -- -- check it function main(sourcefile) -- load source code local sourcecode = io.readfile(sourcefile) -- remove comment first sourcecode = sourcecode:gsub("/%*.-%*/", "") sourcecode = sourcecode:gsub("//.-\n", "\n") -- find func main() { if sourcecode:find("pub%s+fn%s+main%s*%(.-%)") then return true end -- no main function return false end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/zig/load.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- function _get_apis() local apis = {} apis.values = { -- target.add_xxx "target.add_links" , "target.add_syslinks" , "target.add_zcflags" , "target.add_ldflags" , "target.add_arflags" , "target.add_shflags" , "target.add_rpathdirs" -- @note do not translate path, it's usually an absolute path or contains $ORIGIN/@loader_path -- option.add_xxx , "option.add_links" , "option.add_syslinks" , "option.add_zcflags" , "option.add_ldflags" , "option.add_arflags" , "option.add_shflags" , "option.add_rpathdirs" -- package.add_xxx , "package.add_links" , "package.add_syslinks" , "package.add_zcflags" , "package.add_ldflags" , "package.add_arflags" , "package.add_shflags" , "package.add_rpathdirs" , "package.add_linkdirs" -- toolchain.add_xxx , "toolchain.add_links" , "toolchain.add_syslinks" , "toolchain.add_zcflags" , "toolchain.add_ldflags" , "toolchain.add_arflags" , "toolchain.add_shflags" , "toolchain.add_rpathdirs" , "toolchain.add_linkdirs" } apis.paths = { -- target.add_xxx "target.add_linkdirs" -- option.add_xxx , "option.add_linkdirs" } return apis end function main() return {apis = _get_apis()} end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/zig/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 -- language("zig") add_rules("zig") set_sourcekinds {zc = ".zig"} set_sourceflags {zc = "zcflags"} set_targetkinds {binary = "zcld", static = "zcar", shared = "zcsh"} set_targetflags {binary = "ldflags", static = "arflags", shared = "shflags"} set_langkinds {zig = "zc"} set_mixingkinds("zc", "cc", "cxx", "as") on_load("load") on_check_main("check_main") set_nameflags { object = { "target.symbols" , "target.warnings" , "target.optimize:check" , "target.vectorexts:check" } , binary = { "config.linkdirs" , "target.linkdirs" , "target.rpathdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "toolchain.rpathdirs" , "config.links" , "target.links" , "toolchain.links" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , shared = { "config.linkdirs" , "target.linkdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "config.links" , "target.links" , "toolchain.links" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , static = { "target.strip" , "target.symbols" } } set_menu { config = { {category = "Cross Complation Configuration/Compiler Configuration" } , {nil, "zc", "kv", nil, "The Zig Compiler" } , {category = "Cross Complation Configuration/Linker Configuration" } , {nil, "zcld", "kv", nil, "The Zig Linker" } , {nil, "zcar", "kv", nil, "The Zig Static Library Archiver" } , {nil, "zcsh", "kv", nil, "The Zig Shared Library Linker" } , {category = "Cross Complation Configuration/Builtin Flags Configuration" } , {nil, "links", "kv", nil, "The Link Libraries" } , {nil, "syslinks", "kv", nil, "The System Link Libraries" } , {nil, "linkdirs", "kv", nil, "The Link Search Directories" } } }
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/rust/check_main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file check_main.lua -- -- check it function main(sourcefile) -- load source code local sourcecode = io.readfile(sourcefile) -- remove comment first sourcecode = sourcecode:gsub("/%*.-%*/", "") sourcecode = sourcecode:gsub("//.-\n", "\n") -- find func main() { if sourcecode:find("fn%s+main%s*%(.-%)") then return true end -- no main function return false end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/rust/load.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- function _get_apis() local apis = {} apis.values = { -- target.add_xxx "target.add_rcflags" , "target.add_ldflags" , "target.add_arflags" , "target.add_shflags" , "target.add_rpathdirs" -- @note do not translate path, it's usually an absolute path or contains $ORIGIN/@loader_path -- option.add_xxx , "option.add_rcflags" , "option.add_ldflags" , "option.add_arflags" , "option.add_shflags" , "option.add_rpathdirs" -- toolchain.add_xxx , "toolchain.add_rcflags" , "toolchain.add_ldflags" , "toolchain.add_arflags" , "toolchain.add_shflags" , "toolchain.add_rpathdirs" } apis.paths = { -- target.add_xxx "target.add_linkdirs" -- option.add_xxx , "option.add_linkdirs" } return apis end function main() return {apis = _get_apis()} end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/rust/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 -- language("rust") add_rules("rust") set_sourcekinds {rc = ".rs"} set_sourceflags {rc = "rcflags"} set_targetkinds {binary = "rcld", static = "rcar", shared = "rcsh"} set_targetflags {binary = "ldflags", static = "arflags", shared = "shflags"} set_langkinds {rust = "rc"} set_mixingkinds("rc", "cc", "cxx") on_load("load") on_check_main("check_main") set_nameflags { object = { "target.symbols" , "target.warnings" , "target.optimize:check" , "target.vectorexts:check" } , binary = { "config.linkdirs" , "config.frameworkdirs" , "target.linkdirs" , "target.frameworkdirs" , "target.rpathdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "toolchain.frameworkdirs" , "toolchain.rpathdirs" , "config.frameworks" , "target.frameworks" , "toolchain.frameworks" , "config.links" , "target.links" , "toolchain.links" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , shared = { "config.linkdirs" , "config.frameworkdirs" , "target.linkdirs" , "target.frameworkdirs" , "target.rpathdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "toolchain.frameworkdirs" , "toolchain.rpathdirs" , "config.frameworks" , "target.frameworks" , "toolchain.frameworks" , "config.links" , "target.links" , "toolchain.links" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , static = { "config.linkdirs" , "config.frameworkdirs" , "target.linkdirs" , "target.frameworkdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "toolchain.frameworkdirs" , "config.frameworks" , "target.frameworks" , "toolchain.frameworks" } } set_menu { config = { {category = "Cross Complation Configuration/Compiler Configuration" } , {nil, "rc", "kv", nil, "The Rust Compiler" } , {category = "Cross Complation Configuration/Linker Configuration" } , {nil, "rcld", "kv", nil, "The Rust Linker" } , {nil, "rcar", "kv", nil, "The Rust Static Library Archiver" } , {nil, "rcsh", "kv", nil, "The Rust Shared Library Linker" } , {category = "Cross Complation Configuration/Builtin Flags Configuration" } , {nil, "linkdirs", "kv", nil, "The Link Search Directories" } } }
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/c/check_main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file check_main.lua -- -- check it function main(sourcefile) -- load source code local sourcecode = io.readfile(sourcefile) -- remove comment first sourcecode = sourcecode:gsub("/%*.-%*/", "") sourcecode = sourcecode:gsub("//.-\n", "\n") -- find int main(int argc, char** argv) {} if sourcecode:find("%s+main%s*%(.-%)") then return true end -- no main function return false end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/c/load.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- -- get apis function _get_apis() local apis = {} apis.values = { -- target.add_xxx "target.add_links" , "target.add_syslinks" , "target.add_cflags" , "target.add_cxflags" , "target.add_ldflags" , "target.add_arflags" , "target.add_shflags" , "target.add_defines" , "target.add_undefines" , "target.add_frameworks" , "target.add_rpathdirs" -- @note do not translate path, it's usually an absolute path or contains $ORIGIN/@loader_path , "target.add_forceincludes" -- option.add_xxx , "option.add_cincludes" , "option.add_cfuncs" , "option.add_ctypes" , "option.add_links" , "option.add_syslinks" , "option.add_cflags" , "option.add_cxflags" , "option.add_ldflags" , "option.add_arflags" , "option.add_shflags" , "option.add_defines" , "option.add_undefines" , "option.add_frameworks" , "option.add_rpathdirs" -- package.add_xxx , "package.add_links" , "package.add_syslinks" , "package.add_cflags" , "package.add_cxflags" , "package.add_ldflags" , "package.add_arflags" , "package.add_shflags" , "package.add_defines" , "package.add_undefines" , "package.add_frameworks" , "package.add_rpathdirs" , "package.add_linkdirs" , "package.add_includedirs" --@note we need not uses paths for package, see https://github.com/xmake-io/xmake/issues/717 , "package.add_sysincludedirs" , "package.add_frameworkdirs" -- toolchain.add_xxx , "toolchain.add_links" , "toolchain.add_syslinks" , "toolchain.add_cflags" , "toolchain.add_cxflags" , "toolchain.add_ldflags" , "toolchain.add_arflags" , "toolchain.add_shflags" , "toolchain.add_defines" , "toolchain.add_undefines" , "toolchain.add_frameworks" , "toolchain.add_rpathdirs" , "toolchain.add_linkdirs" , "toolchain.add_includedirs" , "toolchain.add_sysincludedirs" , "toolchain.add_frameworkdirs" } apis.groups = { -- target.add_xxx "target.add_linkorders" , "target.add_linkgroups" -- package.add_xxx , "package.add_linkorders" , "package.add_linkgroups" } apis.paths = { -- target.set_xxx "target.set_pcheader" -- target.add_xxx , "target.add_headerfiles" , "target.add_linkdirs" , "target.add_includedirs" , "target.add_sysincludedirs" , "target.add_frameworkdirs" -- option.add_xxx , "option.add_linkdirs" , "option.add_includedirs" , "option.add_sysincludedirs" , "option.add_frameworkdirs" } apis.dictionary = { -- option.add_xxx "option.add_csnippets" } return apis end function main() return {apis = _get_apis()} end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/c/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 -- language("c") add_rules("c") set_sourcekinds {cc = ".c"} set_sourceflags {cc = {"cflags", "cxflags"}} set_targetkinds {binary = "ld", static = "ar", shared = "sh"} set_targetflags {binary = "ldflags", static = "arflags", shared = "shflags"} set_langkinds {c = "cc"} set_mixingkinds("cc", "cxx", "as", "mrc") on_load("load") on_check_main("check_main") set_nameflags { object = { "config.includedirs" , "config.frameworkdirs" , "config.frameworks" , "target.symbols" , "target.warnings" , "target.fpmodels" , "target.optimize:check" , "target.vectorexts:check" , "target.languages" , "target.runtimes" , "target.includedirs" , "target.defines" , "target.undefines" , "target.frameworkdirs" , "target.frameworks" , "target.exceptions" , "target.encodings" , "target.pcheader" , "target.forceincludes" , "toolchain.includedirs" , "toolchain.defines" , "toolchain.undefines" , "toolchain.frameworkdirs" , "toolchain.frameworks" , "target.sysincludedirs" , "toolchain.sysincludedirs" } , binary = { "config.linkdirs" , "config.frameworkdirs" , "target.linkdirs" , "target.frameworkdirs" , "target.rpathdirs" , "target.strip" , "target.symbols" , "target.optimize:check" , "target.runtimes" , "toolchain.linkdirs" , "toolchain.rpathdirs" , "toolchain.frameworkdirs" , "config.links" , "target.linkgroups" -- we must move it before target.links, because we need sort correct order for package and its deps , "target.links" , "toolchain.links" , "config.frameworks" , "target.frameworks" , "toolchain.frameworks" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , shared = { "config.linkdirs" , "config.frameworkdirs" , "target.linkdirs" , "target.frameworkdirs" , "target.rpathdirs" , "target.strip" , "target.symbols" , "target.optimize:check" , "target.runtimes" , "toolchain.linkdirs" , "toolchain.rpathdirs" , "toolchain.frameworkdirs" , "config.links" , "target.links" , "target.linkgroups" , "toolchain.links" , "config.frameworks" , "target.frameworks" , "toolchain.frameworks" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , static = { "target.strip" , "target.symbols" } } set_menu { config = { {category = "Cross Complation Configuration/Compiler Configuration" } , {nil, "cc", "kv", nil, "The C Compiler" } , {nil, "cpp", "kv", nil, "The C/C++ Preprocessor" } , {category = "Cross Complation Configuration/Linker Configuration" } , {nil, "ld", "kv", nil, "The Linker" } , {nil, "ar", "kv", nil, "The Static Library Linker" } , {nil, "sh", "kv", nil, "The Shared Library Linker" } , {nil, "ranlib", "kv", nil, "The Static Library Index Generator" } , {category = "Cross Complation Configuration/Compiler Flags Configuration" } , {nil, "cflags", "kv", nil, "The C Compiler Flags" } , {nil, "cxflags", "kv", nil, "The C/C++ compiler Flags" } , {category = "Cross Complation Configuration/Linker Flags Configuration" } , {nil, "ldflags", "kv", nil, "The Binary Linker Flags" } , {nil, "arflags", "kv", nil, "The Static Library Linker Flags" } , {nil, "shflags", "kv", nil, "The Shared Library Linker Flags" } , {category = "Cross Complation Configuration/Builtin Flags Configuration" } , {nil, "links", "kv", nil, "The Link Libraries" } , {nil, "syslinks", "kv", nil, "The System Link Libraries" } , {nil, "linkdirs", "kv", nil, "The Link Search Directories" } , {nil, "includedirs", "kv", nil, "The Include Search Directories" } , {nil, "frameworks", "kv", nil, "The Frameworks" } , {nil, "frameworkdirs", "kv", nil, "The Frameworks Search Directories" } } }
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/golang/check_main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file check_main.lua -- -- check it function main(sourcefile) -- load source code local sourcecode = io.readfile(sourcefile) -- remove comment first sourcecode = sourcecode:gsub("/%*.-%*/", "") sourcecode = sourcecode:gsub("//.-\n", "\n") -- find func main() { if sourcecode:find("func%s+main%s*%(.-%)") then return true end -- no main function return false end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/golang/load.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- function _get_apis() local apis = {} apis.values = { -- target.add_xxx "target.add_links" , "target.add_syslinks" , "target.add_gcflags" , "target.add_ldflags" , "target.add_arflags" -- option.add_xxx , "option.add_links" , "option.add_syslinks" , "option.add_gcflags" , "option.add_ldflags" , "option.add_arflags" -- toolchain.add_xxx , "toolchain.add_links" , "toolchain.add_syslinks" , "toolchain.add_gcflags" , "toolchain.add_ldflags" , "toolchain.add_arflags" } apis.paths = { -- target.add_xxx "target.add_linkdirs" , "target.add_includedirs" , "target.add_sysincludedirs" -- option.add_xxx , "option.add_linkdirs" , "option.add_includedirs" , "option.add_sysincludedirs" } return apis end function main() return {apis = _get_apis()} end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/golang/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 -- language("golang") add_rules("go") set_sourcekinds {gc = ".go"} set_sourceflags {gc = "gcflags"} set_targetkinds {binary = "gcld", static = "gcar"} set_targetflags {binary = "ldflags", static = "arflags"} set_langkinds {go = "gc"} set_mixingkinds("gc") on_load("load") on_check_main("check_main") set_nameflags { object = { "config.includedirs" , "target.symbols" , "target.warnings" , "target.optimize:check" , "target.vectorexts:check" , "target.defines" , "target.undefines" , "target.includedirs" , "toolchain.includedirs" , "toolchain.defines" , "toolchain.undefines" , "target.sysincludedirs" , "toolchain.sysincludedirs" } , binary = { "config.linkdirs" , "target.linkdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "config.links" , "target.links" , "toolchain.links" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , shared = { "config.linkdirs" , "target.linkdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "config.links" , "target.links" , "toolchain.links" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } } set_menu { config = { {category = "Cross Complation Configuration/Compiler Configuration" } , {nil, "go", "kv", nil, "The Golang Compiler" } , {category = "Cross Complation Configuration/Linker Configuration" } , {nil, "gcld", "kv", nil, "The Golang Linker" } , {nil, "go-ar", "kv", nil, "The Golang Static Library Linker" } , {category = "Cross Complation Configuration/Builtin Flags Configuration" } , {nil, "links", "kv", nil, "The Link Libraries" } , {nil, "syslinks", "kv", nil, "The System Link Libraries" } , {nil, "linkdirs", "kv", nil, "The Link Search Directories" } , {nil, "includedirs","kv", nil, "The Include Search Directories" } } }
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/fortran/check_main.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file check_main.lua -- -- check it function main(sourcefile) -- load source code local sourcecode = io.readfile(sourcefile) -- remove comment first sourcecode = sourcecode:gsub("!.-\n", "\n") -- find 'program xxx' if sourcecode:find("program%s*%(.-%)") then return true end -- no main function return false end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/fortran/load.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- function _get_apis() local apis = {} apis.values = { -- target.add_xxx "target.add_links" , "target.add_syslinks" , "target.add_fcflags" , "target.add_ldflags" , "target.add_arflags" , "target.add_shflags" , "target.add_rpathdirs" -- @note do not translate path, it's usually an absolute path or contains $ORIGIN/@loader_path -- option.add_xxx , "option.add_links" , "option.add_syslinks" , "option.add_fcflags" , "option.add_ldflags" , "option.add_arflags" , "option.add_shflags" , "option.add_rpathdirs" -- package.add_xxx , "package.add_links" , "package.add_syslinks" , "package.add_fcflags" , "package.add_ldflags" , "package.add_arflags" , "package.add_shflags" , "package.add_rpathdirs" , "package.add_linkdirs" , "package.add_includedirs" , "package.add_sysincludedirs" -- toolchain.add_xxx , "toolchain.add_links" , "toolchain.add_syslinks" , "toolchain.add_fcflags" , "toolchain.add_ldflags" , "toolchain.add_arflags" , "toolchain.add_shflags" , "toolchain.add_rpathdirs" , "toolchain.add_linkdirs" , "toolchain.add_includedirs" , "toolchain.add_sysincludedirs" } apis.paths = { -- target.add_xxx "target.add_linkdirs" , "target.add_includedirs" , "target.add_sysincludedirs" -- option.add_xxx , "option.add_linkdirs" , "option.add_includedirs" , "option.add_sysincludedirs" } return apis end function main() return {apis = _get_apis()} end
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/fortran/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 -- language("fortran") add_rules("fortran") set_sourcekinds {fc = {".f03", ".f90", ".f95", ".for", ".f"}} set_sourceflags {fc = "fcflags"} set_targetkinds {binary = "fcld", static = "ar", shared = "fcsh"} set_targetflags {binary = "ldflags", static = "arflags", shared = "shflags"} set_langkinds {fortran = "fc"} set_mixingkinds("fc", "cc", "cxx", "as") on_load("load") on_check_main("check_main") set_nameflags { object = { "config.includedirs" , "target.symbols" , "target.warnings" , "target.optimize:check" , "target.vectorexts:check" , "target.includedirs" , "toolchain.includedirs" , "target.sysincludedirs" , "toolchain.sysincludedirs" } , binary = { "config.linkdirs" , "target.linkdirs" , "target.rpathdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "toolchain.rpathdirs" , "config.links" , "target.links" , "toolchain.links" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , shared = { "config.linkdirs" , "target.linkdirs" , "target.strip" , "target.symbols" , "toolchain.linkdirs" , "config.links" , "target.links" , "toolchain.links" , "config.syslinks" , "target.syslinks" , "toolchain.syslinks" } , static = { "target.strip" , "target.symbols" } } set_menu { config = { {category = "Cross Complation Configuration/Compiler Configuration" } , {nil, "fc", "kv", nil, "The Fortran Compiler" } , {category = "Cross Complation Configuration/Linker Configuration" } , {nil, "fcld", "kv", nil, "The Fortran Linker" } , {nil, "fcsh", "kv", nil, "The Fortran Shared Library Linker" } , {category = "Cross Complation Configuration/Builtin Flags Configuration" } , {nil, "links", "kv", nil, "The Link Libraries" } , {nil, "syslinks", "kv", nil, "The System Link Libraries" } , {nil, "linkdirs", "kv", nil, "The Link Search Directories" } , {nil, "includedirs","kv", nil, "The Include Search Directories" } } }
0
repos/xmake/xmake/languages
repos/xmake/xmake/languages/msrc/load.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file load.lua -- function _get_apis() local apis = {} apis.values = { -- target.add_xxx "target.add_mrcflags" -- option.add_xxx , "option.add_mrcflags" -- toolchain.add_xxx , "toolchain.add_mrcflags" } apis.paths = { -- target.add_xxx "target.add_includedirs" , "target.add_sysincludedirs" -- option.add_xxx , "option.add_includedirs" , "option.add_sysincludedirs" } return apis end function main() return {apis = _get_apis()} end