]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/BuildEnv.py
1. Add DPC protocol and DpcLib library in MdeModulePkg.
[mirror_edk2.git] / BaseTools / BuildEnv.py
1 ## @file BuildEnv.py
2 # Initialize Environment for building
3 #
4 # Copyright (c) 2007, Intel Corporation
5 #
6 # All rights reserved. This program and the accompanying materials
7 # are licensed and made available under the terms and conditions of the BSD License
8 # which accompanies this distribution. The full text of the license may be found at
9 # http://opensource.org/licenses/bsd-license.php
10 #
11 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
13 #
14
15 ##
16 # Import Modules
17 #
18 import os
19 import os.path
20 import pickle
21 import shutil
22 import sys
23
24 from optparse import OptionParser
25
26 # Version and Copyright
27 VersionNumber = "0.01"
28 __version__ = "%prog Version " + VersionNumber
29 __copyright__ = "Copyright (c) 2007, Intel Corporation All rights reserved."
30
31 class SetupBuildEnvironmentApp:
32
33 def __init__(self):
34 (self.Opt, self.Args) = self.ProcessCommandLine()
35 self.SetupDefaults()
36 self.DetermineEnvironment()
37 self.DeleteEnvironmentConfigurationScript()
38 self.CopyTemplates()
39 self.WriteEnvironmentConfigurationScript()
40
41 def SetupDefaults(self):
42 self.itemsToConfigure = (
43 'compiler',
44 #'compiler-prefix',
45 'templates',
46 )
47
48 self.defaults = {
49 'compiler': {
50 'options': ('gcc', 'icc'),
51 'default': 'gcc',
52 },
53 'compiler-prefix': {
54 'options': ('/usr/bin', '/usr/bin/x86_64-pc-mingw32-'),
55 'freeform': True,
56 },
57 'templates': {
58 'description': 'templates and Conf directory',
59 'options': (
60 'copy once (no-overwrite)',
61 'copy with overwrite',
62 'symlink to templates',
63 'do nothing',
64 ),
65 'default': 'copy once (no-overwrite)',
66 },
67 }
68
69 def ProcessCommandLine(self):
70 Parser = OptionParser(description=__copyright__,version=__version__,prog="BaseTools/BuildEnv")
71 Parser.add_option("-q", "--quiet", action="store_true", type=None, help="Disable all messages except FATAL ERRORS.")
72 Parser.add_option("-v", "--verbose", action="store_true", type=None, help="Turn on verbose output with informational messages printed, "\
73 "including library instances selected, final dependency expression, "\
74 "and warning messages, etc.")
75 Parser.add_option("-d", "--debug", action="store", type="int", help="Enable debug messages at specified level.")
76
77 if os.environ.has_key('WORKSPACE'):
78 default = os.environ['WORKSPACE']
79 else:
80 default = os.getcwd()
81 Parser.add_option("--workspace", action="store", type="string", help="Base director of tree to configure", default=default)
82
83 (Opt, Args)=Parser.parse_args()
84 Parser.print_version()
85
86 return (Opt, Args)
87
88 def DetermineEnvironment(self):
89 confFilename = os.path.join(os.path.expanduser('~'), '.edk-build-env.pickle')
90 try:
91 confFile = open(confFilename, 'r')
92 conf = pickle.load(confFile)
93 confFile.close()
94 except Exception:
95 conf = {}
96 self.conf = conf
97
98 for item in self.itemsToConfigure:
99 if not conf.has_key(item):
100 self.AskForValueOfOption(item)
101
102 while True:
103 self.SummarizeCurrentState()
104
105 if not self.Opt.quiet:
106 response = raw_input('Would you like to change anything? (default=no): ')
107 response = response.strip()
108 else:
109 response = ''
110
111 if response.lower() in ('', 'n', 'no'):
112 break
113
114 for item in self.itemsToConfigure:
115 self.AskForValueOfOption(item)
116
117 confFile = open(confFilename, 'w')
118 pickle.dump(conf, confFile)
119 confFile.close()
120
121 def AskForValueOfOption(self, option):
122
123 options = self.defaults[option]['options']
124
125 if self.defaults[option].has_key('default'):
126 default = self.defaults[option]['default']
127 else:
128 default = None
129
130 if self.defaults[option].has_key('freeform'):
131 freeform = self.defaults[option]['freeform']
132 else:
133 freeform = False
134
135 if self.defaults[option].has_key('description'):
136 description = self.defaults[option]['description']
137 else:
138 description = option
139
140 conf = self.conf
141 if conf.has_key(option):
142 default = conf[option]
143 options = list(options) # in case options came in as a tuple
144 assert((default == '') or (default is None) or ('' not in options))
145 if (default is not None) and (default not in options):
146 options.append(default)
147 if (freeform and ('' not in options)):
148 options.append('')
149 options.sort()
150 while True:
151 print
152 if len(options) > 0:
153 print 'Options for', description
154 for i in range(len(options)):
155 print ' %d.' % (i + 1),
156 if options[i] != '':
157 print options[i],
158 else:
159 print '(empty string)',
160 if options[i] == default:
161 print '(default)'
162 else:
163 print
164
165 if len(options) > 0:
166 prompt = 'Select number or type value: '
167 else:
168 prompt = 'Type value: '
169 response = raw_input(prompt)
170 response = response.strip()
171
172 if response.isdigit():
173 response = int(response)
174 if response > len(options):
175 print 'ERROR: Invalid number selection!'
176 continue
177 response = options[response - 1]
178 elif (response == '') and (default is not None):
179 response = default
180
181 if (not freeform) and (response not in options):
182 print 'ERROR: Invalid selection! (must be from list)'
183 continue
184
185 break
186
187 conf[option] = response
188 print 'Using', conf[option], 'for', description
189
190 def SummarizeCurrentState(self):
191 print
192 print 'Current configuration:'
193 conf = self.conf
194 for item in self.itemsToConfigure:
195 value = conf[item]
196 if value == '': value = '(empty string)'
197 print ' ', item, '->', value
198
199 def CopyTemplates(self):
200 todo = self.conf['templates']
201 workspace = os.path.realpath(self.Opt.workspace)
202 templatesDir = \
203 os.path.join(workspace, 'BaseTools', 'Conf')
204 confDir = \
205 os.path.join(workspace, 'Conf')
206 print
207 print 'Templates & Conf directory'
208 print ' Templates dir:', self.RelativeToWorkspace(templatesDir)
209 for filename in os.listdir(templatesDir):
210 if not filename.endswith('.template'): continue
211
212 srcFilename = os.path.join(templatesDir, filename)
213 destFilename = os.path.join(confDir, filename[:-len('template')] + 'txt')
214 print ' ', self.RelativeToWorkspace(destFilename),
215
216 if todo == 'copy once (no-overwrite)':
217 if os.path.exists(destFilename):
218 print '[skipped, already exists]'
219 else:
220 shutil.copy(srcFilename, destFilename)
221 print '[copied]'
222 elif todo == 'copy with overwrite':
223 overwrite = ''
224 if os.path.exists(destFilename):
225 os.remove(destFilename)
226 overwrite = ', overwritten'
227 shutil.copy(srcFilename, destFilename)
228 print '[copied' + overwrite + ']'
229 elif todo == 'symlink to templates':
230 if os.path.islink(destFilename) or os.path.exists(destFilename):
231 if not os.path.islink(destFilename):
232 raise Exception, '%s is not a symlink! (remove file if you want to start using symlinks)' % \
233 (self.RelativeToWorkspace(destFilename))
234 os.remove(destFilename)
235 os.symlink(os.path.join('..', self.RelativeToWorkspace(srcFilename)), destFilename)
236 print '[symlinked]'
237 elif todo == 'do nothing':
238 print '[skipped by user request]'
239 else:
240 raise Exception, 'Unknown action for templates&conf: %s' % todo
241
242 def DeleteEnvironmentConfigurationScript(self):
243 workspace = os.path.realpath(self.Opt.workspace)
244 scriptFilename = os.path.join(workspace, 'Conf', 'BuildEnv.sh')
245 if os.path.exists(scriptFilename):
246 os.remove(scriptFilename)
247
248 def WriteEnvironmentConfigurationScript(self):
249 workspace = os.path.realpath(self.Opt.workspace)
250 scriptFilename = os.path.join(workspace, 'Conf', 'BuildEnv.sh')
251 print
252 print 'Storing environment configuration into',
253 print self.RelativeToWorkspace(scriptFilename)
254 script = open(scriptFilename, 'w')
255
256 print >> script, 'export WORKSPACE="%s"' % workspace
257 print >> script, 'export TOOLCHAIN="%s"' % self.conf['compiler']
258 #print >> script, 'export COMPILER_SUITE_PATH_PREFIX="%s"' % self.conf['compiler-prefix']
259
260 EDK_TOOLS_PATH = os.path.join(workspace, 'BaseTools')
261 print >> script, 'if [ $EDK_TOOLS_PATH=="" ]'
262 print >> script, 'then'
263 print >> script, ' export EDK_TOOLS_PATH="%s"' % EDK_TOOLS_PATH
264 print >> script, 'fi'
265
266 #
267 # Change PATH variable
268 #
269 newPath = os.environ['PATH'].split(os.path.pathsep)
270 binDir = \
271 os.path.join(workspace, 'BaseTools', 'Bin', sys.platform.title())
272 if binDir not in newPath:
273 newPath.append(binDir)
274 newPath = os.path.pathsep.join(newPath)
275 print >> script, 'export PATH=%s' % newPath
276
277 script.close()
278
279 def RelativeToWorkspace(self, path):
280 workspace = os.path.realpath(self.Opt.workspace)
281 for prefix in (workspace + os.path.sep, workspace):
282 if path.startswith(prefix):
283 return path[len(prefix):]
284
285 if __name__ == '__main__':
286 SetupBuildEnvironmentApp()
287