desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns the backend image objects from a ImageFile instance'
def get_image(self, source):
with NamedTemporaryFile(mode=u'wb', delete=False) as fp: fp.write(source.read()) return {u'source': fp.name, u'options': OrderedDict(), u'size': None}
'Returns the image width and height as a tuple'
def get_image_size(self, image):
if (image[u'size'] is None): args = settings.THUMBNAIL_VIPSHEADER.split(u' ') args.append(image[u'source']) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() m = size_re.match(str(p.stdout.read())) image[u'size'] = (int(m.group(u'x')), int(m.group(u'y'))) return image[u'size']
'vipsheader will try a lot of formats, including all those supported by imagemagick if compiled with magick support, this can take a while'
def is_valid_image(self, raw_data):
with NamedTemporaryFile(mode=u'wb') as fp: fp.write(raw_data) fp.flush() args = settings.THUMBNAIL_VIPSHEADER.split(u' ') args.append(fp.name) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retcode = p.wait() return (retcode == 0)
'vipsthumbnail does not support greyscaling of images, but pretend it does'
def _colorspace(self, image, colorspace):
return image
'Does the resizing of the image'
def _scale(self, image, width, height):
image[u'options'][u'size'] = (u'%sx%s' % (width, height)) image[u'size'] = (width, height) return image
'Substitutes (via the format operator) the values in the specified dictionary into the specified command. The command can be an (action, string) tuple. In all cases, we perform substitution on strings and don\'t worry if something isn\'t a string. (It\'s probably a Python function to be executed.)'
def subst(self, string, dictionary=None):
if (dictionary is None): dictionary = self._subst_dictionary if dictionary: try: string = (string % dictionary) except TypeError: pass return string
'Executes a single command.'
def execute(self, command, stdout=None, stderr=None):
if (not self.active): return 0 if (type(command) == type('')): command = self.subst(command) cmdargs = shlex.split(command) if (cmdargs[0] == 'cd'): command = ((os.chdir,) + tuple(cmdargs[1:])) if (type(command) == type(())): func = command[0] args = command[1:] return func(*args) else: if (stdout is sys.stdout): subout = None else: subout = subprocess.PIPE if (stderr is sys.stderr): suberr = None elif (stderr is None): suberr = subprocess.STDOUT else: suberr = subprocess.PIPE p = subprocess.Popen(command, shell=(sys.platform == 'win32'), stdout=subout, stderr=suberr) p.wait() if (stdout is None): self.stdout = p.stdout.read() elif (stdout is not sys.stdout): stdout.write(p.stdout.read()) if (stderr not in (None, sys.stderr)): stderr.write(p.stderr.read()) return p.returncode
'Runs a single command, displaying it first.'
def run(self, command, display=None, stdout=None, stderr=None):
if (display is None): display = command self.display(display) return self.execute(command, stdout, stderr)
'Handle the results of running LoadTargetBuildFile in another process.'
def LoadTargetBuildFileCallback(self, result):
self.condition.acquire() if (not result): self.error = True self.condition.notify() self.condition.release() return (build_file_path0, build_file_data0, dependencies0) = result self.data[build_file_path0] = build_file_data0 self.data['target_build_files'].add(build_file_path0) for new_dependency in dependencies0: if (new_dependency not in self.scheduled): self.scheduled.add(new_dependency) self.dependencies.append(new_dependency) self.pending -= 1 self.condition.notify() self.condition.release()
'Returns a list of cycles in the graph, where each cycle is its own list.'
def FindCycles(self):
results = [] visited = set() def Visit(node, path): for child in node.dependents: if (child in path): results.append(([child] + path[:(path.index(child) + 1)])) elif (not (child in visited)): visited.add(child) Visit(child, ([child] + path)) visited.add(self) Visit(self, [self]) return results
'Returns a list of just direct dependencies.'
def DirectDependencies(self, dependencies=None):
if (dependencies == None): dependencies = [] for dependency in self.dependencies: if ((dependency.ref != None) and (dependency.ref not in dependencies)): dependencies.append(dependency.ref) return dependencies
'Given a list of direct dependencies, adds indirect dependencies that other dependencies have declared to export their settings. This method does not operate on self. Rather, it operates on the list of dependencies in the |dependencies| argument. For each dependency in that list, if any declares that it exports the settings of one of its own dependencies, those dependencies whose settings are "passed through" are added to the list. As new items are added to the list, they too will be processed, so it is possible to import settings through multiple levels of dependencies. This method is not terribly useful on its own, it depends on being "primed" with a list of direct dependencies such as one provided by DirectDependencies. DirectAndImportedDependencies is intended to be the public entry point.'
def _AddImportedDependencies(self, targets, dependencies=None):
if (dependencies == None): dependencies = [] index = 0 while (index < len(dependencies)): dependency = dependencies[index] dependency_dict = targets[dependency] add_index = 1 for imported_dependency in dependency_dict.get('export_dependent_settings', []): if (imported_dependency not in dependencies): dependencies.insert((index + add_index), imported_dependency) add_index = (add_index + 1) index = (index + 1) return dependencies
'Returns a list of a target\'s direct dependencies and all indirect dependencies that a dependency has advertised settings should be exported through the dependency for.'
def DirectAndImportedDependencies(self, targets, dependencies=None):
dependencies = self.DirectDependencies(dependencies) return self._AddImportedDependencies(targets, dependencies)
'Returns an OrderedSet of all of a target\'s dependencies, recursively.'
def DeepDependencies(self, dependencies=None):
if (dependencies is None): dependencies = OrderedSet() for dependency in self.dependencies: if (dependency.ref is None): continue if (dependency.ref not in dependencies): dependency.DeepDependencies(dependencies) dependencies.add(dependency.ref) return dependencies
'Returns an OrderedSet of dependency targets that are linked into this target. This function has a split personality, depending on the setting of |initial|. Outside callers should always leave |initial| at its default setting. When adding a target to the list of dependencies, this function will recurse into itself with |initial| set to False, to collect dependencies that are linked into the linkable target for which the list is being built. If |include_shared_libraries| is False, the resulting dependencies will not include shared_library targets that are linked into this target.'
def _LinkDependenciesInternal(self, targets, include_shared_libraries, dependencies=None, initial=True):
if (dependencies is None): dependencies = OrderedSet() if (self.ref is None): return dependencies if ('target_name' not in targets[self.ref]): raise GypError("Missing 'target_name' field in target.") if ('type' not in targets[self.ref]): raise GypError(("Missing 'type' field in target %s" % targets[self.ref]['target_name'])) target_type = targets[self.ref]['type'] is_linkable = (target_type in linkable_types) if (initial and (not is_linkable)): return dependencies if ((target_type == 'none') and (not targets[self.ref].get('dependencies_traverse', True))): dependencies.add(self.ref) return dependencies if ((not initial) and (target_type in ('executable', 'loadable_module', 'mac_kernel_extension'))): return dependencies if ((not initial) and (target_type == 'shared_library') and (not include_shared_libraries)): return dependencies if (self.ref not in dependencies): dependencies.add(self.ref) if (initial or (not is_linkable)): for dependency in self.dependencies: dependency._LinkDependenciesInternal(targets, include_shared_libraries, dependencies, False) return dependencies
'Returns a list of dependency targets whose link_settings should be merged into this target.'
def DependenciesForLinkSettings(self, targets):
include_shared_libraries = targets[self.ref].get('allow_sharedlib_linksettings_propagation', True) return self._LinkDependenciesInternal(targets, include_shared_libraries)
'Returns a list of dependency targets that are linked into this target.'
def DependenciesToLinkAgainst(self, targets):
return self._LinkDependenciesInternal(targets, True)
'Returns the number of \'$\' characters right in front of s[i].'
def _count_dollars_before_index(self, s, i):
dollar_count = 0 dollar_index = (i - 1) while ((dollar_index > 0) and (s[dollar_index] == '$')): dollar_count += 1 dollar_index -= 1 return dollar_count
'Write \'text\' word-wrapped at self.width characters.'
def _line(self, text, indent=0):
leading_space = (' ' * indent) while ((len(leading_space) + len(text)) > self.width): available_space = ((self.width - len(leading_space)) - len(' $')) space = available_space while True: space = text.rfind(' ', 0, space) if ((space < 0) or ((self._count_dollars_before_index(text, space) % 2) == 0)): break if (space < 0): space = (available_space - 1) while True: space = text.find(' ', (space + 1)) if ((space < 0) or ((self._count_dollars_before_index(text, space) % 2) == 0)): break if (space < 0): break self.output.write(((leading_space + text[0:space]) + ' $\n')) text = text[(space + 1):] leading_space = (' ' * (indent + 2)) self.output.write(((leading_space + text) + '\n'))
'Initializes the tool. Args: name: Tool name. attrs: Dict of tool attributes; may be None.'
def __init__(self, name, attrs=None):
self._attrs = (attrs or {}) self._attrs['Name'] = name
'Creates an element for the tool. Returns: A new xml.dom.Element for the tool.'
def _GetSpecification(self):
return ['Tool', self._attrs]
'Initializes the folder. Args: name: Filter (folder) name. contents: List of filenames and/or Filter objects contained.'
def __init__(self, name, contents=None):
self.name = name self.contents = list((contents or []))
'Initializes the project. Args: project_path: Path to the project file. version: Format version to emit. name: Name of the project. guid: GUID to use for project, if not None. platforms: Array of string, the supported platforms. If null, [\'Win32\']'
def __init__(self, project_path, version, name, guid=None, platforms=None):
self.project_path = project_path self.version = version self.name = name self.guid = guid if (not platforms): platforms = ['Win32'] self.platform_section = ['Platforms'] for platform in platforms: self.platform_section.append(['Platform', {'Name': platform}]) self.tool_files_section = ['ToolFiles'] self.configurations_section = ['Configurations'] self.files_section = ['Files'] self.files_dict = dict()
'Adds a tool file to the project. Args: path: Relative path from project to tool file.'
def AddToolFile(self, path):
self.tool_files_section.append(['ToolFile', {'RelativePath': path}])
'Returns the specification for a configuration. Args: config_type: Type of configuration node. config_name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Returns:'
def _GetSpecForConfiguration(self, config_type, config_name, attrs, tools):
if (not attrs): attrs = {} if (not tools): tools = [] node_attrs = attrs.copy() node_attrs['Name'] = config_name specification = [config_type, node_attrs] if tools: for t in tools: if isinstance(t, Tool): specification.append(t._GetSpecification()) else: specification.append(Tool(t)._GetSpecification()) return specification
'Adds a configuration to the project. Args: name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None.'
def AddConfig(self, name, attrs=None, tools=None):
spec = self._GetSpecForConfiguration('Configuration', name, attrs, tools) self.configurations_section.append(spec)
'Adds files and/or filters to the parent node. Args: parent: Destination node files: A list of Filter objects and/or relative paths to files. Will call itself recursively, if the files list contains Filter objects.'
def _AddFilesToNode(self, parent, files):
for f in files: if isinstance(f, Filter): node = ['Filter', {'Name': f.name}] self._AddFilesToNode(node, f.contents) else: node = ['File', {'RelativePath': f}] self.files_dict[f] = node parent.append(node)
'Adds files to the project. Args: files: A list of Filter objects and/or relative paths to files. This makes a copy of the file/filter tree at the time of this call. If you later add files to a Filter object which was passed into a previous call to AddFiles(), it will not be reflected in this project.'
def AddFiles(self, files):
self._AddFilesToNode(self.files_section, files)
'Adds a configuration to a file. Args: path: Relative path to the file. config: Name of configuration to add. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Raises: ValueError: Relative path does not match any file added via AddFiles().'
def AddFileConfig(self, path, config, attrs=None, tools=None):
parent = self.files_dict.get(path) if (not parent): raise ValueError(('AddFileConfig: file "%s" not in project.' % path)) spec = self._GetSpecForConfiguration('FileConfiguration', config, attrs, tools) parent.append(spec)
'Writes the project file.'
def WriteIfChanged(self):
content = ['VisualStudioProject', {'ProjectType': 'Visual C++', 'Version': self.version.ProjectVersion(), 'Name': self.name, 'ProjectGUID': self.guid, 'RootNamespace': self.name, 'Keyword': 'Win32Proj'}, self.platform_section, self.tool_files_section, self.configurations_section, ['References'], self.files_section, ['Globals']] easy_xml.WriteXmlIfChanged(content, self.project_path, encoding='Windows-1252')
'Initialize an ordered dictionary. Signature is the same as for regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary.'
def __init__(self, *args, **kwds):
if (len(args) > 1): raise TypeError(('expected at most 1 arguments, got %d' % len(args))) try: self.__root except AttributeError: self.__root = root = [] root[:] = [root, root, None] self.__map = {} self.__update(*args, **kwds)
'od.__setitem__(i, y) <==> od[i]=y'
def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
if (key not in self): root = self.__root last = root[0] last[1] = root[0] = self.__map[key] = [last, root, key] dict_setitem(self, key, value)
'od.__delitem__(y) <==> del od[y]'
def __delitem__(self, key, dict_delitem=dict.__delitem__):
dict_delitem(self, key) (link_prev, link_next, key) = self.__map.pop(key) link_prev[1] = link_next link_next[0] = link_prev
'od.__iter__() <==> iter(od)'
def __iter__(self):
root = self.__root curr = root[1] while (curr is not root): (yield curr[2]) curr = curr[1]
'od.__reversed__() <==> reversed(od)'
def __reversed__(self):
root = self.__root curr = root[0] while (curr is not root): (yield curr[2]) curr = curr[0]
'od.clear() -> None. Remove all items from od.'
def clear(self):
try: for node in self.__map.itervalues(): del node[:] root = self.__root root[:] = [root, root, None] self.__map.clear() except AttributeError: pass dict.clear(self)
'od.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false.'
def popitem(self, last=True):
if (not self): raise KeyError('dictionary is empty') root = self.__root if last: link = root[0] link_prev = link[0] link_prev[1] = root root[0] = link_prev else: link = root[1] link_next = link[1] root[1] = link_next link_next[0] = root key = link[2] del self.__map[key] value = dict.pop(self, key) return (key, value)
'od.keys() -> list of keys in od'
def keys(self):
return list(self)
'od.values() -> list of values in od'
def values(self):
return [self[key] for key in self]
'od.items() -> list of (key, value) pairs in od'
def items(self):
return [(key, self[key]) for key in self]
'od.iterkeys() -> an iterator over the keys in od'
def iterkeys(self):
return iter(self)
'od.itervalues -> an iterator over the values in od'
def itervalues(self):
for k in self: (yield self[k])
'od.iteritems -> an iterator over the (key, value) items in od'
def iteritems(self):
for k in self: (yield (k, self[k]))
'od.update(E, **F) -> None. Update od from dict/iterable E and F. If E is a dict instance, does: for k in E: od[k] = E[k] If E has a .keys() method, does: for k in E.keys(): od[k] = E[k] Or if E is an iterable of items, does: for k, v in E: od[k] = v In either case, this is followed by: for k, v in F.items(): od[k] = v'
def update(*args, **kwds):
if (len(args) > 2): raise TypeError(('update() takes at most 2 positional arguments (%d given)' % (len(args),))) elif (not args): raise TypeError('update() takes at least 1 argument (0 given)') self = args[0] other = () if (len(args) == 2): other = args[1] if isinstance(other, dict): for key in other: self[key] = other[key] elif hasattr(other, 'keys'): for key in other.keys(): self[key] = other[key] else: for (key, value) in other: self[key] = value for (key, value) in kwds.items(): self[key] = value
'od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.'
def pop(self, key, default=__marker):
if (key in self): result = self[key] del self[key] return result if (default is self.__marker): raise KeyError(key) return default
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
def setdefault(self, key, default=None):
if (key in self): return self[key] self[key] = default return default
'od.__repr__() <==> repr(od)'
def __repr__(self, _repr_running={}):
call_key = (id(self), _get_ident()) if (call_key in _repr_running): return '...' _repr_running[call_key] = 1 try: if (not self): return ('%s()' % (self.__class__.__name__,)) return ('%s(%r)' % (self.__class__.__name__, self.items())) finally: del _repr_running[call_key]
'Return state information for pickling'
def __reduce__(self):
items = [[k, self[k]] for k in self] inst_dict = vars(self).copy() for k in vars(OrderedDict()): inst_dict.pop(k, None) if inst_dict: return (self.__class__, (items,), inst_dict) return (self.__class__, (items,))
'od.copy() -> a shallow copy of od'
def copy(self):
return self.__class__(self)
'OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S and values equal to v (which defaults to None).'
@classmethod def fromkeys(cls, iterable, value=None):
d = cls() for key in iterable: d[key] = value return d
'od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive.'
def __eq__(self, other):
if isinstance(other, OrderedDict): return ((len(self) == len(other)) and (self.items() == other.items())) return dict.__eq__(self, other)
'od.viewkeys() -> a set-like object providing a view on od\'s keys'
def viewkeys(self):
return KeysView(self)
'od.viewvalues() -> an object providing a view on od\'s values'
def viewvalues(self):
return ValuesView(self)
'od.viewitems() -> a set-like object providing a view on od\'s items'
def viewitems(self):
return ItemsView(self)
'Returns the dictionary of variable mapping depending on the SDKROOT.'
def _VariableMapping(self, sdkroot):
sdkroot = sdkroot.lower() if ('iphoneos' in sdkroot): return self._archs['ios'] elif ('iphonesimulator' in sdkroot): return self._archs['iossim'] else: return self._archs['mac']
'Expands variables references in ARCHS, and remove duplicates.'
def _ExpandArchs(self, archs, sdkroot):
variable_mapping = self._VariableMapping(sdkroot) expanded_archs = [] for arch in archs: if self.variable_pattern.match(arch): variable = arch try: variable_expansion = variable_mapping[variable] for arch in variable_expansion: if (arch not in expanded_archs): expanded_archs.append(arch) except KeyError as e: print ('Warning: Ignoring unsupported variable "%s".' % variable) elif (arch not in expanded_archs): expanded_archs.append(arch) return expanded_archs
'Expands variables references in ARCHS, and filter by VALID_ARCHS if it is defined (if not set, Xcode accept any value in ARCHS, otherwise, only values present in VALID_ARCHS are kept).'
def ActiveArchs(self, archs, valid_archs, sdkroot):
expanded_archs = self._ExpandArchs((archs or self._default), (sdkroot or '')) if valid_archs: filtered_archs = [] for arch in expanded_archs: if (arch in valid_archs): filtered_archs.append(arch) expanded_archs = filtered_archs return expanded_archs
'Converts or warns on conditional keys. Xcode supports conditional keys, such as CODE_SIGN_IDENTITY[sdk=iphoneos*]. This is a partial implementation with some keys converted while the rest force a warning.'
def _ConvertConditionalKeys(self, configname):
settings = self.xcode_settings[configname] conditional_keys = [key for key in settings if key.endswith(']')] for key in conditional_keys: if key.endswith('[sdk=iphoneos*]'): if configname.endswith('iphoneos'): new_key = key.split('[')[0] settings[new_key] = settings[key] else: print 'Warning: Conditional keys not implemented, ignoring:', ' '.join(conditional_keys) del settings[key]
'Returns the framework version of the current target. Only valid for bundles.'
def GetFrameworkVersion(self):
assert self._IsBundle() return self.GetPerTargetSetting('FRAMEWORK_VERSION', default='A')
'Returns the bundle extension (.app, .framework, .plugin, etc). Only valid for bundles.'
def GetWrapperExtension(self):
assert self._IsBundle() if (self.spec['type'] in ('loadable_module', 'shared_library')): default_wrapper_extension = {'loadable_module': 'bundle', 'shared_library': 'framework'}[self.spec['type']] wrapper_extension = self.GetPerTargetSetting('WRAPPER_EXTENSION', default=default_wrapper_extension) return ('.' + self.spec.get('product_extension', wrapper_extension)) elif (self.spec['type'] == 'executable'): if (self._IsIosAppExtension() or self._IsIosWatchKitExtension()): return ('.' + self.spec.get('product_extension', 'appex')) else: return ('.' + self.spec.get('product_extension', 'app')) else: assert False, ("Don't know extension for '%s', target '%s'" % (self.spec['type'], self.spec['target_name']))
'Returns PRODUCT_NAME.'
def GetProductName(self):
return self.spec.get('product_name', self.spec['target_name'])
'Returns FULL_PRODUCT_NAME.'
def GetFullProductName(self):
if self._IsBundle(): return self.GetWrapperName() else: return self._GetStandaloneBinaryPath()
'Returns the directory name of the bundle represented by this target. Only valid for bundles.'
def GetWrapperName(self):
assert self._IsBundle() return (self.GetProductName() + self.GetWrapperExtension())
'Returns the qualified path to the bundle\'s contents folder. E.g. Chromium.app/Contents or Foo.bundle/Versions/A. Only valid for bundles.'
def GetBundleContentsFolderPath(self):
if self.isIOS: return self.GetWrapperName() assert self._IsBundle() if (self.spec['type'] == 'shared_library'): return os.path.join(self.GetWrapperName(), 'Versions', self.GetFrameworkVersion()) else: return os.path.join(self.GetWrapperName(), 'Contents')
'Returns the qualified path to the bundle\'s resource folder. E.g. Chromium.app/Contents/Resources. Only valid for bundles.'
def GetBundleResourceFolder(self):
assert self._IsBundle() if self.isIOS: return self.GetBundleContentsFolderPath() return os.path.join(self.GetBundleContentsFolderPath(), 'Resources')
'Returns the qualified path to the bundle\'s plist file. E.g. Chromium.app/Contents/Info.plist. Only valid for bundles.'
def GetBundlePlistPath(self):
assert self._IsBundle() if (self.spec['type'] in ('executable', 'loadable_module')): return os.path.join(self.GetBundleContentsFolderPath(), 'Info.plist') else: return os.path.join(self.GetBundleContentsFolderPath(), 'Resources', 'Info.plist')
'Returns the PRODUCT_TYPE of this target.'
def GetProductType(self):
if self._IsIosAppExtension(): assert self._IsBundle(), ('ios_app_extension flag requires mac_bundle (target %s)' % self.spec['target_name']) return 'com.apple.product-type.app-extension' if self._IsIosWatchKitExtension(): assert self._IsBundle(), ('ios_watchkit_extension flag requires mac_bundle (target %s)' % self.spec['target_name']) return 'com.apple.product-type.watchkit-extension' if self._IsIosWatchApp(): assert self._IsBundle(), ('ios_watch_app flag requires mac_bundle (target %s)' % self.spec['target_name']) return 'com.apple.product-type.application.watchapp' if self._IsBundle(): return {'executable': 'com.apple.product-type.application', 'loadable_module': 'com.apple.product-type.bundle', 'shared_library': 'com.apple.product-type.framework'}[self.spec['type']] else: return {'executable': 'com.apple.product-type.tool', 'loadable_module': 'com.apple.product-type.library.dynamic', 'shared_library': 'com.apple.product-type.library.dynamic', 'static_library': 'com.apple.product-type.library.static'}[self.spec['type']]
'Returns the MACH_O_TYPE of this target.'
def GetMachOType(self):
if ((not self._IsBundle()) and (self.spec['type'] == 'executable')): return '' return {'executable': 'mh_execute', 'static_library': 'staticlib', 'shared_library': 'mh_dylib', 'loadable_module': 'mh_bundle'}[self.spec['type']]
'Returns the name of the bundle binary of by this target. E.g. Chromium.app/Contents/MacOS/Chromium. Only valid for bundles.'
def _GetBundleBinaryPath(self):
assert self._IsBundle() if ((self.spec['type'] in 'shared_library') or self.isIOS): path = self.GetBundleContentsFolderPath() elif (self.spec['type'] in ('executable', 'loadable_module')): path = os.path.join(self.GetBundleContentsFolderPath(), 'MacOS') return os.path.join(path, self.GetExecutableName())
'Returns the name of the non-bundle binary represented by this target. E.g. hello_world. Only valid for non-bundles.'
def _GetStandaloneBinaryPath(self):
assert (not self._IsBundle()) assert (self.spec['type'] in ('executable', 'shared_library', 'static_library', 'loadable_module')), ('Unexpected type %s' % self.spec['type']) target = self.spec['target_name'] if (self.spec['type'] == 'static_library'): if (target[:3] == 'lib'): target = target[3:] elif (self.spec['type'] in ('loadable_module', 'shared_library')): if (target[:3] == 'lib'): target = target[3:] target_prefix = self._GetStandaloneExecutablePrefix() target = self.spec.get('product_name', target) target_ext = self._GetStandaloneExecutableSuffix() return ((target_prefix + target) + target_ext)
'Returns the executable name of the bundle represented by this target. E.g. Chromium.'
def GetExecutableName(self):
if self._IsBundle(): return self.spec.get('product_name', self.spec['target_name']) else: return self._GetStandaloneBinaryPath()
'Returns the directory name of the bundle represented by this target. E.g. Chromium.app/Contents/MacOS/Chromium.'
def GetExecutablePath(self):
if self._IsBundle(): return self._GetBundleBinaryPath() else: return self._GetStandaloneBinaryPath()
'Returns the architectures this target should be built for.'
def GetActiveArchs(self, configname):
config_settings = self.xcode_settings[configname] xcode_archs_default = GetXcodeArchsDefault() return xcode_archs_default.ActiveArchs(config_settings.get('ARCHS'), config_settings.get('VALID_ARCHS'), config_settings.get('SDKROOT'))
'Returns flags that need to be added to .c, .cc, .m, and .mm compilations.'
def GetCflags(self, configname, arch=None):
self.configname = configname cflags = [] sdk_root = self._SdkPath() if (('SDKROOT' in self._Settings()) and sdk_root): cflags.append(('-isysroot %s' % sdk_root)) if self._Test('CLANG_WARN_CONSTANT_CONVERSION', 'YES', default='NO'): cflags.append('-Wconstant-conversion') if self._Test('GCC_CHAR_IS_UNSIGNED_CHAR', 'YES', default='NO'): cflags.append('-funsigned-char') if self._Test('GCC_CW_ASM_SYNTAX', 'YES', default='YES'): cflags.append('-fasm-blocks') if ('GCC_DYNAMIC_NO_PIC' in self._Settings()): if (self._Settings()['GCC_DYNAMIC_NO_PIC'] == 'YES'): cflags.append('-mdynamic-no-pic') else: pass if self._Test('GCC_ENABLE_PASCAL_STRINGS', 'YES', default='YES'): cflags.append('-mpascal-strings') self._Appendf(cflags, 'GCC_OPTIMIZATION_LEVEL', '-O%s', default='s') if self._Test('GCC_GENERATE_DEBUGGING_SYMBOLS', 'YES', default='YES'): dbg_format = self._Settings().get('DEBUG_INFORMATION_FORMAT', 'dwarf') if (dbg_format == 'dwarf'): cflags.append('-gdwarf-2') elif (dbg_format == 'stabs'): raise NotImplementedError('stabs debug format is not supported yet.') elif (dbg_format == 'dwarf-with-dsym'): cflags.append('-gdwarf-2') else: raise NotImplementedError(('Unknown debug format %s' % dbg_format)) if (self._Settings().get('GCC_STRICT_ALIASING') == 'YES'): cflags.append('-fstrict-aliasing') elif (self._Settings().get('GCC_STRICT_ALIASING') == 'NO'): cflags.append('-fno-strict-aliasing') if self._Test('GCC_SYMBOLS_PRIVATE_EXTERN', 'YES', default='NO'): cflags.append('-fvisibility=hidden') if self._Test('GCC_TREAT_WARNINGS_AS_ERRORS', 'YES', default='NO'): cflags.append('-Werror') if self._Test('GCC_WARN_ABOUT_MISSING_NEWLINE', 'YES', default='NO'): cflags.append('-Wnewline-eof') if self._Test('LLVM_LTO', 'YES', default='NO'): cflags.append('-flto') self._AppendPlatformVersionMinFlags(cflags) if self._Test('COPY_PHASE_STRIP', 'YES', default='NO'): self._WarnUnimplemented('COPY_PHASE_STRIP') self._WarnUnimplemented('GCC_DEBUGGING_SYMBOLS') self._WarnUnimplemented('GCC_ENABLE_OBJC_EXCEPTIONS') self._WarnUnimplemented('MACH_O_TYPE') self._WarnUnimplemented('PRODUCT_TYPE') if (arch is not None): archs = [arch] else: assert self.configname archs = self.GetActiveArchs(self.configname) if (len(archs) != 1): self._WarnUnimplemented('ARCHS') archs = ['i386'] cflags.append(('-arch ' + archs[0])) if (archs[0] in ('i386', 'x86_64')): if self._Test('GCC_ENABLE_SSE3_EXTENSIONS', 'YES', default='NO'): cflags.append('-msse3') if self._Test('GCC_ENABLE_SUPPLEMENTAL_SSE3_INSTRUCTIONS', 'YES', default='NO'): cflags.append('-mssse3') if self._Test('GCC_ENABLE_SSE41_EXTENSIONS', 'YES', default='NO'): cflags.append('-msse4.1') if self._Test('GCC_ENABLE_SSE42_EXTENSIONS', 'YES', default='NO'): cflags.append('-msse4.2') cflags += self._Settings().get('WARNING_CFLAGS', []) if sdk_root: framework_root = sdk_root else: framework_root = '' config = self.spec['configurations'][self.configname] framework_dirs = config.get('mac_framework_dirs', []) for directory in framework_dirs: cflags.append(('-F' + directory.replace('$(SDKROOT)', framework_root))) self.configname = None return cflags
'Returns flags that need to be added to .c, and .m compilations.'
def GetCflagsC(self, configname):
self.configname = configname cflags_c = [] if (self._Settings().get('GCC_C_LANGUAGE_STANDARD', '') == 'ansi'): cflags_c.append('-ansi') else: self._Appendf(cflags_c, 'GCC_C_LANGUAGE_STANDARD', '-std=%s') cflags_c += self._Settings().get('OTHER_CFLAGS', []) self.configname = None return cflags_c
'Returns flags that need to be added to .cc, and .mm compilations.'
def GetCflagsCC(self, configname):
self.configname = configname cflags_cc = [] clang_cxx_language_standard = self._Settings().get('CLANG_CXX_LANGUAGE_STANDARD') if clang_cxx_language_standard: cflags_cc.append(('-std=%s' % clang_cxx_language_standard)) self._Appendf(cflags_cc, 'CLANG_CXX_LIBRARY', '-stdlib=%s') if self._Test('GCC_ENABLE_CPP_RTTI', 'NO', default='YES'): cflags_cc.append('-fno-rtti') if self._Test('GCC_ENABLE_CPP_EXCEPTIONS', 'NO', default='YES'): cflags_cc.append('-fno-exceptions') if self._Test('GCC_INLINES_ARE_PRIVATE_EXTERN', 'YES', default='NO'): cflags_cc.append('-fvisibility-inlines-hidden') if self._Test('GCC_THREADSAFE_STATICS', 'NO', default='YES'): cflags_cc.append('-fno-threadsafe-statics') if self._Test('GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO', 'NO', default='YES'): cflags_cc.append('-Wno-invalid-offsetof') other_ccflags = [] for flag in self._Settings().get('OTHER_CPLUSPLUSFLAGS', ['$(inherited)']): if (flag in ('$inherited', '$(inherited)', '${inherited}')): flag = '$OTHER_CFLAGS' if (flag in ('$OTHER_CFLAGS', '$(OTHER_CFLAGS)', '${OTHER_CFLAGS}')): other_ccflags += self._Settings().get('OTHER_CFLAGS', []) else: other_ccflags.append(flag) cflags_cc += other_ccflags self.configname = None return cflags_cc
'Returns flags that need to be added to .m compilations.'
def GetCflagsObjC(self, configname):
self.configname = configname cflags_objc = [] self._AddObjectiveCGarbageCollectionFlags(cflags_objc) self._AddObjectiveCARCFlags(cflags_objc) self._AddObjectiveCMissingPropertySynthesisFlags(cflags_objc) self.configname = None return cflags_objc
'Returns flags that need to be added to .mm compilations.'
def GetCflagsObjCC(self, configname):
self.configname = configname cflags_objcc = [] self._AddObjectiveCGarbageCollectionFlags(cflags_objcc) self._AddObjectiveCARCFlags(cflags_objcc) self._AddObjectiveCMissingPropertySynthesisFlags(cflags_objcc) if self._Test('GCC_OBJC_CALL_CXX_CDTORS', 'YES', default='NO'): cflags_objcc.append('-fobjc-call-cxx-cdtors') self.configname = None return cflags_objcc
'Return DYLIB_INSTALL_NAME_BASE for this target.'
def GetInstallNameBase(self):
if ((self.spec['type'] != 'shared_library') and ((self.spec['type'] != 'loadable_module') or self._IsBundle())): return None install_base = self.GetPerTargetSetting('DYLIB_INSTALL_NAME_BASE', default=('/Library/Frameworks' if self._IsBundle() else '/usr/local/lib')) return install_base
'Do :standardizepath processing for path.'
def _StandardizePath(self, path):
if ('/' in path): (prefix, rest) = ('', path) if path.startswith('@'): (prefix, rest) = path.split('/', 1) rest = os.path.normpath(rest) path = os.path.join(prefix, rest) return path
'Return LD_DYLIB_INSTALL_NAME for this target.'
def GetInstallName(self):
if ((self.spec['type'] != 'shared_library') and ((self.spec['type'] != 'loadable_module') or self._IsBundle())): return None default_install_name = '$(DYLIB_INSTALL_NAME_BASE:standardizepath)/$(EXECUTABLE_PATH)' install_name = self.GetPerTargetSetting('LD_DYLIB_INSTALL_NAME', default=default_install_name) if ('$' in install_name): assert (install_name in ('$(DYLIB_INSTALL_NAME_BASE:standardizepath)/$(WRAPPER_NAME)/$(PRODUCT_NAME)', default_install_name)), ("Variables in LD_DYLIB_INSTALL_NAME are not generally supported yet in target '%s' (got '%s')" % (self.spec['target_name'], install_name)) install_name = install_name.replace('$(DYLIB_INSTALL_NAME_BASE:standardizepath)', self._StandardizePath(self.GetInstallNameBase())) if self._IsBundle(): install_name = install_name.replace('$(WRAPPER_NAME)', self.GetWrapperName()) install_name = install_name.replace('$(PRODUCT_NAME)', self.GetProductName()) else: assert ('$(WRAPPER_NAME)' not in install_name) assert ('$(PRODUCT_NAME)' not in install_name) install_name = install_name.replace('$(EXECUTABLE_PATH)', self.GetExecutablePath()) return install_name
'Checks if ldflag contains a filename and if so remaps it from gyp-directory-relative to build-directory-relative.'
def _MapLinkerFlagFilename(self, ldflag, gyp_to_build_path):
LINKER_FILE = '(\\S+)' WORD = '\\S+' linker_flags = [['-exported_symbols_list', LINKER_FILE], ['-unexported_symbols_list', LINKER_FILE], ['-reexported_symbols_list', LINKER_FILE], ['-sectcreate', WORD, WORD, LINKER_FILE]] for flag_pattern in linker_flags: regex = re.compile(('(?:-Wl,)?' + '[ ,]'.join(flag_pattern))) m = regex.match(ldflag) if m: ldflag = ((ldflag[:m.start(1)] + gyp_to_build_path(m.group(1))) + ldflag[m.end(1):]) if ldflag.startswith('-L'): ldflag = ('-L' + gyp_to_build_path(ldflag[len('-L'):])) return ldflag
'Returns flags that need to be passed to the linker. Args: configname: The name of the configuration to get ld flags for. product_dir: The directory where products such static and dynamic libraries are placed. This is added to the library search path. gyp_to_build_path: A function that converts paths relative to the current gyp file to paths relative to the build direcotry.'
def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None):
self.configname = configname ldflags = [] for ldflag in self._Settings().get('OTHER_LDFLAGS', []): ldflags.append(self._MapLinkerFlagFilename(ldflag, gyp_to_build_path)) if self._Test('DEAD_CODE_STRIPPING', 'YES', default='NO'): ldflags.append('-Wl,-dead_strip') if self._Test('PREBINDING', 'YES', default='NO'): ldflags.append('-Wl,-prebind') self._Appendf(ldflags, 'DYLIB_COMPATIBILITY_VERSION', '-compatibility_version %s') self._Appendf(ldflags, 'DYLIB_CURRENT_VERSION', '-current_version %s') self._AppendPlatformVersionMinFlags(ldflags) if (('SDKROOT' in self._Settings()) and self._SdkPath()): ldflags.append(('-isysroot ' + self._SdkPath())) for library_path in self._Settings().get('LIBRARY_SEARCH_PATHS', []): ldflags.append(('-L' + gyp_to_build_path(library_path))) if ('ORDER_FILE' in self._Settings()): ldflags.append((('-Wl,-order_file ' + '-Wl,') + gyp_to_build_path(self._Settings()['ORDER_FILE']))) if (arch is not None): archs = [arch] else: assert self.configname archs = self.GetActiveArchs(self.configname) if (len(archs) != 1): self._WarnUnimplemented('ARCHS') archs = ['i386'] ldflags.append(('-arch ' + archs[0])) ldflags.append(('-L' + product_dir)) install_name = self.GetInstallName() if (install_name and (self.spec['type'] != 'loadable_module')): ldflags.append(('-install_name ' + install_name.replace(' ', '\\ '))) for rpath in self._Settings().get('LD_RUNPATH_SEARCH_PATHS', []): ldflags.append(('-Wl,-rpath,' + rpath)) sdk_root = self._SdkPath() if (not sdk_root): sdk_root = '' config = self.spec['configurations'][self.configname] framework_dirs = config.get('mac_framework_dirs', []) for directory in framework_dirs: ldflags.append(('-F' + directory.replace('$(SDKROOT)', sdk_root))) is_extension = (self._IsIosAppExtension() or self._IsIosWatchKitExtension()) if (sdk_root and is_extension): ldflags.append('-lpkstart') if (XcodeVersion() < '0900'): ldflags.append((sdk_root + '/System/Library/PrivateFrameworks/PlugInKit.framework/PlugInKit')) ldflags.append('-fapplication-extension') ldflags.append('-Xlinker -rpath -Xlinker @executable_path/../../Frameworks') self._Appendf(ldflags, 'CLANG_CXX_LIBRARY', '-stdlib=%s') self.configname = None return ldflags
'Returns flags that need to be passed to the static linker. Args: configname: The name of the configuration to get ld flags for.'
def GetLibtoolflags(self, configname):
self.configname = configname libtoolflags = [] for libtoolflag in self._Settings().get('OTHER_LDFLAGS', []): libtoolflags.append(libtoolflag) self.configname = None return libtoolflags
'Gets a list of all the per-target settings. This will only fetch keys whose values are the same across all configurations.'
def GetPerTargetSettings(self):
first_pass = True result = {} for configname in sorted(self.xcode_settings.keys()): if first_pass: result = dict(self.xcode_settings[configname]) first_pass = False else: for (key, value) in self.xcode_settings[configname].iteritems(): if (key not in result): continue elif (result[key] != value): del result[key] return result
'Tries to get xcode_settings.setting from spec. Assumes that the setting has the same value in all configurations and throws otherwise.'
def GetPerTargetSetting(self, setting, default=None):
is_first_pass = True result = None for configname in sorted(self.xcode_settings.keys()): if is_first_pass: result = self.xcode_settings[configname].get(setting, None) is_first_pass = False else: assert (result == self.xcode_settings[configname].get(setting, None)), ("Expected per-target setting for '%s', got per-config setting (target %s)" % (setting, self.spec['target_name'])) if (result is None): return default return result
'Returns a list of shell commands that contain the shell commands neccessary to strip this target\'s binary. These should be run as postbuilds before the actual postbuilds run.'
def _GetStripPostbuilds(self, configname, output_binary, quiet):
self.configname = configname result = [] if (self._Test('DEPLOYMENT_POSTPROCESSING', 'YES', default='NO') and self._Test('STRIP_INSTALLED_PRODUCT', 'YES', default='NO')): default_strip_style = 'debugging' if ((self.spec['type'] == 'loadable_module') and self._IsBundle()): default_strip_style = 'non-global' elif (self.spec['type'] == 'executable'): default_strip_style = 'all' strip_style = self._Settings().get('STRIP_STYLE', default_strip_style) strip_flags = {'all': '', 'non-global': '-x', 'debugging': '-S'}[strip_style] explicit_strip_flags = self._Settings().get('STRIPFLAGS', '') if explicit_strip_flags: strip_flags += (' ' + _NormalizeEnvVarReferences(explicit_strip_flags)) if (not quiet): result.append(('echo STRIP\\(%s\\)' % self.spec['target_name'])) result.append(('strip %s %s' % (strip_flags, output_binary))) self.configname = None return result
'Returns a list of shell commands that contain the shell commands neccessary to massage this target\'s debug information. These should be run as postbuilds before the actual postbuilds run.'
def _GetDebugInfoPostbuilds(self, configname, output, output_binary, quiet):
self.configname = configname result = [] if (self._Test('GCC_GENERATE_DEBUGGING_SYMBOLS', 'YES', default='YES') and self._Test('DEBUG_INFORMATION_FORMAT', 'dwarf-with-dsym', default='dwarf') and (self.spec['type'] != 'static_library')): if (not quiet): result.append(('echo DSYMUTIL\\(%s\\)' % self.spec['target_name'])) result.append(('dsymutil %s -o %s' % (output_binary, (output + '.dSYM')))) self.configname = None return result
'Returns a list of shell commands that contain the shell commands to run as postbuilds for this target, before the actual postbuilds.'
def _GetTargetPostbuilds(self, configname, output, output_binary, quiet=False):
return (self._GetDebugInfoPostbuilds(configname, output, output_binary, quiet) + self._GetStripPostbuilds(configname, output_binary, quiet))
'Return a shell command to codesign the iOS output binary so it can be deployed to a device. This should be run as the very last step of the build.'
def _GetIOSPostbuilds(self, configname, output_binary):
if (not (self.isIOS and (self.spec['type'] == 'executable'))): return [] settings = self.xcode_settings[configname] key = self._GetIOSCodeSignIdentityKey(settings) if (not key): return [] unimpl = ['OTHER_CODE_SIGN_FLAGS'] unimpl = (set(unimpl) & set(self.xcode_settings[configname].keys())) if unimpl: print ('Warning: Some codesign keys not implemented, ignoring: %s' % ', '.join(sorted(unimpl))) return [('%s code-sign-bundle "%s" "%s" "%s" "%s"' % (os.path.join('${TARGET_BUILD_DIR}', 'gyp-mac-tool'), key, settings.get('CODE_SIGN_RESOURCE_RULES_PATH', ''), settings.get('CODE_SIGN_ENTITLEMENTS', ''), settings.get('PROVISIONING_PROFILE', '')))]
'Returns a list of shell commands that should run before and after |postbuilds|.'
def AddImplicitPostbuilds(self, configname, output, output_binary, postbuilds=[], quiet=False):
assert (output_binary is not None) pre = self._GetTargetPostbuilds(configname, output, output_binary, quiet) post = self._GetIOSPostbuilds(configname, output_binary) return ((pre + postbuilds) + post)
'Transforms entries like \'Cocoa.framework\' in libraries into entries like \'-framework Cocoa\', \'libcrypto.dylib\' into \'-lcrypto\', etc.'
def AdjustLibraries(self, libraries, config_name=None):
libraries = [self._AdjustLibrary(library, config_name) for library in libraries] return libraries
'Returns a dictionary with extra items to insert into Info.plist.'
def GetExtraPlistItems(self, configname=None):
if (configname not in XcodeSettings._plist_cache): cache = {} cache['BuildMachineOSBuild'] = self._BuildMachineOSBuild() (xcode, xcode_build) = XcodeVersion() cache['DTXcode'] = xcode cache['DTXcodeBuild'] = xcode_build sdk_root = self._SdkRoot(configname) if (not sdk_root): sdk_root = self._DefaultSdkRoot() cache['DTSDKName'] = sdk_root if (xcode >= '0430'): cache['DTSDKBuild'] = self._GetSdkVersionInfoItem(sdk_root, 'ProductBuildVersion') else: cache['DTSDKBuild'] = cache['BuildMachineOSBuild'] if self.isIOS: cache['DTPlatformName'] = cache['DTSDKName'] if configname.endswith('iphoneos'): cache['DTPlatformVersion'] = self._GetSdkVersionInfoItem(sdk_root, 'ProductVersion') cache['CFBundleSupportedPlatforms'] = ['iPhoneOS'] else: cache['CFBundleSupportedPlatforms'] = ['iPhoneSimulator'] XcodeSettings._plist_cache[configname] = cache items = dict(XcodeSettings._plist_cache[configname]) if self.isIOS: items['UIDeviceFamily'] = self._XcodeIOSDeviceFamily(configname) return items
'Returns the default SDKROOT to use. Prior to version 5.0.0, if SDKROOT was not explicitly set in the Xcode project, then the environment variable was empty. Starting with this version, Xcode uses the name of the newest SDK installed.'
def _DefaultSdkRoot(self):
(xcode_version, xcode_build) = XcodeVersion() if (xcode_version < '0500'): return '' default_sdk_path = self._XcodeSdkPath('') default_sdk_root = XcodeSettings._sdk_root_cache.get(default_sdk_path) if default_sdk_root: return default_sdk_root try: all_sdks = GetStdout(['xcodebuild', '-showsdks']) except: return '' for line in all_sdks.splitlines(): items = line.split() if ((len(items) >= 3) and (items[(-2)] == '-sdk')): sdk_root = items[(-1)] sdk_path = self._XcodeSdkPath(sdk_root) if (sdk_path == default_sdk_path): return sdk_root return ''
'If xcode_settings is None, all methods on this class are no-ops. Args: gyp_path_to_build_path: A function that takes a gyp-relative path, and returns a path relative to the build directory. gyp_path_to_build_output: A function that takes a gyp-relative path and a language code (\'c\', \'cc\', \'m\', or \'mm\'), and that returns a path to where the output of precompiling that path for that language should be placed (without the trailing \'.gch\').'
def __init__(self, xcode_settings, gyp_path_to_build_path, gyp_path_to_build_output):
self.header = None self.compile_headers = False if xcode_settings: self.header = xcode_settings.GetPerTargetSetting('GCC_PREFIX_HEADER') self.compile_headers = (xcode_settings.GetPerTargetSetting('GCC_PRECOMPILE_PREFIX_HEADER', default='NO') != 'NO') self.compiled_headers = {} if self.header: if self.compile_headers: for lang in ['c', 'cc', 'm', 'mm']: self.compiled_headers[lang] = gyp_path_to_build_output(self.header, lang) self.header = gyp_path_to_build_path(self.header)
'Gets the cflags to include the prefix header for language |lang|.'
def GetInclude(self, lang, arch=None):
if (self.compile_headers and (lang in self.compiled_headers)): return ('-include %s' % self._CompiledHeader(lang, arch)) elif self.header: return ('-include %s' % self.header) else: return ''
'Returns the actual file name of the prefix header for language |lang|.'
def _Gch(self, lang, arch):
assert self.compile_headers return (self._CompiledHeader(lang, arch) + '.gch')
'Given a list of source files and the corresponding object files, returns a list of (source, object, gch) tuples, where |gch| is the build-directory relative path to the gch file each object file depends on. |compilable[i]| has to be the source file belonging to |objs[i]|.'
def GetObjDependencies(self, sources, objs, arch=None):
if ((not self.header) or (not self.compile_headers)): return [] result = [] for (source, obj) in zip(sources, objs): ext = os.path.splitext(source)[1] lang = {'.c': 'c', '.cpp': 'cc', '.cc': 'cc', '.cxx': 'cc', '.m': 'm', '.mm': 'mm'}.get(ext, None) if lang: result.append((source, obj, self._Gch(lang, arch))) return result
'Returns [(path_to_gch, language_flag, language, header)]. |path_to_gch| and |header| are relative to the build directory.'
def GetPchBuildCommands(self, arch=None):
if ((not self.header) or (not self.compile_headers)): return [] return [(self._Gch('c', arch), '-x c-header', 'c', self.header), (self._Gch('cc', arch), '-x c++-header', 'cc', self.header), (self._Gch('m', arch), '-x objective-c-header', 'm', self.header), (self._Gch('mm', arch), '-x objective-c++-header', 'mm', self.header)]
'Add an option to the parser. This accepts the same arguments as OptionParser.add_option, plus the following: regenerate: can be set to False to prevent this option from being included in regeneration. env_name: name of environment variable that additional values for this option come from. type: adds type=\'path\', to tell the regenerator that the values of this option need to be made relative to options.depth'
def add_option(self, *args, **kw):
env_name = kw.pop('env_name', None) if (('dest' in kw) and kw.pop('regenerate', True)): dest = kw['dest'] type = kw.get('type') if (type == 'path'): kw['type'] = 'string' self.__regeneratable_options[dest] = {'action': kw.get('action'), 'type': type, 'env_name': env_name, 'opt': args[0]} optparse.OptionParser.add_option(self, *args, **kw)