1# -*- coding: utf-8 -*-
2
3import os
4import re
5import sys
6import argparse
7
8def readFile (filename):
9	f = open(filename, 'rb')
10	d = f.read()
11	f.close()
12	return d
13
14def writeFile (filename, data):
15	f = open(filename, 'wb')
16	f.write(data)
17	f.close()
18
19COMMIT	= 0
20REF		= 1
21
22def getCommitOrRef (filename):
23	src = readFile(filename)
24	m = re.search(r'^[a-zA-Z0-9]{40}', src)
25	if m:
26		return (COMMIT, m.group(0))
27	m = re.search(r'^ref:\s+([^\s]+)', src)
28	if m:
29		return (REF, m.group(1))
30	raise Exception("Coulnd't parse %s" % filename)
31
32def getHead (gitDir):
33	curFile = os.path.join(gitDir, "HEAD")
34	while True:
35		type, ptr = getCommitOrRef(curFile)
36		if type == COMMIT:
37			return ptr
38		else:
39			assert type == REF
40			curFile = os.path.join(gitDir, ptr)
41
42def makeReleaseInfo (name, id):
43	return """
44/* WARNING: auto-generated file, use {genFileName} to modify */
45
46#define DEQP_RELEASE_NAME	"{releaseName}"
47#define DEQP_RELEASE_ID		{releaseId}
48"""[1:].format(
49		genFileName	= os.path.basename(__file__),
50		releaseName	= name,
51		releaseId	= id)
52
53def parseArgs ():
54	parser = argparse.ArgumentParser(description="Generate release info for build")
55	parser.add_argument('--name', dest='releaseName', default=None, help="Release name")
56	parser.add_argument('--id', dest='releaseId', default=None, help="Release ID (must be C integer literal)")
57	parser.add_argument('--git', dest='git', action='store_true', default=False, help="Development build, use git HEAD to identify")
58	parser.add_argument('--git-dir', dest='gitDir', default=None, help="Use specific git dir for extracting info")
59	parser.add_argument('--out', dest='out', default=None, help="Output file")
60
61	args = parser.parse_args()
62
63	if (args.releaseName == None) != (args.releaseId == None):
64		print "Both --name and --id must be specified"
65		parser.print_help()
66		sys.exit(-1)
67
68	if (args.releaseName != None) == args.git:
69		print "Either --name and --id, or --git must be specified"
70		parser.print_help()
71		sys.exit(-1)
72
73	return args
74
75if __name__ == "__main__":
76	curDir			= os.path.dirname(__file__)
77	defaultGitDir	= os.path.normpath(os.path.join(curDir, "..", "..", ".git"))
78	defaultDstFile	= os.path.join(curDir, "qpReleaseInfo.inl")
79
80	args = parseArgs()
81
82	if args.git:
83		gitDir		= args.gitDir if args.gitDir != None else defaultGitDir
84		head		= getHead(gitDir)
85		releaseName	= "git-%s" % head
86		releaseId	= "0x%s" % head[0:8]
87	else:
88		releaseName	= args.releaseName
89		releaseId	= args.releaseId
90
91	releaseInfo	= makeReleaseInfo(releaseName, releaseId)
92	dstFile		= args.out if args.out != None else defaultDstFile
93
94	writeFile(dstFile, releaseInfo)
95