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