Maintain Visual Studio project guids between Premake regenerations

By default premake will generate a new guid for Visual Studio projects every time it is run. If you are creating all your solutions at once with each solution in a different premake file then sharing projects between solutions can result in the solution that was generated first referencing the wrong project guids.

To retrieve the existing guid from a Visual Studio project you can use the following script functions.

local fileext = "vcproj"
local pattern = "ProjectGUID=\"{(.+)}\""
 
if _ACTION == "vs2010" then
	fileext = "vcxproj"
	pattern = "<ProjectGuid>{(.+)}</ProjectGuid>"
end
 
local is_visual_studio = function()
	return string.startswith(_ACTION, "vs20")
end
 
local get_existing_uuid = function(p)
	if is_visual_studio() then
		local filename = string.format("%s.%s", p.name, fileext)
		local filepath = path.join(p.location, filename)
 
		local file, errmsg, errno = io.open(filepath, "r")
		if not file then
			return nil
		end
 
		local content = file:read("*all")
 
		local _, _, guid = string.find(content, pattern)
		file:close()
 
                return guid
	end
 
	return nil
end

Then later in your project definition somewhere you can find the existing uuid for the project or use the newly generated one as follows.

if is_visual_studio() then
	local p = project()
	p.uuid = get_existing_uuid(p) or p.uuid
end

This method of reusing guids also allows you to compare the newly generated file with an old file to check for changes without the noise of guids changing getting in the way. If you perform this check before replacing the generated project file while visual studio is running you should minimise the number of dialog popups complaining about project changes to only the project files that have changed.

* EDIT: added return guid and corrected the code block to use lua highlighting, thanks to Anonymous and annulen for the fixes *

And remember that you can also set your own GUID for the project, instead of allowing a random one to be generated.

Sorry I should have read those docs on uuid a bit more thoroughly as I see you've already covered the visual studio problem there.

No worries! This is still a good tip.

In get_existing_uuid() you are missing a

return guid

Not that it's a big deal, but maybe some people will just copy paste and see it doesn't work and not even look at why!
Thanks!

Good spot should be fixed now, thanks.

mopey: You can also wrap your snippet in <code lang="lua"> to set up proper highlighting

Fixed again, thanks.