Commit f4fa98d2 authored by Hiroshi Ichikawa's avatar Hiroshi Ichikawa Committed by Commit Bot

Apply git cl format to //tools/licenses.py.

//tools has its own custom styling configuration to use 2-space indent:
https://source.chromium.org/chromium/chromium/src/+/master:tools/.style.yapf?originalUrl=https:%2F%2Fcs.chromium.org%2F
So it is expected that this CL converts the file to use 2-space indent
even though it's not compatible with the latest style guide.

Change-Id: I5fd40493eba702f5ffcc5aa932841a509554c665
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2132649
Auto-Submit: Hiroshi Ichikawa <ichikawa@chromium.org>
Reviewed-by: default avatarDavid Jean <djean@chromium.org>
Commit-Queue: David Jean <djean@chromium.org>
Cr-Commit-Position: refs/heads/master@{#756209}
parent 4c420c42
...@@ -365,173 +365,175 @@ KNOWN_NON_IOS_LIBRARIES = set([ ...@@ -365,173 +365,175 @@ KNOWN_NON_IOS_LIBRARIES = set([
class LicenseError(Exception): class LicenseError(Exception):
"""We raise this exception when a directory's licensing info isn't """We raise this exception when a directory's licensing info isn't
fully filled out.""" fully filled out."""
pass pass
def AbsolutePath(path, filename, root): def AbsolutePath(path, filename, root):
"""Convert a path in README.chromium to be absolute based on the source """Convert a path in README.chromium to be absolute based on the source
root.""" root."""
if filename.startswith('/'): if filename.startswith('/'):
# Absolute-looking paths are relative to the source root # Absolute-looking paths are relative to the source root
# (which is the directory we're run from). # (which is the directory we're run from).
absolute_path = os.path.join(root, filename[1:]) absolute_path = os.path.join(root, filename[1:])
else: else:
absolute_path = os.path.join(root, path, filename) absolute_path = os.path.join(root, path, filename)
if os.path.exists(absolute_path): if os.path.exists(absolute_path):
return absolute_path return absolute_path
return None return None
def ParseDir(path, root, require_license_file=True, optional_keys=None): def ParseDir(path, root, require_license_file=True, optional_keys=None):
"""Examine a third_party/foo component and extract its metadata.""" """Examine a third_party/foo component and extract its metadata."""
# Parse metadata fields out of README.chromium. # Parse metadata fields out of README.chromium.
# We examine "LICENSE" for the license file by default. # We examine "LICENSE" for the license file by default.
metadata = { metadata = {
"License File": "LICENSE", # Relative path to license text. "License File": "LICENSE", # Relative path to license text.
"Name": None, # Short name (for header on about:credits). "Name": None, # Short name (for header on about:credits).
"URL": None, # Project home page. "URL": None, # Project home page.
"License": None, # Software license. "License": None, # Software license.
} }
if optional_keys is None: if optional_keys is None:
optional_keys = [] optional_keys = []
if path in SPECIAL_CASES: if path in SPECIAL_CASES:
metadata.update(SPECIAL_CASES[path]) metadata.update(SPECIAL_CASES[path])
else: else:
# Try to find README.chromium. # Try to find README.chromium.
readme_path = os.path.join(root, path, 'README.chromium') readme_path = os.path.join(root, path, 'README.chromium')
if not os.path.exists(readme_path): if not os.path.exists(readme_path):
raise LicenseError("missing README.chromium or licenses.py " raise LicenseError("missing README.chromium or licenses.py "
"SPECIAL_CASES entry in %s\n" % path) "SPECIAL_CASES entry in %s\n" % path)
for line in open(readme_path): for line in open(readme_path):
line = line.strip() line = line.strip()
if not line: if not line:
break break
for key in list(metadata.keys()) + optional_keys: for key in list(metadata.keys()) + optional_keys:
field = key + ": " field = key + ": "
if line.startswith(field): if line.startswith(field):
metadata[key] = line[len(field):] metadata[key] = line[len(field):]
# Check that all expected metadata is present. # Check that all expected metadata is present.
errors = [] errors = []
for key, value in metadata.items(): for key, value in metadata.items():
if not value: if not value:
errors.append("couldn't find '" + key + "' line " errors.append("couldn't find '" + key + "' line "
"in README.chromium or licences.py " "in README.chromium or licences.py "
"SPECIAL_CASES") "SPECIAL_CASES")
# Special-case modules that aren't in the shipping product, so don't need # Special-case modules that aren't in the shipping product, so don't need
# their license in about:credits. # their license in about:credits.
if metadata["License File"] != NOT_SHIPPED: if metadata["License File"] != NOT_SHIPPED:
# Check that the license file exists. # Check that the license file exists.
for filename in (metadata["License File"], "COPYING"): for filename in (metadata["License File"], "COPYING"):
license_path = AbsolutePath(path, filename, root) license_path = AbsolutePath(path, filename, root)
if license_path is not None: if license_path is not None:
break break
if require_license_file and not license_path: if require_license_file and not license_path:
errors.append("License file not found. " errors.append("License file not found. "
"Either add a file named LICENSE, " "Either add a file named LICENSE, "
"import upstream's COPYING if available, " "import upstream's COPYING if available, "
"or add a 'License File:' line to " "or add a 'License File:' line to "
"README.chromium with the appropriate path.") "README.chromium with the appropriate path.")
metadata["License File"] = license_path metadata["License File"] = license_path
if errors: if errors:
raise LicenseError("Errors in %s:\n %s\n" % (path, ";\n ".join(errors))) raise LicenseError("Errors in %s:\n %s\n" % (path, ";\n ".join(errors)))
return metadata return metadata
def ContainsFiles(path, root): def ContainsFiles(path, root):
"""Determines whether any files exist in a directory or in any of its """Determines whether any files exist in a directory or in any of its
subdirectories.""" subdirectories."""
for _, dirs, files in os.walk(os.path.join(root, path)): for _, dirs, files in os.walk(os.path.join(root, path)):
if files: if files:
return True return True
for vcs_metadata in VCS_METADATA_DIRS: for vcs_metadata in VCS_METADATA_DIRS:
if vcs_metadata in dirs: if vcs_metadata in dirs:
dirs.remove(vcs_metadata) dirs.remove(vcs_metadata)
return False return False
def FilterDirsWithFiles(dirs_list, root): def FilterDirsWithFiles(dirs_list, root):
# If a directory contains no files, assume it's a DEPS directory for a # If a directory contains no files, assume it's a DEPS directory for a
# project not used by our current configuration and skip it. # project not used by our current configuration and skip it.
return [x for x in dirs_list if ContainsFiles(x, root)] return [x for x in dirs_list if ContainsFiles(x, root)]
def FindThirdPartyDirs(prune_paths, root): def FindThirdPartyDirs(prune_paths, root):
"""Find all third_party directories underneath the source root.""" """Find all third_party directories underneath the source root."""
third_party_dirs = set() third_party_dirs = set()
for path, dirs, files in os.walk(root): for path, dirs, files in os.walk(root):
path = path[len(root)+1:] # Pretty up the path. path = path[len(root) + 1:] # Pretty up the path.
if path in prune_paths: if path in prune_paths:
dirs[:] = [] dirs[:] = []
continue continue
# Prune out directories we want to skip. # Prune out directories we want to skip.
# (Note that we loop over PRUNE_DIRS so we're not iterating over a # (Note that we loop over PRUNE_DIRS so we're not iterating over a
# list that we're simultaneously mutating.) # list that we're simultaneously mutating.)
for skip in PRUNE_DIRS: for skip in PRUNE_DIRS:
if skip in dirs: if skip in dirs:
dirs.remove(skip) dirs.remove(skip)
if os.path.basename(path) == 'third_party': if os.path.basename(path) == 'third_party':
# Add all subdirectories that are not marked for skipping. # Add all subdirectories that are not marked for skipping.
for dir in dirs: for dir in dirs:
dirpath = os.path.join(path, dir) dirpath = os.path.join(path, dir)
additional_paths_file = os.path.join( additional_paths_file = os.path.join(root, dirpath,
root, dirpath, ADDITIONAL_PATHS_FILENAME) ADDITIONAL_PATHS_FILENAME)
if dirpath not in prune_paths: if dirpath not in prune_paths:
third_party_dirs.add(dirpath) third_party_dirs.add(dirpath)
if os.path.exists(additional_paths_file): if os.path.exists(additional_paths_file):
with open(additional_paths_file) as paths_file: with open(additional_paths_file) as paths_file:
extra_paths = json.load(paths_file) extra_paths = json.load(paths_file)
third_party_dirs.update([ third_party_dirs.update(
os.path.join(dirpath, p) for p in extra_paths]) [os.path.join(dirpath, p) for p in extra_paths])
# Don't recurse into any subdirs from here. # Don't recurse into any subdirs from here.
dirs[:] = [] dirs[:] = []
continue continue
# Don't recurse into paths in ADDITIONAL_PATHS, like we do with regular # Don't recurse into paths in ADDITIONAL_PATHS, like we do with regular
# third_party/foo paths. # third_party/foo paths.
if path in ADDITIONAL_PATHS: if path in ADDITIONAL_PATHS:
dirs[:] = [] dirs[:] = []
for dir in ADDITIONAL_PATHS: for dir in ADDITIONAL_PATHS:
if dir not in prune_paths: if dir not in prune_paths:
third_party_dirs.add(dir) third_party_dirs.add(dir)
return third_party_dirs return third_party_dirs
def FindThirdPartyDirsWithFiles(root): def FindThirdPartyDirsWithFiles(root):
third_party_dirs = FindThirdPartyDirs(PRUNE_PATHS, root) third_party_dirs = FindThirdPartyDirs(PRUNE_PATHS, root)
return FilterDirsWithFiles(third_party_dirs, root) return FilterDirsWithFiles(third_party_dirs, root)
# Many builders do not contain 'gn' in their PATH, so use the GN binary from # Many builders do not contain 'gn' in their PATH, so use the GN binary from
# //buildtools. # //buildtools.
def _GnBinary(): def _GnBinary():
exe = 'gn' exe = 'gn'
if sys.platform.startswith('linux'): if sys.platform.startswith('linux'):
subdir = 'linux64' subdir = 'linux64'
elif sys.platform == 'darwin': elif sys.platform == 'darwin':
subdir = 'mac' subdir = 'mac'
elif sys.platform == 'win32': elif sys.platform == 'win32':
subdir, exe = 'win', 'gn.exe' subdir, exe = 'win', 'gn.exe'
else: else:
raise RuntimeError("Unsupported platform '%s'." % sys.platform) raise RuntimeError("Unsupported platform '%s'." % sys.platform)
return os.path.join(_REPOSITORY_ROOT, 'buildtools', subdir, exe) return os.path.join(_REPOSITORY_ROOT, 'buildtools', subdir, exe)
def GetThirdPartyDepsFromGNDepsOutput(gn_deps, target_os): def GetThirdPartyDepsFromGNDepsOutput(gn_deps, target_os):
"""Returns third_party/foo directories given the output of "gn desc deps". """Returns third_party/foo directories given the output of "gn desc deps".
Note that it always returns the direct sub-directory of third_party Note that it always returns the direct sub-directory of third_party
where README.chromium and LICENSE files are, so that it can be passed to where README.chromium and LICENSE files are, so that it can be passed to
...@@ -540,269 +542,265 @@ def GetThirdPartyDepsFromGNDepsOutput(gn_deps, target_os): ...@@ -540,269 +542,265 @@ def GetThirdPartyDepsFromGNDepsOutput(gn_deps, target_os):
It returns relative paths from _REPOSITORY_ROOT, not absolute paths. It returns relative paths from _REPOSITORY_ROOT, not absolute paths.
""" """
third_party_deps = set() third_party_deps = set()
for absolute_build_dep in gn_deps.split(): for absolute_build_dep in gn_deps.split():
relative_build_dep = os.path.relpath( relative_build_dep = os.path.relpath(absolute_build_dep, _REPOSITORY_ROOT)
absolute_build_dep, _REPOSITORY_ROOT) m = re.search(
m = re.search( r'^((.+[/\\])?third_party[/\\][^/\\]+[/\\])(.+[/\\])?BUILD\.gn$',
r'^((.+[/\\])?third_party[/\\][^/\\]+[/\\])(.+[/\\])?BUILD\.gn$', relative_build_dep)
relative_build_dep) if not m:
if not m: continue
continue third_party_path = m.group(1)
third_party_path = m.group(1) if any(third_party_path.startswith(p + os.sep) for p in PRUNE_PATHS):
if any(third_party_path.startswith(p + os.sep) for p in PRUNE_PATHS): continue
continue if (target_os == 'ios' and any(
if (target_os == 'ios' and third_party_path.startswith(p + os.sep)
any(third_party_path.startswith(p + os.sep) for p in KNOWN_NON_IOS_LIBRARIES)):
for p in KNOWN_NON_IOS_LIBRARIES)): # Skip over files that are known not to be used on iOS.
# Skip over files that are known not to be used on iOS. continue
continue third_party_deps.add(third_party_path[:-1])
third_party_deps.add(third_party_path[:-1]) return third_party_deps
return third_party_deps
def FindThirdPartyDeps(gn_out_dir, gn_target, target_os): def FindThirdPartyDeps(gn_out_dir, gn_target, target_os):
if not gn_out_dir: if not gn_out_dir:
raise RuntimeError("--gn-out-dir is required if --gn-target is used.") raise RuntimeError("--gn-out-dir is required if --gn-target is used.")
# Generate gn project in temp directory and use it to find dependencies. # Generate gn project in temp directory and use it to find dependencies.
# Current gn directory cannot be used when we run this script in a gn action # Current gn directory cannot be used when we run this script in a gn action
# rule, because gn doesn't allow recursive invocations due to potential side # rule, because gn doesn't allow recursive invocations due to potential side
# effects. # effects.
tmp_dir = None tmp_dir = None
try: try:
tmp_dir = tempfile.mkdtemp(dir = gn_out_dir) tmp_dir = tempfile.mkdtemp(dir=gn_out_dir)
shutil.copy(os.path.join(gn_out_dir, "args.gn"), tmp_dir) shutil.copy(os.path.join(gn_out_dir, "args.gn"), tmp_dir)
subprocess.check_output([_GnBinary(), "gen", tmp_dir]) subprocess.check_output([_GnBinary(), "gen", tmp_dir])
gn_deps = subprocess.check_output([ gn_deps = subprocess.check_output([
_GnBinary(), "desc", tmp_dir, gn_target, _GnBinary(), "desc", tmp_dir, gn_target, "deps", "--as=buildfile",
"deps", "--as=buildfile", "--all"]) "--all"
if isinstance(gn_deps, bytes): ])
gn_deps = gn_deps.decode("utf-8") if isinstance(gn_deps, bytes):
finally: gn_deps = gn_deps.decode("utf-8")
if tmp_dir and os.path.exists(tmp_dir): finally:
shutil.rmtree(tmp_dir) if tmp_dir and os.path.exists(tmp_dir):
shutil.rmtree(tmp_dir)
return GetThirdPartyDepsFromGNDepsOutput(gn_deps, target_os)
return GetThirdPartyDepsFromGNDepsOutput(gn_deps, target_os)
def ScanThirdPartyDirs(root=None): def ScanThirdPartyDirs(root=None):
"""Scan a list of directories and report on any problems we find.""" """Scan a list of directories and report on any problems we find."""
if root is None: if root is None:
root = os.getcwd() root = os.getcwd()
third_party_dirs = FindThirdPartyDirsWithFiles(root) third_party_dirs = FindThirdPartyDirsWithFiles(root)
errors = [] errors = []
for path in sorted(third_party_dirs): for path in sorted(third_party_dirs):
try: try:
metadata = ParseDir(path, root) metadata = ParseDir(path, root)
except LicenseError as e: except LicenseError as e:
errors.append((path, e.args[0])) errors.append((path, e.args[0]))
continue continue
for path, error in sorted(errors): for path, error in sorted(errors):
print(path + ": " + error) print(path + ": " + error)
return len(errors) == 0 return len(errors) == 0
def GenerateCredits( def GenerateCredits(
file_template_file, entry_template_file, output_file, target_os, file_template_file, entry_template_file, output_file, target_os,
gn_out_dir, gn_target, depfile=None): gn_out_dir, gn_target, depfile=None):
"""Generate about:credits.""" """Generate about:credits."""
def EvaluateTemplate(template, env, escape=True): def EvaluateTemplate(template, env, escape=True):
"""Expand a template with variables like {{foo}} using a """Expand a template with variables like {{foo}} using a
dictionary of expansions.""" dictionary of expansions."""
for key, val in env.items(): for key, val in env.items():
if escape: if escape:
val = html.escape(val) val = html.escape(val)
template = template.replace('{{%s}}' % key, val) template = template.replace('{{%s}}' % key, val)
return template return template
def MetadataToTemplateEntry(metadata, entry_template): def MetadataToTemplateEntry(metadata, entry_template):
env = { env = {
'name': metadata['Name'], 'name': metadata['Name'],
'url': metadata['URL'], 'url': metadata['URL'],
'license': open(metadata['License File']).read(), 'license': open(metadata['License File']).read(),
} }
return { return {
'name': metadata['Name'], 'name': metadata['Name'],
'content': EvaluateTemplate(entry_template, env), 'content': EvaluateTemplate(entry_template, env),
'license_file': metadata['License File'], 'license_file': metadata['License File'],
} }
if gn_target: if gn_target:
third_party_dirs = FindThirdPartyDeps(gn_out_dir, gn_target, target_os) third_party_dirs = FindThirdPartyDeps(gn_out_dir, gn_target, target_os)
# Sanity-check to raise a build error if invalid gn_... settings are # Sanity-check to raise a build error if invalid gn_... settings are
# somehow passed to this script. # somehow passed to this script.
if not third_party_dirs: if not third_party_dirs:
raise RuntimeError("No deps found.") raise RuntimeError("No deps found.")
else: else:
third_party_dirs = FindThirdPartyDirs(PRUNE_PATHS, _REPOSITORY_ROOT) third_party_dirs = FindThirdPartyDirs(PRUNE_PATHS, _REPOSITORY_ROOT)
if not file_template_file: if not file_template_file:
file_template_file = os.path.join(_REPOSITORY_ROOT, 'components', file_template_file = os.path.join(_REPOSITORY_ROOT, 'components',
'about_ui', 'resources', 'about_ui', 'resources',
'about_credits.tmpl') 'about_credits.tmpl')
if not entry_template_file: if not entry_template_file:
entry_template_file = os.path.join(_REPOSITORY_ROOT, 'components', entry_template_file = os.path.join(_REPOSITORY_ROOT, 'components',
'about_ui', 'resources', 'about_ui', 'resources',
'about_credits_entry.tmpl') 'about_credits_entry.tmpl')
entry_template = open(entry_template_file).read() entry_template = open(entry_template_file).read()
entries = [] entries = []
# Start from Chromium's LICENSE file # Start from Chromium's LICENSE file
chromium_license_metadata = { chromium_license_metadata = {
'Name': 'The Chromium Project', 'Name': 'The Chromium Project',
'URL': 'http://www.chromium.org', 'URL': 'http://www.chromium.org',
'License File': os.path.join(_REPOSITORY_ROOT, 'LICENSE') } 'License File': os.path.join(_REPOSITORY_ROOT, 'LICENSE')
entries.append(MetadataToTemplateEntry(chromium_license_metadata, }
entry_template)) entries.append(
MetadataToTemplateEntry(chromium_license_metadata, entry_template))
for path in third_party_dirs:
try: for path in third_party_dirs:
metadata = ParseDir(path, _REPOSITORY_ROOT) try:
except LicenseError: metadata = ParseDir(path, _REPOSITORY_ROOT)
# TODO(phajdan.jr): Convert to fatal error (http://crbug.com/39240). except LicenseError:
continue # TODO(phajdan.jr): Convert to fatal error (http://crbug.com/39240).
if metadata['License File'] == NOT_SHIPPED: continue
continue if metadata['License File'] == NOT_SHIPPED:
if target_os == 'ios' and not gn_target: continue
# Skip over files that are known not to be used on iOS. But if target_os == 'ios' and not gn_target:
# skipping is unnecessary if GN was used to query the actual # Skip over files that are known not to be used on iOS. But
# dependencies. # skipping is unnecessary if GN was used to query the actual
# TODO(lambroslambrou): Remove this step once the iOS build is # dependencies.
# updated to provide --gn-target to this script. # TODO(lambroslambrou): Remove this step once the iOS build is
if path in KNOWN_NON_IOS_LIBRARIES: # updated to provide --gn-target to this script.
continue if path in KNOWN_NON_IOS_LIBRARIES:
entries.append(MetadataToTemplateEntry(metadata, entry_template)) continue
entries.append(MetadataToTemplateEntry(metadata, entry_template))
entries.sort(key=lambda entry: (entry['name'].lower(), entry['content']))
for entry_id, entry in enumerate(entries): entries.sort(key=lambda entry: (entry['name'].lower(), entry['content']))
entry['content'] = entry['content'].replace('{{id}}', str(entry_id)) for entry_id, entry in enumerate(entries):
entry['content'] = entry['content'].replace('{{id}}', str(entry_id))
entries_contents = '\n'.join([entry['content'] for entry in entries])
file_template = open(file_template_file).read() entries_contents = '\n'.join([entry['content'] for entry in entries])
template_contents = "<!-- Generated by licenses.py; do not edit. -->" file_template = open(file_template_file).read()
template_contents += EvaluateTemplate(file_template, template_contents = "<!-- Generated by licenses.py; do not edit. -->"
{'entries': entries_contents}, template_contents += EvaluateTemplate(
escape=False) file_template, {'entries': entries_contents}, escape=False)
if output_file: if output_file:
changed = True changed = True
try: try:
old_output = open(output_file, 'r').read() old_output = open(output_file, 'r').read()
if old_output == template_contents: if old_output == template_contents:
changed = False changed = False
except: except:
pass pass
if changed: if changed:
with open(output_file, 'w') as output: with open(output_file, 'w') as output:
output.write(template_contents) output.write(template_contents)
else: else:
print(template_contents) print(template_contents)
if depfile: if depfile:
assert output_file assert output_file
# Add in build.ninja so that the target will be considered dirty whenever # Add in build.ninja so that the target will be considered dirty whenever
# gn gen is run. Otherwise, it will fail to notice new files being added. # gn gen is run. Otherwise, it will fail to notice new files being added.
# This is still no perfect, as it will fail if no build files are changed, # This is still no perfect, as it will fail if no build files are changed,
# but a new README.chromium / LICENSE is added. This shouldn't happen in # but a new README.chromium / LICENSE is added. This shouldn't happen in
# practice however. # practice however.
license_file_list = (entry['license_file'] for entry in entries) license_file_list = (entry['license_file'] for entry in entries)
license_file_list = (os.path.relpath(p) for p in license_file_list) license_file_list = (os.path.relpath(p) for p in license_file_list)
license_file_list = sorted(set(license_file_list)) license_file_list = sorted(set(license_file_list))
build_utils.WriteDepfile(depfile, output_file, build_utils.WriteDepfile(depfile, output_file,
license_file_list + ['build.ninja']) license_file_list + ['build.ninja'])
return True return True
def _ReadFile(path): def _ReadFile(path):
"""Reads a file from disk. """Reads a file from disk.
Args: Args:
path: The path of the file to read, relative to the root of the path: The path of the file to read, relative to the root of the
repository. repository.
Returns: Returns:
The contents of the file as a string. The contents of the file as a string.
""" """
with codecs.open(os.path.join(_REPOSITORY_ROOT, path), 'r', 'utf-8') as f: with codecs.open(os.path.join(_REPOSITORY_ROOT, path), 'r', 'utf-8') as f:
return f.read() return f.read()
def GenerateLicenseFile(output_file, gn_out_dir, gn_target, target_os): def GenerateLicenseFile(output_file, gn_out_dir, gn_target, target_os):
"""Generate a plain-text LICENSE file which can be used when you ship a part """Generate a plain-text LICENSE file which can be used when you ship a part
of Chromium code (specified by gn_target) as a stand-alone library of Chromium code (specified by gn_target) as a stand-alone library
(e.g., //ios/web_view). (e.g., //ios/web_view).
The LICENSE file contains licenses of both Chromium and third-party The LICENSE file contains licenses of both Chromium and third-party
libraries which gn_target depends on. """ libraries which gn_target depends on. """
third_party_dirs = FindThirdPartyDeps(gn_out_dir, gn_target, target_os) third_party_dirs = FindThirdPartyDeps(gn_out_dir, gn_target, target_os)
# Start with Chromium's LICENSE file. # Start with Chromium's LICENSE file.
content = [_ReadFile('LICENSE')] content = [_ReadFile('LICENSE')]
# Add necessary third_party. # Add necessary third_party.
for directory in sorted(third_party_dirs): for directory in sorted(third_party_dirs):
metadata = ParseDir( metadata = ParseDir(directory, _REPOSITORY_ROOT, require_license_file=True)
directory, _REPOSITORY_ROOT, require_license_file=True) content.append('-' * 20)
content.append('-' * 20) content.append(directory.split(os.sep)[-1])
content.append(directory.split(os.sep)[-1]) content.append('-' * 20)
content.append('-' * 20) license_file = metadata['License File']
license_file = metadata['License File'] if license_file and license_file != NOT_SHIPPED:
if license_file and license_file != NOT_SHIPPED: content.append(_ReadFile(license_file))
content.append(_ReadFile(license_file))
content_text = '\n'.join(content) content_text = '\n'.join(content)
if output_file: if output_file:
with codecs.open(output_file, 'w', 'utf-8') as output: with codecs.open(output_file, 'w', 'utf-8') as output:
output.write(content_text) output.write(content_text)
else: else:
print(content_text) print(content_text)
def main(): def main():
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('--file-template', parser.add_argument(
help='Template HTML to use for the license page.') '--file-template', help='Template HTML to use for the license page.')
parser.add_argument('--entry-template', parser.add_argument(
help='Template HTML to use for each license.') '--entry-template', help='Template HTML to use for each license.')
parser.add_argument('--target-os', parser.add_argument('--target-os', help='OS that this build is targeting.')
help='OS that this build is targeting.') parser.add_argument(
parser.add_argument('--gn-out-dir', '--gn-out-dir', help='GN output directory for scanning dependencies.')
help='GN output directory for scanning dependencies.') parser.add_argument('--gn-target', help='GN target to scan for dependencies.')
parser.add_argument('--gn-target', parser.add_argument(
help='GN target to scan for dependencies.') 'command', choices=['help', 'scan', 'credits', 'license_file'])
parser.add_argument('command', parser.add_argument('output_file', nargs='?')
choices=['help', 'scan', 'credits', 'license_file']) build_utils.AddDepfileOption(parser)
parser.add_argument('output_file', nargs='?') args = parser.parse_args()
build_utils.AddDepfileOption(parser)
args = parser.parse_args() if args.command == 'scan':
if not ScanThirdPartyDirs():
if args.command == 'scan': return 1
if not ScanThirdPartyDirs(): elif args.command == 'credits':
return 1 if not GenerateCredits(args.file_template, args.entry_template,
elif args.command == 'credits': args.output_file, args.target_os, args.gn_out_dir,
if not GenerateCredits(args.file_template, args.entry_template, args.gn_target, args.depfile):
args.output_file, args.target_os, return 1
args.gn_out_dir, args.gn_target, args.depfile): elif args.command == 'license_file':
return 1 try:
elif args.command == 'license_file': GenerateLicenseFile(args.output_file, args.gn_out_dir, args.gn_target,
try: args.target_os)
GenerateLicenseFile( except LicenseError as e:
args.output_file, args.gn_out_dir, args.gn_target, print("Failed to parse README.chromium: {}".format(e))
args.target_os) return 1
except LicenseError as e: else:
print("Failed to parse README.chromium: {}".format(e)) print(__doc__)
return 1 return 1
else:
print(__doc__)
return 1
if __name__ == '__main__': if __name__ == '__main__':
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment