desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Merge multiple .plist files into a single .plist file.'
| def ExecMergeInfoPlist(self, output, *inputs):
| merged_plist = {}
for path in inputs:
plist = self._LoadPlistMaybeBinary(path)
self._MergePlist(merged_plist, plist)
plistlib.writePlist(merged_plist, output)
|
'Code sign a bundle.
This function tries to code sign an iOS bundle, following the same
algorithm as Xcode:
1. copy ResourceRules.plist from the user or the SDK into the bundle,
2. pick the provisioning profile that best match the bundle identifier,
and copy it into the bundle as embedded.mobileprovision,
3. copy Entit... | def ExecCodeSignBundle(self, key, resource_rules, entitlements, provisioning):
| resource_rules_path = self._InstallResourceRules(resource_rules)
(substitutions, overrides) = self._InstallProvisioningProfile(provisioning, self._GetCFBundleIdentifier())
entitlements_path = self._InstallEntitlements(entitlements, substitutions, overrides)
subprocess.check_call(['codesign', '--force', ... |
'Installs ResourceRules.plist from user or SDK into the bundle.
Args:
resource_rules: string, optional, path to the ResourceRules.plist file
to use, default to "${SDKROOT}/ResourceRules.plist"
Returns:
Path to the copy of ResourceRules.plist into the bundle.'
| def _InstallResourceRules(self, resource_rules):
| source_path = resource_rules
target_path = os.path.join(os.environ['BUILT_PRODUCTS_DIR'], os.environ['CONTENTS_FOLDER_PATH'], 'ResourceRules.plist')
if (not source_path):
source_path = os.path.join(os.environ['SDKROOT'], 'ResourceRules.plist')
shutil.copy2(source_path, target_path)
return ta... |
'Installs embedded.mobileprovision into the bundle.
Args:
profile: string, optional, short name of the .mobileprovision file
to use, if empty or the file is missing, the best file installed
will be used
bundle_identifier: string, value of CFBundleIdentifier from Info.plist
Returns:
A tuple containing two dictionary: va... | def _InstallProvisioningProfile(self, profile, bundle_identifier):
| (source_path, provisioning_data, team_id) = self._FindProvisioningProfile(profile, bundle_identifier)
target_path = os.path.join(os.environ['BUILT_PRODUCTS_DIR'], os.environ['CONTENTS_FOLDER_PATH'], 'embedded.mobileprovision')
shutil.copy2(source_path, target_path)
substitutions = self._GetSubstitutions... |
'Finds the .mobileprovision file to use for signing the bundle.
Checks all the installed provisioning profiles (or if the user specified
the PROVISIONING_PROFILE variable, only consult it) and select the most
specific that correspond to the bundle identifier.
Args:
profile: string, optional, short name of the .mobilepr... | def _FindProvisioningProfile(self, profile, bundle_identifier):
| profiles_dir = os.path.join(os.environ['HOME'], 'Library', 'MobileDevice', 'Provisioning Profiles')
if (not os.path.isdir(profiles_dir)):
print >>sys.stderr, ('cannot find mobile provisioning for %s' % bundle_identifier)
sys.exit(1)
provisioning_profiles = None
if profi... |
'Extracts the plist embedded in a provisioning profile.
Args:
profile_path: string, path to the .mobileprovision file
Returns:
Content of the plist embedded in the provisioning profile as a dictionary.'
| def _LoadProvisioningProfile(self, profile_path):
| with tempfile.NamedTemporaryFile() as temp:
subprocess.check_call(['security', 'cms', '-D', '-i', profile_path, '-o', temp.name])
return self._LoadPlistMaybeBinary(temp.name)
|
'Merge |plist| into |merged_plist|.'
| def _MergePlist(self, merged_plist, plist):
| for (key, value) in plist.iteritems():
if isinstance(value, dict):
merged_value = merged_plist.get(key, {})
if isinstance(merged_value, dict):
self._MergePlist(merged_value, value)
merged_plist[key] = merged_value
else:
merg... |
'Loads into a memory a plist possibly encoded in binary format.
This is a wrapper around plistlib.readPlist that tries to convert the
plist to the XML format if it can\'t be parsed (assuming that it is in
the binary format).
Args:
plist_path: string, path to a plist file, in XML or binary format
Returns:
Content of the... | def _LoadPlistMaybeBinary(self, plist_path):
| try:
return plistlib.readPlist(plist_path)
except:
pass
with tempfile.NamedTemporaryFile() as temp:
shutil.copy2(plist_path, temp.name)
subprocess.check_call(['plutil', '-convert', 'xml1', temp.name])
return plistlib.readPlist(temp.name)
|
'Constructs a dictionary of variable substitutions for Entitlements.plist.
Args:
bundle_identifier: string, value of CFBundleIdentifier from Info.plist
app_identifier_prefix: string, value for AppIdentifierPrefix
Returns:
Dictionary of substitutions to apply when generating Entitlements.plist.'
| def _GetSubstitutions(self, bundle_identifier, app_identifier_prefix):
| return {'CFBundleIdentifier': bundle_identifier, 'AppIdentifierPrefix': app_identifier_prefix}
|
'Extracts CFBundleIdentifier value from Info.plist in the bundle.
Returns:
Value of CFBundleIdentifier in the Info.plist located in the bundle.'
| def _GetCFBundleIdentifier(self):
| info_plist_path = os.path.join(os.environ['TARGET_BUILD_DIR'], os.environ['INFOPLIST_PATH'])
info_plist_data = self._LoadPlistMaybeBinary(info_plist_path)
return info_plist_data['CFBundleIdentifier']
|
'Generates and install the ${BundleName}.xcent entitlements file.
Expands variables "$(variable)" pattern in the source entitlements file,
add extra entitlements defined in the .mobileprovision file and the copy
the generated plist to "${BundlePath}.xcent".
Args:
entitlements: string, optional, path to the Entitlements... | def _InstallEntitlements(self, entitlements, substitutions, overrides):
| source_path = entitlements
target_path = os.path.join(os.environ['BUILT_PRODUCTS_DIR'], (os.environ['PRODUCT_NAME'] + '.xcent'))
if (not source_path):
source_path = os.path.join(os.environ['SDKROOT'], 'Entitlements.plist')
shutil.copy2(source_path, target_path)
data = self._LoadPlistMaybeBin... |
'Expands variables "$(variable)" in data.
Args:
data: object, can be either string, list or dictionary
substitutions: dictionary, variable substitutions to perform
Returns:
Copy of data where each references to "$(variable)" has been replaced
by the corresponding value found in substitutions, or left intact if
the key ... | def _ExpandVariables(self, data, substitutions):
| if isinstance(data, str):
for (key, value) in substitutions.iteritems():
data = data.replace(('$(%s)' % key), value)
return data
if isinstance(data, list):
return [self._ExpandVariables(v, substitutions) for v in data]
if isinstance(data, dict):
return {k: self._E... |
'Make a copy of this object.
The new object will have its own copy of lists and dicts. Any XCObject
objects owned by this object (marked "strong") will be copied in the
new object, even those found in lists. If this object has any weak
references to other XCObjects, the same references are added to the new
object wit... | def Copy(self):
| that = self.__class__(id=self.id, parent=self.parent)
for (key, value) in self._properties.iteritems():
is_strong = self._schema[key][2]
if isinstance(value, XCObject):
if is_strong:
new_value = value.Copy()
new_value.parent = that
that... |
'Return the name corresponding to an object.
Not all objects necessarily need to be nameable, and not all that do have
a "name" property. Override as needed.'
| def Name(self):
| if (('name' in self._properties) or (('name' in self._schema) and self._schema['name'][3])):
return self._properties['name']
raise NotImplementedError((self.__class__.__name__ + ' must implement Name'))
|
'Return a comment string for the object.
Most objects just use their name as the comment, but PBXProject uses
different values.
The returned comment is not escaped and does not have any comment marker
strings applied to it.'
| def Comment(self):
| return self.Name()
|
'Set "id" properties deterministically.
An object\'s "id" property is set based on a hash of its class type and
name, as well as the class type and name of all ancestor objects. As
such, it is only advisable to call ComputeIDs once an entire project file
tree is built.
If recursive is True, recurse into all descendant... | def ComputeIDs(self, recursive=True, overwrite=True, seed_hash=None):
| def _HashUpdate(hash, data):
"Update hash with data's length and contents.\n\n If the hash were updated only with the value of data, it would be\n possible for clowns to induce collisions ... |
'Verifies that no two objects have the same ID. Checks all descendants.'
| def EnsureNoIDCollisions(self):
| ids = {}
descendants = self.Descendants()
for descendant in descendants:
if (descendant.id in ids):
other = ids[descendant.id]
raise KeyError(('Duplicate ID %s, objects "%s" and "%s" in "%s"' % (descendant.id, str(descendant._properties), str(other._pr... |
'Returns a list of all of this object\'s owned (strong) children.'
| def Children(self):
| children = []
for (property, attributes) in self._schema.iteritems():
(is_list, property_type, is_strong) = attributes[0:3]
if (is_strong and (property in self._properties)):
if (not is_list):
children.append(self._properties[property])
else:
... |
'Returns a list of all of this object\'s descendants, including this
object.'
| def Descendants(self):
| children = self.Children()
descendants = [self]
for child in children:
descendants.extend(child.Descendants())
return descendants
|
'Encodes a comment to be placed in the project file output, mimicing
Xcode behavior.'
| def _EncodeComment(self, comment):
| return (('/* ' + comment.replace('*/', '(*)/')) + ' */')
|
'Encodes a string to be placed in the project file output, mimicing
Xcode behavior.'
| def _EncodeString(self, value):
| if (_unquoted.search(value) and (not _quoted.search(value))):
return value
return (('"' + _escaped.sub(self._EncodeTransform, value)) + '"')
|
'Returns a representation of value that may be printed in a project file,
mimicing Xcode\'s behavior.
_XCPrintableValue can handle str and int values, XCObjects (which are
made printable by returning their id property), and list and dict objects
composed of any of the above types. When printing a list or dict, and
_sh... | def _XCPrintableValue(self, tabs, value, flatten_list=False):
| printable = ''
comment = None
if self._should_print_single_line:
sep = ' '
element_tabs = ''
end_tabs = ''
else:
sep = '\n'
element_tabs = (' DCTB ' * (tabs + 1))
end_tabs = (' DCTB ' * tabs)
if isinstance(value, XCObject):
printable += valu... |
'Prints a key and value, members of an XCObject\'s _properties dictionary,
to file.
tabs is an int identifying the indentation level. If the class\'
_should_print_single_line variable is True, tabs is ignored and the
key-value pair will be followed by a space insead of a newline.'
| def _XCKVPrint(self, file, tabs, key, value):
| if self._should_print_single_line:
printable = ''
after_kv = ' '
else:
printable = (' DCTB ' * tabs)
after_kv = '\n'
if ((key == 'remoteGlobalIDString') and isinstance(self, PBXContainerItemProxy)):
value_to_print = value.id
else:
value_to_print = value... |
'Prints a reprentation of this object to file, adhering to Xcode output
formatting.'
| def Print(self, file=sys.stdout):
| self.VerifyHasRequiredProperties()
if self._should_print_single_line:
sep = ''
end_tabs = 0
else:
sep = '\n'
end_tabs = 2
self._XCPrint(file, 2, ((self._XCPrintableValue(2, self) + ' = {') + sep))
self._XCKVPrint(file, 3, 'isa', self.__class__.__name__)
for ... |
'Merge the supplied properties into the _properties dictionary.
The input properties must adhere to the class schema or a KeyError or
TypeError exception will be raised. If adding an object of an XCObject
subclass and the schema indicates a strong relationship, the object\'s
parent will be set to this object.
If do_co... | def UpdateProperties(self, properties, do_copy=False):
| if (properties is None):
return
for (property, value) in properties.iteritems():
if (not (property in self._schema)):
raise KeyError(((property + ' not in ') + self.__class__.__name__))
(is_list, property_type, is_strong) = self._schema[property][0:3]
if is_l... |
'Ensure that all properties identified as required by the schema are
set.'
| def VerifyHasRequiredProperties(self):
| for (property, attributes) in self._schema.iteritems():
(is_list, property_type, is_strong, is_required) = attributes[0:4]
if (is_required and (not (property in self._properties))):
raise KeyError(((self.__class__.__name__ + ' requires ') + property))
|
'Assign object default values according to the schema. This will not
overwrite properties that have already been set.'
| def _SetDefaultsFromSchema(self):
| defaults = {}
for (property, attributes) in self._schema.iteritems():
(is_list, property_type, is_strong, is_required) = attributes[0:4]
if (is_required and (len(attributes) >= 5) and (not (property in self._properties))):
default = attributes[4]
defaults[property] = defa... |
'Custom hashables for XCHierarchicalElements.
XCHierarchicalElements are special. Generally, their hashes shouldn\'t
change if the paths don\'t change. The normal XCObject implementation of
Hashables adds a hashable for each object, which means that if
the hierarchical structure changes (possibly due to changes cause... | def Hashables(self):
| if (self == self.PBXProjectAncestor()._properties['mainGroup']):
return XCObject.Hashables(self)
hashables = []
if ('name' in self._properties):
hashables.append((self.__class__.__name__ + '.name'))
hashables.append(self._properties['name'])
path = self.PathFromSourceTreeAndPath(... |
'Returns an existing or new file reference corresponding to path.
If hierarchical is True, this method will create or use the necessary
hierarchical group structure corresponding to path. Otherwise, it will
look in and create an item in the current group only.
If an existing matching reference is found, it is returned... | def AddOrGetFileByPath(self, path, hierarchical):
| is_dir = False
if path.endswith('/'):
is_dir = True
path = posixpath.normpath(path)
if is_dir:
path = (path + '/')
variant_name = None
parent = posixpath.dirname(path)
grandparent = posixpath.dirname(parent)
parent_basename = posixpath.basename(parent)
(parent_root, p... |
'Returns an existing or new PBXVariantGroup for name and path.
If a PBXVariantGroup identified by the name and path arguments is already
present as a child of this object, it is returned. Otherwise, a new
PBXVariantGroup with the correct properties is created, added as a child,
and returned.
This method will generally... | def AddOrGetVariantGroupByNameAndPath(self, name, path):
| key = (name, path)
if (key in self._variant_children_by_name_and_path):
variant_group_ref = self._variant_children_by_name_and_path[key]
assert (variant_group_ref.__class__ == PBXVariantGroup)
return variant_group_ref
variant_group_properties = {'name': name}
if (path != None):
... |
'If this PBXGroup has only one child and it\'s also a PBXGroup, take
it over by making all of its children this object\'s children.
This function will continue to take over only children when those children
are groups. If there are three PBXGroups representing a, b, and c, with
c inside b and b inside a, and a and b h... | def TakeOverOnlyChild(self, recurse=False):
| while ((len(self._properties['children']) == 1) and (self._properties['children'][0].__class__ == PBXGroup)):
child = self._properties['children'][0]
old_properties = self._properties
self._properties = child._properties
self._children_by_path = child._children_by_path
if ((n... |
'Convenience accessor to obtain an XCBuildConfiguration by name.'
| def ConfigurationNamed(self, name):
| for configuration in self._properties['buildConfigurations']:
if (configuration._properties['name'] == name):
return configuration
raise KeyError(name)
|
'Convenience accessor to obtain the default XCBuildConfiguration.'
| def DefaultConfiguration(self):
| return self.ConfigurationNamed(self._properties['defaultConfigurationName'])
|
'Determines the state of a build setting in all XCBuildConfiguration
child objects.
If all child objects have key in their build settings, and the value is the
same in all child objects, returns 1.
If no child objects have the key in their build settings, returns 0.
If some, but not all, child objects have the key in t... | def HasBuildSetting(self, key):
| has = None
value = None
for configuration in self._properties['buildConfigurations']:
configuration_has = configuration.HasBuildSetting(key)
if (has is None):
has = configuration_has
elif (has != configuration_has):
return (-1)
if configuration_has:
... |
'Gets the build setting for key.
All child XCConfiguration objects must have the same value set for the
setting, or a ValueError will be raised.'
| def GetBuildSetting(self, key):
| value = None
for configuration in self._properties['buildConfigurations']:
configuration_value = configuration.GetBuildSetting(key)
if (value is None):
value = configuration_value
elif (value != configuration_value):
raise ValueError(('Variant values for ... |
'Sets the build setting for key to value in all child
XCBuildConfiguration objects.'
| def SetBuildSetting(self, key, value):
| for configuration in self._properties['buildConfigurations']:
configuration.SetBuildSetting(key, value)
|
'Appends value to the build setting for key, which is treated as a list,
in all child XCBuildConfiguration objects.'
| def AppendBuildSetting(self, key, value):
| for configuration in self._properties['buildConfigurations']:
configuration.AppendBuildSetting(key, value)
|
'Deletes the build setting key from all child XCBuildConfiguration
objects.'
| def DelBuildSetting(self, key):
| for configuration in self._properties['buildConfigurations']:
configuration.DelBuildSetting(key)
|
'Sets the build configuration in all child XCBuildConfiguration objects.'
| def SetBaseConfiguration(self, value):
| for configuration in self._properties['buildConfigurations']:
configuration.SetBaseConfiguration(value)
|
'Adds path to the dict tracking paths belonging to this build phase.
If the path is already a member of this build phase, raises an exception.'
| def _AddPathToDict(self, pbxbuildfile, path):
| if (path in self._files_by_path):
raise ValueError(('Found multiple build files with path ' + path))
self._files_by_path[path] = pbxbuildfile
|
'Maintains the _files_by_path and _files_by_xcfilelikeelement dicts.
If path is specified, then it is the path that is being added to the
phase, and pbxbuildfile must contain either a PBXFileReference directly
referencing that path, or it must contain a PBXVariantGroup that itself
contains a PBXFileReference referencin... | def _AddBuildFileToDicts(self, pbxbuildfile, path=None):
| xcfilelikeelement = pbxbuildfile._properties['fileRef']
paths = []
if (path != None):
if isinstance(xcfilelikeelement, PBXVariantGroup):
paths.append(path)
elif isinstance(xcfilelikeelement, PBXVariantGroup):
for variant in xcfilelikeelement._properties['children']:
... |
'Set the dstSubfolderSpec and dstPath properties from path.
path may be specified in the same notation used for XCHierarchicalElements,
specifically, "$(DIR)/path".'
| def SetDestination(self, path):
| path_tree_match = self.path_tree_re.search(path)
if path_tree_match:
path_tree = path_tree_match.group(1)
relative_path = path_tree_match.group(3)
if (path_tree in self.path_tree_to_subfolder):
subfolder = self.path_tree_to_subfolder[path_tree]
if (relative_path i... |
'Returns a PBXGroup child of this object to which path should be added.
This method is intended to choose between SourceGroup and
IntermediatesGroup on the basis of whether path is present in a source
directory or an intermediates directory. For the purposes of this
determination, any path located within a derived fil... | def RootGroupForPath(self, path):
| source_tree_groups = {'DERIVED_FILE_DIR': (self.IntermediatesGroup, True), 'INTERMEDIATE_DIR': (self.IntermediatesGroup, True), 'PROJECT_DERIVED_FILE_DIR': (self.IntermediatesGroup, True), 'SHARED_INTERMEDIATE_DIR': (self.IntermediatesGroup, True)}
(source_tree, path) = SourceTreeAndPathFromPath(path)
if ((... |
'Returns a PBXFileReference corresponding to path in the correct group
according to RootGroupForPath\'s heuristics.
If an existing PBXFileReference for path exists, it will be returned.
Otherwise, one will be created and returned.'
| def AddOrGetFileInRootGroup(self, path):
| (group, hierarchical) = self.RootGroupForPath(path)
return group.AddOrGetFileByPath(path, hierarchical)
|
'Calls TakeOverOnlyChild for all groups in the main group.'
| def RootGroupsTakeOverOnlyChildren(self, recurse=False):
| for group in self._properties['mainGroup']._properties['children']:
if isinstance(group, PBXGroup):
group.TakeOverOnlyChild(recurse)
|
'Add a reference to another project file (via PBXProject object) to this
one.
Returns [ProductGroup, ProjectRef]. ProductGroup is a PBXGroup object in
this project file that contains a PBXReferenceProxy object for each
product of each PBXNativeTarget in the other project file. ProjectRef is
a PBXFileReference to the ... | def AddOrGetProjectReference(self, other_pbxproject):
| if (not ('projectReferences' in self._properties)):
self._properties['projectReferences'] = []
product_group = None
project_ref = None
if (not (other_pbxproject in self._other_pbxprojects)):
product_group = PBXGroup({'name': 'Products'})
product_group.parent = self
produc... |
'Returns the MSBuild equivalent of the MSVS value given.
Args:
value: the MSVS value to convert.
Returns:
the MSBuild equivalent.
Raises:
ValueError if value is not valid.'
| def ConvertToMSBuild(self, value):
| return value
|
'Dispatches a string command to a method.'
| def Dispatch(self, args):
| if (len(args) < 1):
raise Exception('Not enough arguments')
method = ('Exec%s' % self._CommandifyName(args[0]))
getattr(self, method)(*args[1:])
|
'Transforms a tool name like copy-info-plist to CopyInfoPlist'
| def _CommandifyName(self, name_string):
| return name_string.title().replace('-', '')
|
'Emulates the most basic behavior of Linux\'s flock(1).'
| def ExecFlock(self, lockfile, *cmd_list):
| fd = os.open(lockfile, ((os.O_WRONLY | os.O_NOCTTY) | os.O_CREAT), 438)
if sys.platform.startswith('aix'):
op = struct.pack('hhIllqq', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
else:
op = struct.pack('hhllhhl', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
fcntl.fcntl(fd, fcntl.F_SETLK, op)
return subproc... |
'Initializes Config. This is a separate method as it raises an exception
if there is a parse error.'
| def Init(self, params):
| generator_flags = params.get('generator_flags', {})
config_path = generator_flags.get('config_path', None)
if (not config_path):
return
try:
f = open(config_path, 'r')
config = json.load(f)
f.close()
except IOError:
raise Exception(('Unable to open fi... |
'Returns the supplied test targets without \'all\'.'
| def _supplied_target_names_no_all(self):
| result = self._supplied_target_names()
result.discard('all')
return result
|
'Returns true if the supplied files impact the build at all.'
| def is_build_impacted(self):
| return self._changed_targets
|
'Returns the set of output test targets.'
| def find_matching_test_target_names(self):
| assert self.is_build_impacted()
test_target_names_no_all = set(self._test_target_names)
test_target_names_no_all.discard('all')
test_targets_no_all = _LookupTargets(test_target_names_no_all, self._unqualified_mapping)
test_target_names_contains_all = ('all' in self._test_target_names)
if test_ta... |
'Returns the set of output compile targets.'
| def find_matching_compile_target_names(self):
| assert self.is_build_impacted()
for target in self._name_to_target.itervalues():
target.visited = False
supplied_targets = _LookupTargets(self._supplied_target_names_no_all(), self._unqualified_mapping)
if ('all' in self._supplied_target_names()):
supplied_targets = [x for x in (set(supp... |
'The main entry point: writes a .mk file for a single target.
Arguments:
qualified_target: target we\'re generating
relative_target: qualified target name relative to the root
base_path: path relative to source root we\'re building in, used to resolve
target-relative paths
output_filename: output .mk file name to write... | def Write(self, qualified_target, relative_target, base_path, output_filename, spec, configs, part_of_all, write_alias_target, sdk_version):
| gyp.common.EnsureDirExists(output_filename)
self.fp = open(output_filename, 'w')
self.fp.write(header)
self.qualified_target = qualified_target
self.relative_target = relative_target
self.path = base_path
self.target = spec['target_name']
self.type = spec['type']
self.toolset = spec[... |
'Write Makefile code for any \'actions\' from the gyp input.
extra_sources: a list that will be filled in with newly generated source
files, if any
extra_outputs: a list that will be filled in with any outputs of these
actions (used to make other pieces dependent on these
actions)'
| def WriteActions(self, actions, extra_sources, extra_outputs):
| for action in actions:
name = make.StringToMakefileVariable(('%s_%s' % (self.relative_target, action['action_name'])))
self.WriteLn(('### Rules for action "%s":' % action['action_name']))
inputs = action['inputs']
outputs = action['outputs']
dirs = set()
f... |
'Write Makefile code for any \'rules\' from the gyp input.
extra_sources: a list that will be filled in with newly generated source
files, if any
extra_outputs: a list that will be filled in with any outputs of these
rules (used to make other pieces dependent on these rules)'
| def WriteRules(self, rules, extra_sources, extra_outputs):
| if (len(rules) == 0):
return
for rule in rules:
if (len(rule.get('rule_sources', [])) == 0):
continue
name = make.StringToMakefileVariable(('%s_%s' % (self.relative_target, rule['rule_name'])))
self.WriteLn(('\n### Generated for rule "%s":' % name))
... |
'Write Makefile code for any \'copies\' from the gyp input.
extra_outputs: a list that will be filled in with any outputs of this action
(used to make other pieces dependent on this action)'
| def WriteCopies(self, copies, extra_outputs):
| self.WriteLn('### Generated for copy rule.')
variable = make.StringToMakefileVariable((self.relative_target + '_copies'))
outputs = []
for copy in copies:
for path in copy['files']:
if (not copy['destination'].startswith('$')):
print ('WARNING: Copy ... |
'Write out the flags and include paths used to compile source files for
the current target.
Args:
spec, configs: input from gyp.'
| def WriteSourceFlags(self, spec, configs):
| for (configname, config) in sorted(configs.iteritems()):
extracted_includes = []
self.WriteLn('\n# Flags passed to both C and C++ files.')
(cflags, includes_from_cflags) = self.ExtractIncludesFromCFlags((config.get('cflags', []) + config.get('cflags_c', [])))
... |
'Write Makefile code for any \'sources\' from the gyp input.
These are source files necessary to build the current target.
We need to handle shared_intermediate directory source files as
a special case by copying them to the intermediate directory and
treating them as a genereated sources. Otherwise the Android build
r... | def WriteSources(self, spec, configs, extra_sources):
| sources = filter(make.Compilable, spec.get('sources', []))
generated_not_sources = [x for x in extra_sources if (not make.Compilable(x))]
extra_sources = filter(make.Compilable, extra_sources)
all_sources = (sources + extra_sources)
local_cpp_extension = '.cpp'
for source in all_sources:
... |
'Return the Android module name used for a gyp spec.
We use the complete qualified target name to avoid collisions between
duplicate targets in different directories. We also add a suffix to
distinguish gyp-generated module names.'
| def ComputeAndroidModule(self, spec):
| if int(spec.get('android_unmangled_name', 0)):
assert ((self.type != 'shared_library') or self.target.startswith('lib'))
return self.target
if (self.type == 'shared_library'):
prefix = 'lib_'
else:
prefix = ''
if (spec['toolset'] == 'host'):
suffix = '_$(TARGET_$(... |
'Return the \'output basename\' of a gyp spec, split into filename + ext.
Android libraries must be named the same thing as their module name,
otherwise the linker can\'t find them, so product_name and so on must be
ignored if we are building a library, and the "lib" prepending is
not done for Android.'
| def ComputeOutputParts(self, spec):
| assert (self.type != 'loadable_module')
target = spec['target_name']
target_prefix = ''
target_ext = ''
if (self.type == 'static_library'):
target = self.ComputeAndroidModule(spec)
target_ext = '.a'
elif (self.type == 'shared_library'):
target = self.ComputeAndroidModule(... |
'Return the \'output basename\' of a gyp spec.
E.g., the loadable module \'foobar\' in directory \'baz\' will produce
\'libfoobar.so\''
| def ComputeOutputBasename(self, spec):
| return ''.join(self.ComputeOutputParts(spec))
|
'Return the \'output\' (full output path) of a gyp spec.
E.g., the loadable module \'foobar\' in directory \'baz\' will produce
\'$(obj)/baz/libfoobar.so\''
| def ComputeOutput(self, spec):
| if (self.type == 'executable'):
path = '$(gyp_shared_intermediate_dir)'
elif (self.type == 'shared_library'):
if (self.toolset == 'host'):
path = '$($(GYP_HOST_VAR_PREFIX)HOST_OUT_INTERMEDIATE_LIBRARIES)'
else:
path = '$($(GYP_VAR_PREFIX)TARGET_OUT_INTERMEDIATE_LI... |
'Normalize include_paths.
Convert absolute paths to relative to the Android top directory.
Args:
include_paths: A list of unprocessed include paths.
Returns:
A list of normalized include paths.'
| def NormalizeIncludePaths(self, include_paths):
| normalized = []
for path in include_paths:
if (path[0] == '/'):
path = gyp.common.RelativePath(path, self.android_top_dir)
normalized.append(path)
return normalized
|
'Extract includes "-I..." out from cflags
Args:
cflags: A list of compiler flags, which may be mixed with "-I.."
Returns:
A tuple of lists: (clean_clfags, include_paths). "-I.." is trimmed.'
| def ExtractIncludesFromCFlags(self, cflags):
| clean_cflags = []
include_paths = []
for flag in cflags:
if flag.startswith('-I'):
include_paths.append(flag[2:])
else:
clean_cflags.append(flag)
return (clean_cflags, include_paths)
|
'Filter the \'libraries\' key to separate things that shouldn\'t be ldflags.
Library entries that look like filenames should be converted to android
module names instead of being passed to the linker as flags.
Args:
libraries: the value of spec.get(\'libraries\')
Returns:
A tuple (static_lib_modules, dynamic_lib_module... | def FilterLibraries(self, libraries):
| static_lib_modules = []
dynamic_lib_modules = []
ldflags = []
for libs in libraries:
for lib in libs.split():
if ((lib == '-lc') or (lib == '-lstdc++') or (lib == '-lm') or lib.endswith('libgcc.a')):
continue
match = re.search('([^/]+)\\.a$', lib)
... |
'Compute the dependencies of a gyp spec.
Returns a tuple (deps, link_deps), where each is a list of
filenames that will need to be put in front of make for either
building (deps) or linking (link_deps).'
| def ComputeDeps(self, spec):
| deps = []
link_deps = []
if ('dependencies' in spec):
deps.extend([target_outputs[dep] for dep in spec['dependencies'] if target_outputs[dep]])
for dep in spec['dependencies']:
if (dep in target_link_deps):
link_deps.append(target_link_deps[dep])
deps.exte... |
'Write Makefile code to specify the link flags and library dependencies.
spec, configs: input from gyp.
link_deps: link dependency list; see ComputeDeps()'
| def WriteTargetFlags(self, spec, configs, link_deps):
| libraries = gyp.common.uniquer(spec.get('libraries', []))
(static_libs, dynamic_libs, ldflags_libs) = self.FilterLibraries(libraries)
if (self.type != 'static_library'):
for (configname, config) in sorted(configs.iteritems()):
ldflags = list(config.get('ldflags', []))
self.Wr... |
'Write Makefile code to produce the final target of the gyp spec.
spec, configs: input from gyp.
deps, link_deps: dependency lists; see ComputeDeps()
part_of_all: flag indicating this target is part of \'all\'
write_alias_target: flag indicating whether to create short aliases for this
target'
| def WriteTarget(self, spec, configs, deps, link_deps, part_of_all, write_alias_target):
| self.WriteLn('### Rules for final target.')
if (self.type != 'none'):
self.WriteTargetFlags(spec, configs, link_deps)
settings = spec.get('aosp_build_settings', {})
if settings:
self.WriteLn('### Set directly by aosp_build_settings.')
for (k, v) in setting... |
'Write a variable definition that is a list of values.
E.g. WriteList([\'a\',\'b\'], \'foo\', prefix=\'blah\') writes out
foo = blaha blahb
but in a pretty-printed style.'
| def WriteList(self, value_list, variable=None, prefix='', quoter=make.QuoteIfNecessary, local_pathify=False):
| values = ''
if value_list:
value_list = [quoter((prefix + l)) for l in value_list]
if local_pathify:
value_list = [self.LocalPathify(l) for l in value_list]
values = (' \\\n DCTB ' + ' \\\n DCTB '.join(value_list))
self.fp.write(('%s :=%s\n\n' % (variable, values... |
'Convert a subdirectory-relative path into a normalized path which starts
with the make variable $(LOCAL_PATH) (i.e. the top of the project tree).
Absolute paths, or paths that contain variables, are just normalized.'
| def LocalPathify(self, path):
| if (('$(' in path) or os.path.isabs(path)):
return os.path.normpath(path)
local_path = os.path.join('$(LOCAL_PATH)', self.path, path)
local_path = os.path.normpath(local_path)
assert local_path.startswith('$(LOCAL_PATH)'), ('Path %s attempts to escape from gyp path %s ... |
'Return true if this is a target that can be linked against.'
| def Linkable(self):
| return (self.type in ('static_library', 'shared_library'))
|
'Return true if the target should produce a restat rule based on a TOC
file.'
| def UsesToc(self, flavor):
| if ((flavor == 'win') or self.bundle):
return False
return (self.type in ('shared_library', 'loadable_module'))
|
'Return the path, if any, that should be used as a dependency of
any dependent action step.'
| def PreActionInput(self, flavor):
| if self.UsesToc(flavor):
return (self.FinalOutput() + '.TOC')
return (self.FinalOutput() or self.preaction_stamp)
|
'Return the path, if any, that should be used as a dependency of
any dependent compile step.'
| def PreCompileInput(self):
| return (self.actions_stamp or self.precompile_stamp)
|
'Return the last output of the target, which depends on all prior
steps.'
| def FinalOutput(self):
| return (self.bundle or self.binary or self.actions_stamp)
|
'base_dir: path from source root to directory containing this gyp file,
by gyp semantics, all input paths are relative to this
build_dir: path from source root to build output
toplevel_dir: path to the toplevel directory'
| def __init__(self, hash_for_rules, target_outputs, base_dir, build_dir, output_file, toplevel_build, output_file_name, flavor, toplevel_dir=None):
| self.hash_for_rules = hash_for_rules
self.target_outputs = target_outputs
self.base_dir = base_dir
self.build_dir = build_dir
self.ninja = ninja_syntax.Writer(output_file)
self.toplevel_build = toplevel_build
self.output_file_name = output_file_name
self.flavor = flavor
self.abs_buil... |
'Expand specials like $!PRODUCT_DIR in |path|.
If |product_dir| is None, assumes the cwd is already the product
dir. Otherwise, |product_dir| is the relative path to the product
dir.'
| def ExpandSpecial(self, path, product_dir=None):
| PRODUCT_DIR = '$!PRODUCT_DIR'
if (PRODUCT_DIR in path):
if product_dir:
path = path.replace(PRODUCT_DIR, product_dir)
else:
path = path.replace((PRODUCT_DIR + '/'), '')
path = path.replace((PRODUCT_DIR + '\\'), '')
path = path.replace(PRODUCT_DIR, ... |
'Translate a gyp path to a ninja path, optionally expanding environment
variable references in |path| with |env|.
See the above discourse on path conversions.'
| def GypPathToNinja(self, path, env=None):
| if env:
if (self.flavor == 'mac'):
path = gyp.xcode_emulation.ExpandEnvVars(path, env)
elif (self.flavor == 'win'):
path = gyp.msvs_emulation.ExpandMacros(path, env)
if path.startswith('$!'):
expanded = self.ExpandSpecial(path)
if (self.flavor == 'win'):
... |
'Translate a gyp path to a ninja path for writing output.
If qualified is True, qualify the resulting filename with the name
of the target. This is necessary when e.g. compiling the same
path twice for two separate output targets.
See the above discourse on path conversions.'
| def GypPathToUniqueOutput(self, path, qualified=True):
| path = self.ExpandSpecial(path)
assert (not path.startswith('$')), path
obj = 'obj'
if (self.toolset != 'target'):
obj += ('.' + self.toolset)
(path_dir, path_basename) = os.path.split(path)
assert (not os.path.isabs(path_dir)), ("'%s' can not be absolute path (see c... |
'Given a list of targets, return a path for a single file
representing the result of building all the targets or None.
Uses a stamp file if necessary.'
| def WriteCollapsedDependencies(self, name, targets, order_only=None):
| assert (targets == filter(None, targets)), targets
if (len(targets) == 0):
assert (not order_only)
return None
if ((len(targets) > 1) or order_only):
stamp = self.GypPathToUniqueOutput((name + '.stamp'))
targets = self.ninja.build(stamp, 'stamp', targets, order_only=order_onl... |
'The main entry point for NinjaWriter: write the build rules for a spec.
Returns a Target object, which represents the output paths for this spec.
Returns None if there are no outputs (e.g. a settings-only \'none\' type
target).'
| def WriteSpec(self, spec, config_name, generator_flags):
| self.config_name = config_name
self.name = spec['target_name']
self.toolset = spec['toolset']
config = spec['configurations'][config_name]
self.target = Target(spec['type'])
self.is_standalone_static_library = bool(spec.get('standalone_static_library', 0))
self.uses_cpp = False
self.is_m... |
'Handle the implicit VS .idl rule for one source file. Fills |outputs|
with files that are generated.'
| def _WinIdlRule(self, source, prebuild, outputs):
| (outdir, output, vars, flags) = self.msvs_settings.GetIdlBuildData(source, self.config_name)
outdir = self.GypPathToNinja(outdir)
def fix_path(path, rel=None):
path = os.path.join(outdir, path)
(dirname, basename) = os.path.split(source)
(root, ext) = os.path.splitext(basename)
... |
'Writes rules to match MSVS\'s implicit idl handling.'
| def WriteWinIdlFiles(self, spec, prebuild):
| assert (self.flavor == 'win')
if self.msvs_settings.HasExplicitIdlRulesOrActions(spec):
return []
outputs = []
for source in filter((lambda x: x.endswith('.idl')), spec['sources']):
self._WinIdlRule(source, prebuild, outputs)
return outputs
|
'Write out the Actions, Rules, and Copies steps. Return a path
representing the outputs of these steps.'
| def WriteActionsRulesCopies(self, spec, extra_sources, prebuild, mac_bundle_depends):
| outputs = []
if self.is_mac_bundle:
mac_bundle_resources = spec.get('mac_bundle_resources', [])[:]
else:
mac_bundle_resources = []
extra_mac_bundle_resources = []
if ('actions' in spec):
outputs += self.WriteActions(spec['actions'], extra_sources, prebuild, extra_mac_bundle_r... |
'Generate and return a description of a build step.
|verb| is the short summary, e.g. ACTION or RULE.
|message| is a hand-written description, or None if not available.
|fallback| is the gyp-level name of the step, usable as a fallback.'
| def GenerateDescription(self, verb, message, fallback):
| if (self.toolset != 'target'):
verb += ('(%s)' % self.toolset)
if message:
return ('%s %s' % (verb, self.ExpandSpecial(message)))
else:
return ('%s %s: %s' % (verb, self.name, fallback))
|
'Writes ninja edges for \'mac_bundle_resources\'.'
| def WriteMacBundleResources(self, resources, bundle_depends):
| xcassets = []
for (output, res) in gyp.xcode_emulation.GetMacBundleResources(generator_default_variables['PRODUCT_DIR'], self.xcode_settings, map(self.GypPathToNinja, resources)):
output = self.ExpandSpecial(output)
if (os.path.splitext(output)[(-1)] != '.xcassets'):
isBinary = self.... |
'Writes ninja edges for \'mac_bundle_resources\' .xcassets files.
This add an invocation of \'actool\' via the \'mac_tool.py\' helper script.
It assumes that the assets catalogs define at least one imageset and
thus an Assets.car file will be generated in the application resources
directory. If this is not the case, th... | def WriteMacXCassets(self, xcassets, bundle_depends):
| if (not xcassets):
return
extra_arguments = {}
settings_to_arg = {'XCASSETS_APP_ICON': 'app-icon', 'XCASSETS_LAUNCH_IMAGE': 'launch-image'}
settings = self.xcode_settings.xcode_settings[self.config_name]
for (settings_key, arg_name) in settings_to_arg.iteritems():
value = settings.ge... |
'Write build rules for bundle Info.plist files.'
| def WriteMacInfoPlist(self, partial_info_plist, bundle_depends):
| (info_plist, out, defines, extra_env) = gyp.xcode_emulation.GetMacInfoPlist(generator_default_variables['PRODUCT_DIR'], self.xcode_settings, self.GypPathToNinja)
if (not info_plist):
return
out = self.ExpandSpecial(out)
if defines:
intermediate_plist = self.GypPathToUniqueOutput(os.path.... |
'Write build rules to compile all of |sources|.'
| def WriteSources(self, ninja_file, config_name, config, sources, predepends, precompiled_header, spec):
| if (self.toolset == 'host'):
self.ninja.variable('ar', '$ar_host')
self.ninja.variable('cc', '$cc_host')
self.ninja.variable('cxx', '$cxx_host')
self.ninja.variable('ld', '$ld_host')
self.ninja.variable('ldxx', '$ldxx_host')
self.ninja.variable('nm', '$nm_host')
... |
'Write build rules to compile all of |sources|.'
| def WriteSourcesForArch(self, ninja_file, config_name, config, sources, predepends, precompiled_header, spec, arch=None):
| extra_defines = []
if (self.flavor == 'mac'):
cflags = self.xcode_settings.GetCflags(config_name, arch=arch)
cflags_c = self.xcode_settings.GetCflagsC(config_name)
cflags_cc = self.xcode_settings.GetCflagsCC(config_name)
cflags_objc = (['$cflags_c'] + self.xcode_settings.GetCflag... |
'Writes ninja rules to compile prefix headers.'
| def WritePchTargets(self, ninja_file, pch_commands):
| if (not pch_commands):
return
for (gch, lang_flag, lang, input) in pch_commands:
var_name = {'c': 'cflags_pch_c', 'cc': 'cflags_pch_cc', 'm': 'cflags_pch_objc', 'mm': 'cflags_pch_objcc'}[lang]
map = {'c': 'cc', 'cc': 'cxx', 'm': 'objc', 'mm': 'objcxx'}
cmd = map.get(lang)
... |
'Write out a link step. Fills out target.binary.'
| def WriteLink(self, spec, config_name, config, link_deps):
| if ((self.flavor != 'mac') or (len(self.archs) == 1)):
return self.WriteLinkForArch(self.ninja, spec, config_name, config, link_deps)
else:
output = self.ComputeOutput(spec)
inputs = [self.WriteLinkForArch(self.arch_subninjas[arch], spec, config_name, config, link_deps[arch], arch=arch) ... |
'Write out a link step. Fills out target.binary.'
| def WriteLinkForArch(self, ninja_file, spec, config_name, config, link_deps, arch=None):
| command = {'executable': 'link', 'loadable_module': 'solink_module', 'shared_library': 'solink'}[spec['type']]
command_suffix = ''
implicit_deps = set()
solibs = set()
order_deps = set()
if ('dependencies' in spec):
extra_link_deps = set()
for dep in spec['dependencies']:
... |
'Returns the variables toolchain would set for build steps.'
| def GetToolchainEnv(self, additional_settings=None):
| env = self.GetSortedXcodeEnv(additional_settings=additional_settings)
if (self.flavor == 'win'):
env = self.GetMsvsToolchainEnv(additional_settings=additional_settings)
return env
|
'Returns the variables Visual Studio would set for build steps.'
| def GetMsvsToolchainEnv(self, additional_settings=None):
| return self.msvs_settings.GetVSMacroEnv('$!PRODUCT_DIR', config=self.config_name)
|
'Returns the variables Xcode would set for build steps.'
| def GetSortedXcodeEnv(self, additional_settings=None):
| assert self.abs_build_dir
abs_build_dir = self.abs_build_dir
return gyp.xcode_emulation.GetSortedXcodeEnv(self.xcode_settings, abs_build_dir, os.path.join(abs_build_dir, self.build_to_base), self.config_name, additional_settings)
|
'Returns the variables Xcode would set for postbuild steps.'
| def GetSortedXcodePostbuildEnv(self):
| postbuild_settings = {}
strip_save_file = self.xcode_settings.GetPerTargetSetting('CHROMIUM_STRIP_SAVE_FILE')
if strip_save_file:
postbuild_settings['CHROMIUM_STRIP_SAVE_FILE'] = strip_save_file
return self.GetSortedXcodeEnv(additional_settings=postbuild_settings)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.