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