I'd like to be able to set some arbitrary properties in my premake-generated Visual Studio projects, as a site policy rather than on a per-project basis.
Here's an example that works, but it's not ideal. This is in my premake5-system.lua startup file. It overrides the project generator used by the vs2015 action to in turn conditionally override the project property generation function.
premake.override(premake.action._list.vs2015, 'onProject', function(base, prj)
-- For C# libraries force static code analysis on.
if premake.project.isdotnet(prj) and prj.kind == premake.SHAREDLIB then
premake.override(premake.vstudio.cs2005, "compilerProps", function(base, cfg)
_p(2, '<RunCodeAnalysis>true</RunCodeAnalysis>')
base(cfg)
end)
end
base(prj)
end)
I do not like the fact that this snippet mentions VS2015 explicitly, because that means I'd have to duplicate it for other VS versions. I do not like that it mentions the cs2005 project generator explicitly, because if premake ever stops using the 2005 property emitter for later versions of VS then this will break.
Can this be made more generic, or is this even the right approach?
Update:
I've discovered that the scheme of adding overrides inside an override of onProject() is flawed because if there are multiple projects in the workspace, the interior overrides will be added multiple times and thus emit the custom properties multiple times in some of the projects. Here's an improved version but I'd still like to know how to avoid the brittleness that comes from overriding cs2005 directly:
premake.override(premake.vstudio.cs2005, "compilerProps", function(base, cfg)
local prj = cfg.project
if premake.project.isdotnet(prj) then
_p(2, '<RunCodeAnalysis>true</RunCodeAnalysis>')
end
base(cfg)
end)
I suppose the right answer is to create a new a project API call, use the new value in csproj.compilerProps
, and then submit a pull request. There is nothing controversial about this feature, and it should be easy to merge…and then you won't have to maintain the override.
Something like this in _premake_init.lua
:
api.register {
name = "codeanalysis",
scope = "config",
kind = "boolean",
}
And this in vs2005_csproj.lua
:
if cfg.codeanalysis then
_p(2, '<RunCodeAnalysis>true</RunCodeAnalysis>')
end
And then you could use it in your project scripts:
codeanalysis "On" -- or "true" or "yes"
For bonus points, you could refactor csproj.compilerProps
to use the new, more extensible "call array" approach like vs2010_vcxproj.lua
:
m.elements.compilerProps = function(cfg)
return {
m.defineConstants,
m.errorReport,
m.runCodeAnalysis,
m.warningLevel,
m.allowUnsafeBlocks,
m.treatWarningsAsErrors,
m.commandLineParameters,
}
end)
function cs2005.compilerProps(cfg)
p.callArray(m.elements.compilerProps, cfg)
end
function m.defineConstants(cfg)
_x(2,'<DefineConstants>%s</DefineConstants>', table.concat(cfg.defines, ";"))
end
-- and so on…