Sync BaseTools Branch (version r2321) to EDKII main trunk.
[mirror_edk2.git] / BaseTools / Source / Python / TargetTool / TargetTool.py
1 #
2 # Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
3 #
4 # This program and the accompanying materials
5 # are licensed and made available under the terms and conditions of the BSD License
6 # which accompanies this distribution. The full text of the license may be found at
7 # http://opensource.org/licenses/bsd-license.php
8 #
9 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
11 #
12
13 import os
14 import sys
15 import traceback
16 from optparse import OptionParser
17
18 import Common.EdkLogger as EdkLogger
19 import Common.BuildToolError as BuildToolError
20 from Common.DataType import *
21 from Common.BuildVersion import gBUILD_VERSION
22
23 # To Do 1.set clean, 2. add item, if the line is disabled.
24
25 class TargetTool():
26 def __init__(self, opt, args):
27 self.WorkSpace = os.path.normpath(os.getenv('WORKSPACE'))
28 self.Opt = opt
29 self.Arg = args[0]
30 self.FileName = os.path.normpath(os.path.join(self.WorkSpace, 'Conf', 'target.txt'))
31 if os.path.isfile(self.FileName) == False:
32 print "%s does not exist." % self.FileName
33 sys.exit(1)
34 self.TargetTxtDictionary = {
35 TAB_TAT_DEFINES_ACTIVE_PLATFORM : None,
36 TAB_TAT_DEFINES_TOOL_CHAIN_CONF : None,
37 TAB_TAT_DEFINES_MAX_CONCURRENT_THREAD_NUMBER : None,
38 TAB_TAT_DEFINES_TARGET : None,
39 TAB_TAT_DEFINES_TOOL_CHAIN_TAG : None,
40 TAB_TAT_DEFINES_TARGET_ARCH : None,
41 TAB_TAT_DEFINES_BUILD_RULE_CONF : None,
42 }
43 self.LoadTargetTxtFile(self.FileName)
44
45 def LoadTargetTxtFile(self, filename):
46 if os.path.exists(filename) and os.path.isfile(filename):
47 return self.ConvertTextFileToDict(filename, '#', '=')
48 else:
49 raise ParseError('LoadTargetTxtFile() : No Target.txt file exists.')
50 return 1
51
52 #
53 # Convert a text file to a dictionary
54 #
55 def ConvertTextFileToDict(self, FileName, CommentCharacter, KeySplitCharacter):
56 """Convert a text file to a dictionary of (name:value) pairs."""
57 try:
58 f = open(FileName,'r')
59 for Line in f:
60 if Line.startswith(CommentCharacter) or Line.strip() == '':
61 continue
62 LineList = Line.split(KeySplitCharacter,1)
63 if len(LineList) >= 2:
64 Key = LineList[0].strip()
65 if Key.startswith(CommentCharacter) == False and Key in self.TargetTxtDictionary.keys():
66 if Key == TAB_TAT_DEFINES_ACTIVE_PLATFORM or Key == TAB_TAT_DEFINES_TOOL_CHAIN_CONF \
67 or Key == TAB_TAT_DEFINES_MAX_CONCURRENT_THREAD_NUMBER \
68 or Key == TAB_TAT_DEFINES_ACTIVE_MODULE:
69 self.TargetTxtDictionary[Key] = LineList[1].replace('\\', '/').strip()
70 elif Key == TAB_TAT_DEFINES_TARGET or Key == TAB_TAT_DEFINES_TARGET_ARCH \
71 or Key == TAB_TAT_DEFINES_TOOL_CHAIN_TAG or Key == TAB_TAT_DEFINES_BUILD_RULE_CONF:
72 self.TargetTxtDictionary[Key] = LineList[1].split()
73 f.close()
74 return 0
75 except:
76 last_type, last_value, last_tb = sys.exc_info()
77 traceback.print_exception(last_type, last_value, last_tb)
78
79 def Print(self):
80 KeyList = self.TargetTxtDictionary.keys()
81 errMsg = ''
82 for Key in KeyList:
83 if type(self.TargetTxtDictionary[Key]) == type([]):
84 print "%-30s = %s" % (Key, ''.join(elem + ' ' for elem in self.TargetTxtDictionary[Key]))
85 elif self.TargetTxtDictionary[Key] == None:
86 errMsg += " Missing %s configuration information, please use TargetTool to set value!" % Key + os.linesep
87 else:
88 print "%-30s = %s" % (Key, self.TargetTxtDictionary[Key])
89
90 if errMsg != '':
91 print os.linesep + 'Warning:' + os.linesep + errMsg
92
93 def RWFile(self, CommentCharacter, KeySplitCharacter, Num):
94 try:
95 fr = open(self.FileName, 'r')
96 fw = open(os.path.normpath(os.path.join(self.WorkSpace, 'Conf\\targetnew.txt')), 'w')
97
98 existKeys = []
99 for Line in fr:
100 if Line.startswith(CommentCharacter) or Line.strip() == '':
101 fw.write(Line)
102 else:
103 LineList = Line.split(KeySplitCharacter,1)
104 if len(LineList) >= 2:
105 Key = LineList[0].strip()
106 if Key.startswith(CommentCharacter) == False and Key in self.TargetTxtDictionary.keys():
107 if Key not in existKeys:
108 existKeys.append(Key)
109 else:
110 print "Warning: Found duplicate key item in original configuration files!"
111
112 if Num == 0:
113 Line = "%-30s = \n" % Key
114 else:
115 ret = GetConfigureKeyValue(self, Key)
116 if ret != None:
117 Line = ret
118 fw.write(Line)
119 for key in self.TargetTxtDictionary.keys():
120 if key not in existKeys:
121 print "Warning: %s does not exist in original configuration file" % key
122 Line = GetConfigureKeyValue(self, key)
123 if Line == None:
124 Line = "%-30s = " % key
125 fw.write(Line)
126
127 fr.close()
128 fw.close()
129 os.remove(self.FileName)
130 os.rename(os.path.normpath(os.path.join(self.WorkSpace, 'Conf\\targetnew.txt')), self.FileName)
131
132 except:
133 last_type, last_value, last_tb = sys.exc_info()
134 traceback.print_exception(last_type, last_value, last_tb)
135
136 def GetConfigureKeyValue(self, Key):
137 Line = None
138 if Key == TAB_TAT_DEFINES_ACTIVE_PLATFORM and self.Opt.DSCFILE != None:
139 dscFullPath = os.path.join(self.WorkSpace, self.Opt.DSCFILE)
140 if os.path.exists(dscFullPath):
141 Line = "%-30s = %s\n" % (Key, self.Opt.DSCFILE)
142 else:
143 EdkLogger.error("TagetTool", BuildToolError.FILE_NOT_FOUND,
144 "DSC file %s does not exist!" % self.Opt.DSCFILE, RaiseError=False)
145 elif Key == TAB_TAT_DEFINES_TOOL_CHAIN_CONF and self.Opt.TOOL_DEFINITION_FILE != None:
146 tooldefFullPath = os.path.join(self.WorkSpace, self.Opt.TOOL_DEFINITION_FILE)
147 if os.path.exists(tooldefFullPath):
148 Line = "%-30s = %s\n" % (Key, self.Opt.TOOL_DEFINITION_FILE)
149 else:
150 EdkLogger.error("TagetTool", BuildToolError.FILE_NOT_FOUND,
151 "Tooldef file %s does not exist!" % self.Opt.TOOL_DEFINITION_FILE, RaiseError=False)
152
153 elif self.Opt.NUM >= 2:
154 Line = "%-30s = %s\n" % (Key, 'Enable')
155 elif self.Opt.NUM <= 1:
156 Line = "%-30s = %s\n" % (Key, 'Disable')
157 elif Key == TAB_TAT_DEFINES_MAX_CONCURRENT_THREAD_NUMBER and self.Opt.NUM != None:
158 Line = "%-30s = %s\n" % (Key, str(self.Opt.NUM))
159 elif Key == TAB_TAT_DEFINES_TARGET and self.Opt.TARGET != None:
160 Line = "%-30s = %s\n" % (Key, ''.join(elem + ' ' for elem in self.Opt.TARGET))
161 elif Key == TAB_TAT_DEFINES_TARGET_ARCH and self.Opt.TARGET_ARCH != None:
162 Line = "%-30s = %s\n" % (Key, ''.join(elem + ' ' for elem in self.Opt.TARGET_ARCH))
163 elif Key == TAB_TAT_DEFINES_TOOL_CHAIN_TAG and self.Opt.TOOL_CHAIN_TAG != None:
164 Line = "%-30s = %s\n" % (Key, self.Opt.TOOL_CHAIN_TAG)
165 elif Key == TAB_TAT_DEFINES_BUILD_RULE_CONF and self.Opt.BUILD_RULE_FILE != None:
166 buildruleFullPath = os.path.join(self.WorkSpace, self.Opt.BUILD_RULE_FILE)
167 if os.path.exists(buildruleFullPath):
168 Line = "%-30s = %s\n" % (Key, self.Opt.BUILD_RULE_FILE)
169 else:
170 EdkLogger.error("TagetTool", BuildToolError.FILE_NOT_FOUND,
171 "Build rule file %s does not exist!" % self.Opt.BUILD_RULE_FILE, RaiseError=False)
172 return Line
173
174 VersionNumber = ("0.01" + " " + gBUILD_VERSION)
175 __version__ = "%prog Version " + VersionNumber
176 __copyright__ = "Copyright (c) 2007 - 2010, Intel Corporation All rights reserved."
177 __usage__ = "%prog [options] {args} \
178 \nArgs: \
179 \n Clean clean the all default configuration of target.txt. \
180 \n Print print the all default configuration of target.txt. \
181 \n Set replace the default configuration with expected value specified by option."
182
183 gParamCheck = []
184 def SingleCheckCallback(option, opt_str, value, parser):
185 if option not in gParamCheck:
186 setattr(parser.values, option.dest, value)
187 gParamCheck.append(option)
188 else:
189 parser.error("Option %s only allows one instance in command line!" % option)
190
191 def RangeCheckCallback(option, opt_str, value, parser):
192 if option not in gParamCheck:
193 gParamCheck.append(option)
194 if value < 1 or value > 8:
195 parser.error("The count of multi-thread is not in valid range of 1 ~ 8.")
196 else:
197 setattr(parser.values, option.dest, value)
198 else:
199 parser.error("Option %s only allows one instance in command line!" % option)
200
201 def MyOptionParser():
202 parser = OptionParser(version=__version__,prog="TargetTool.exe",usage=__usage__,description=__copyright__)
203 parser.add_option("-a", "--arch", action="append", type="choice", choices=['IA32','X64','IPF','EBC', 'ARM','0'], dest="TARGET_ARCH",
204 help="ARCHS is one of list: IA32, X64, IPF, ARM or EBC, which replaces target.txt's TARGET_ARCH definition. To specify more archs, please repeat this option. 0 will clear this setting in target.txt and can't combine with other value.")
205 parser.add_option("-p", "--platform", action="callback", type="string", dest="DSCFILE", callback=SingleCheckCallback,
206 help="Specify a DSC file, which replace target.txt's ACTIVE_PLATFORM definition. 0 will clear this setting in target.txt and can't combine with other value.")
207 parser.add_option("-c", "--tooldef", action="callback", type="string", dest="TOOL_DEFINITION_FILE", callback=SingleCheckCallback,
208 help="Specify the WORKSPACE relative path of tool_def.txt file, which replace target.txt's TOOL_CHAIN_CONF definition. 0 will clear this setting in target.txt and can't combine with other value.")
209 parser.add_option("-t", "--target", action="append", type="choice", choices=['DEBUG','RELEASE','0'], dest="TARGET",
210 help="TARGET is one of list: DEBUG, RELEASE, which replaces target.txt's TARGET definition. To specify more TARGET, please repeat this option. 0 will clear this setting in target.txt and can't combine with other value.")
211 parser.add_option("-n", "--tagname", action="callback", type="string", dest="TOOL_CHAIN_TAG", callback=SingleCheckCallback,
212 help="Specify the Tool Chain Tagname, which replaces target.txt's TOOL_CHAIN_TAG definition. 0 will clear this setting in target.txt and can't combine with other value.")
213 parser.add_option("-r", "--buildrule", action="callback", type="string", dest="BUILD_RULE_FILE", callback=SingleCheckCallback,
214 help="Specify the build rule configure file, which replaces target.txt's BUILD_RULE_CONF definition. If not specified, the default value Conf/build_rule.txt will be set.")
215 parser.add_option("-m", "--multithreadnum", action="callback", type="int", dest="NUM", callback=RangeCheckCallback,
216 help="Specify the multi-thread number which replace target.txt's MAX_CONCURRENT_THREAD_NUMBER. If the value is less than 2, MULTIPLE_THREAD will be disabled. If the value is larger than 1, MULTIPLE_THREAD will be enabled.")
217 (opt, args)=parser.parse_args()
218 return (opt, args)
219
220 if __name__ == '__main__':
221 EdkLogger.Initialize()
222 EdkLogger.SetLevel(EdkLogger.QUIET)
223 if os.getenv('WORKSPACE') == None:
224 print "ERROR: WORKSPACE should be specified or edksetup script should be executed before run TargetTool"
225 sys.exit(1)
226
227 (opt, args) = MyOptionParser()
228 if len(args) != 1 or (args[0].lower() != 'print' and args[0].lower() != 'clean' and args[0].lower() != 'set'):
229 print "The number of args isn't 1 or the value of args is invalid."
230 sys.exit(1)
231 if opt.NUM != None and opt.NUM < 1:
232 print "The MAX_CONCURRENT_THREAD_NUMBER must be larger than 0."
233 sys.exit(1)
234 if opt.TARGET != None and len(opt.TARGET) > 1:
235 for elem in opt.TARGET:
236 if elem == '0':
237 print "0 will clear the TARGET setting in target.txt and can't combine with other value."
238 sys.exit(1)
239 if opt.TARGET_ARCH != None and len(opt.TARGET_ARCH) > 1:
240 for elem in opt.TARGET_ARCH:
241 if elem == '0':
242 print "0 will clear the TARGET_ARCH setting in target.txt and can't combine with other value."
243 sys.exit(1)
244
245 try:
246 FileHandle = TargetTool(opt, args)
247 if FileHandle.Arg.lower() == 'print':
248 FileHandle.Print()
249 sys.exit(0)
250 elif FileHandle.Arg.lower() == 'clean':
251 FileHandle.RWFile('#', '=', 0)
252 else:
253 FileHandle.RWFile('#', '=', 1)
254 except Exception, e:
255 last_type, last_value, last_tb = sys.exc_info()
256 traceback.print_exception(last_type, last_value, last_tb)
257