NSS: {EC,RSA}PrivateKey shouldn't call crypto::GetPublicNSSKeySlot or GetPrivateNSSKe...
[chromium-blink-merge.git] / tools / licenses.py
blobe87a54d1682565088f01b458b7d5f7d18eda111c
1 #!/usr/bin/env python
2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """Utility for checking and processing licensing information in third_party
7 directories.
9 Usage: licenses.py <command>
11 Commands:
12 scan scan third_party directories, verifying that we have licensing info
13 credits generate about:credits on stdout
15 (You can also import this as a module.)
16 """
18 import cgi
19 import os
20 import sys
22 # Paths from the root of the tree to directories to skip.
23 PRUNE_PATHS = set([
24 # Same module occurs in crypto/third_party/nss and net/third_party/nss, so
25 # skip this one.
26 os.path.join('third_party','nss'),
28 # Placeholder directory only, not third-party code.
29 os.path.join('third_party','adobe'),
31 # Build files only, not third-party code.
32 os.path.join('third_party','widevine'),
34 # Only binaries, used during development.
35 os.path.join('third_party','valgrind'),
37 # Used for development and test, not in the shipping product.
38 os.path.join('third_party','bison'),
39 os.path.join('third_party','cygwin'),
40 os.path.join('third_party','gnu_binutils'),
41 os.path.join('third_party','gold'),
42 os.path.join('third_party','gperf'),
43 os.path.join('third_party','lighttpd'),
44 os.path.join('third_party','llvm'),
45 os.path.join('third_party','llvm-build'),
46 os.path.join('third_party','mingw-w64'),
47 os.path.join('third_party','nacl_sdk_binaries'),
48 os.path.join('third_party','pefile'),
49 os.path.join('third_party','perl'),
50 os.path.join('third_party','psyco_win32'),
51 os.path.join('third_party','pylib'),
52 os.path.join('third_party','python_26'),
53 os.path.join('third_party','pywebsocket'),
54 os.path.join('third_party','syzygy'),
55 os.path.join('tools','gn'),
57 # Chromium code in third_party.
58 os.path.join('third_party','fuzzymatch'),
59 os.path.join('tools', 'swarming_client'),
61 # Stuff pulled in from chrome-internal for official builds/tools.
62 os.path.join('third_party', 'clear_cache'),
63 os.path.join('third_party', 'gnu'),
64 os.path.join('third_party', 'googlemac'),
65 os.path.join('third_party', 'pcre'),
66 os.path.join('third_party', 'psutils'),
67 os.path.join('third_party', 'sawbuck'),
69 # Redistribution does not require attribution in documentation.
70 os.path.join('third_party','directxsdk'),
71 os.path.join('third_party','platformsdk_win2008_6_1'),
72 os.path.join('third_party','platformsdk_win7'),
75 # Directories we don't scan through.
76 VCS_METADATA_DIRS = ('.svn', '.git')
77 PRUNE_DIRS = (VCS_METADATA_DIRS +
78 ('out', 'Debug', 'Release', # build files
79 'layout_tests')) # lots of subdirs
81 ADDITIONAL_PATHS = (
82 os.path.join('breakpad'),
83 os.path.join('chrome', 'common', 'extensions', 'docs', 'examples'),
84 os.path.join('chrome', 'test', 'chromeos', 'autotest'),
85 os.path.join('chrome', 'test', 'data'),
86 os.path.join('native_client'),
87 os.path.join('net', 'tools', 'spdyshark'),
88 os.path.join('sdch', 'open-vcdiff'),
89 os.path.join('testing', 'gmock'),
90 os.path.join('testing', 'gtest'),
91 # The directory with the word list for Chinese and Japanese segmentation
92 # with different license terms than ICU.
93 os.path.join('third_party','icu','source','data','brkitr'),
94 os.path.join('tools', 'grit'),
95 os.path.join('tools', 'gyp'),
96 os.path.join('tools', 'page_cycler', 'acid3'),
97 os.path.join('url', 'third_party', 'mozilla'),
98 os.path.join('v8'),
99 # Fake directory so we can include the strongtalk license.
100 os.path.join('v8', 'strongtalk'),
104 # Directories where we check out directly from upstream, and therefore
105 # can't provide a README.chromium. Please prefer a README.chromium
106 # wherever possible.
107 SPECIAL_CASES = {
108 os.path.join('native_client'): {
109 "Name": "native client",
110 "URL": "http://code.google.com/p/nativeclient",
111 "License": "BSD",
113 os.path.join('sdch', 'open-vcdiff'): {
114 "Name": "open-vcdiff",
115 "URL": "http://code.google.com/p/open-vcdiff",
116 "License": "Apache 2.0, MIT, GPL v2 and custom licenses",
117 "License Android Compatible": "yes",
119 os.path.join('testing', 'gmock'): {
120 "Name": "gmock",
121 "URL": "http://code.google.com/p/googlemock",
122 "License": "BSD",
123 "License File": "NOT_SHIPPED",
125 os.path.join('testing', 'gtest'): {
126 "Name": "gtest",
127 "URL": "http://code.google.com/p/googletest",
128 "License": "BSD",
129 "License File": "NOT_SHIPPED",
131 os.path.join('third_party', 'angle'): {
132 "Name": "Almost Native Graphics Layer Engine",
133 "URL": "http://code.google.com/p/angleproject/",
134 "License": "BSD",
136 os.path.join('third_party', 'cros_system_api'): {
137 "Name": "Chromium OS system API",
138 "URL": "http://www.chromium.org/chromium-os",
139 "License": "BSD",
140 # Absolute path here is resolved as relative to the source root.
141 "License File": "/LICENSE.chromium_os",
143 os.path.join('third_party', 'GTM'): {
144 "Name": "Google Toolbox for Mac",
145 "URL": "http://code.google.com/p/google-toolbox-for-mac/",
146 "License": "Apache 2.0",
147 "License File": "COPYING",
149 os.path.join('third_party', 'lss'): {
150 "Name": "linux-syscall-support",
151 "URL": "http://code.google.com/p/linux-syscall-support/",
152 "License": "BSD",
153 "License File": "/LICENSE",
155 os.path.join('third_party', 'ots'): {
156 "Name": "OTS (OpenType Sanitizer)",
157 "URL": "http://code.google.com/p/ots/",
158 "License": "BSD",
160 os.path.join('third_party', 'pdfsqueeze'): {
161 "Name": "pdfsqueeze",
162 "URL": "http://code.google.com/p/pdfsqueeze/",
163 "License": "Apache 2.0",
164 "License File": "COPYING",
166 os.path.join('third_party', 'ppapi'): {
167 "Name": "ppapi",
168 "URL": "http://code.google.com/p/ppapi/",
170 os.path.join('third_party', 'scons-2.0.1'): {
171 "Name": "scons-2.0.1",
172 "URL": "http://www.scons.org",
173 "License": "MIT",
174 "License File": "NOT_SHIPPED",
176 os.path.join('third_party', 'trace-viewer'): {
177 "Name": "trace-viewer",
178 "URL": "http://code.google.com/p/trace-viewer",
179 "License": "BSD",
180 "License File": "NOT_SHIPPED",
182 os.path.join('third_party', 'v8-i18n'): {
183 "Name": "Internationalization Library for v8",
184 "URL": "http://code.google.com/p/v8-i18n/",
185 "License": "Apache 2.0",
187 os.path.join('third_party', 'WebKit'): {
188 "Name": "WebKit",
189 "URL": "http://webkit.org/",
190 "License": "BSD and GPL v2",
191 # Absolute path here is resolved as relative to the source root.
192 "License File": "/webkit/LICENSE",
194 os.path.join('third_party', 'webpagereplay'): {
195 "Name": "webpagereplay",
196 "URL": "http://code.google.com/p/web-page-replay",
197 "License": "Apache 2.0",
198 "License File": "NOT_SHIPPED",
200 os.path.join('tools', 'grit'): {
201 "Name": "grit",
202 "URL": "http://code.google.com/p/grit-i18n",
203 "License": "BSD",
204 "License File": "NOT_SHIPPED",
206 os.path.join('tools', 'gyp'): {
207 "Name": "gyp",
208 "URL": "http://code.google.com/p/gyp",
209 "License": "BSD",
210 "License File": "NOT_SHIPPED",
212 os.path.join('v8'): {
213 "Name": "V8 JavaScript Engine",
214 "URL": "http://code.google.com/p/v8",
215 "License": "BSD",
217 os.path.join('v8', 'strongtalk'): {
218 "Name": "Strongtalk",
219 "URL": "http://www.strongtalk.org/",
220 "License": "BSD",
221 # Absolute path here is resolved as relative to the source root.
222 "License File": "/v8/LICENSE.strongtalk",
226 # Special value for 'License File' field used to indicate that the license file
227 # should not be used in about:credits.
228 NOT_SHIPPED = "NOT_SHIPPED"
231 class LicenseError(Exception):
232 """We raise this exception when a directory's licensing info isn't
233 fully filled out."""
234 pass
236 def AbsolutePath(path, filename, root):
237 """Convert a path in README.chromium to be absolute based on the source
238 root."""
239 if filename.startswith('/'):
240 # Absolute-looking paths are relative to the source root
241 # (which is the directory we're run from).
242 absolute_path = os.path.join(root, filename[1:])
243 else:
244 absolute_path = os.path.join(root, path, filename)
245 if os.path.exists(absolute_path):
246 return absolute_path
247 return None
249 def ParseDir(path, root, require_license_file=True):
250 """Examine a third_party/foo component and extract its metadata."""
252 # Parse metadata fields out of README.chromium.
253 # We examine "LICENSE" for the license file by default.
254 metadata = {
255 "License File": "LICENSE", # Relative path to license text.
256 "Name": None, # Short name (for header on about:credits).
257 "URL": None, # Project home page.
258 "License": None, # Software license.
261 # Relative path to a file containing some html we're required to place in
262 # about:credits.
263 optional_keys = ["Required Text", "License Android Compatible"]
265 if path in SPECIAL_CASES:
266 metadata.update(SPECIAL_CASES[path])
267 else:
268 # Try to find README.chromium.
269 readme_path = os.path.join(root, path, 'README.chromium')
270 if not os.path.exists(readme_path):
271 raise LicenseError("missing README.chromium or licenses.py "
272 "SPECIAL_CASES entry")
274 for line in open(readme_path):
275 line = line.strip()
276 if not line:
277 break
278 for key in metadata.keys() + optional_keys:
279 field = key + ": "
280 if line.startswith(field):
281 metadata[key] = line[len(field):]
283 # Check that all expected metadata is present.
284 for key, value in metadata.iteritems():
285 if not value:
286 raise LicenseError("couldn't find '" + key + "' line "
287 "in README.chromium or licences.py "
288 "SPECIAL_CASES")
290 # Special-case modules that aren't in the shipping product, so don't need
291 # their license in about:credits.
292 if metadata["License File"] != NOT_SHIPPED:
293 # Check that the license file exists.
294 for filename in (metadata["License File"], "COPYING"):
295 license_path = AbsolutePath(path, filename, root)
296 if license_path is not None:
297 break
299 if require_license_file and not license_path:
300 raise LicenseError("License file not found. "
301 "Either add a file named LICENSE, "
302 "import upstream's COPYING if available, "
303 "or add a 'License File:' line to "
304 "README.chromium with the appropriate path.")
305 metadata["License File"] = license_path
307 if "Required Text" in metadata:
308 required_path = AbsolutePath(path, metadata["Required Text"], root)
309 if required_path is not None:
310 metadata["Required Text"] = required_path
311 else:
312 raise LicenseError("Required text file listed but not found.")
314 return metadata
317 def ContainsFiles(path, root):
318 """Determines whether any files exist in a directory or in any of its
319 subdirectories."""
320 for _, dirs, files in os.walk(os.path.join(root, path)):
321 if files:
322 return True
323 for vcs_metadata in VCS_METADATA_DIRS:
324 if vcs_metadata in dirs:
325 dirs.remove(vcs_metadata)
326 return False
329 def FilterDirsWithFiles(dirs_list, root):
330 # If a directory contains no files, assume it's a DEPS directory for a
331 # project not used by our current configuration and skip it.
332 return [x for x in dirs_list if ContainsFiles(x, root)]
335 def FindThirdPartyDirs(prune_paths, root):
336 """Find all third_party directories underneath the source root."""
337 third_party_dirs = []
338 for path, dirs, files in os.walk(root):
339 path = path[len(root)+1:] # Pretty up the path.
341 if path in prune_paths:
342 dirs[:] = []
343 continue
345 # Prune out directories we want to skip.
346 # (Note that we loop over PRUNE_DIRS so we're not iterating over a
347 # list that we're simultaneously mutating.)
348 for skip in PRUNE_DIRS:
349 if skip in dirs:
350 dirs.remove(skip)
352 if os.path.basename(path) == 'third_party':
353 # Add all subdirectories that are not marked for skipping.
354 for dir in dirs:
355 dirpath = os.path.join(path, dir)
356 if dirpath not in prune_paths:
357 third_party_dirs.append(dirpath)
359 # Don't recurse into any subdirs from here.
360 dirs[:] = []
361 continue
363 # Don't recurse into paths in ADDITIONAL_PATHS, like we do with regular
364 # third_party/foo paths.
365 if path in ADDITIONAL_PATHS:
366 dirs[:] = []
368 for dir in ADDITIONAL_PATHS:
369 if dir not in prune_paths:
370 third_party_dirs.append(dir)
372 return third_party_dirs
375 def ScanThirdPartyDirs(root=None):
376 """Scan a list of directories and report on any problems we find."""
377 if root is None:
378 root = os.getcwd()
379 third_party_dirs = FindThirdPartyDirs(PRUNE_PATHS, root)
380 third_party_dirs = FilterDirsWithFiles(third_party_dirs, root)
382 errors = []
383 for path in sorted(third_party_dirs):
384 try:
385 metadata = ParseDir(path, root)
386 except LicenseError, e:
387 errors.append((path, e.args[0]))
388 continue
390 for path, error in sorted(errors):
391 print path + ": " + error
393 return len(errors) == 0
396 def GenerateCredits():
397 """Generate about:credits."""
399 if len(sys.argv) not in (2, 3):
400 print 'usage: licenses.py credits [output_file]'
401 return False
403 def EvaluateTemplate(template, env, escape=True):
404 """Expand a template with variables like {{foo}} using a
405 dictionary of expansions."""
406 for key, val in env.items():
407 if escape and not key.endswith("_unescaped"):
408 val = cgi.escape(val)
409 template = template.replace('{{%s}}' % key, val)
410 return template
412 root = os.path.join(os.path.dirname(__file__), '..')
413 third_party_dirs = FindThirdPartyDirs(PRUNE_PATHS, root)
415 entry_template = open(os.path.join(root, 'chrome', 'browser', 'resources',
416 'about_credits_entry.tmpl'), 'rb').read()
417 entries = []
418 for path in sorted(third_party_dirs):
419 try:
420 metadata = ParseDir(path, root)
421 except LicenseError:
422 # TODO(phajdan.jr): Convert to fatal error (http://crbug.com/39240).
423 continue
424 if metadata['License File'] == NOT_SHIPPED:
425 continue
426 env = {
427 'name': metadata['Name'],
428 'url': metadata['URL'],
429 'license': open(metadata['License File'], 'rb').read(),
430 'license_unescaped': '',
432 if 'Required Text' in metadata:
433 required_text = open(metadata['Required Text'], 'rb').read()
434 env["license_unescaped"] = required_text
435 entries.append(EvaluateTemplate(entry_template, env))
437 file_template = open(os.path.join(root, 'chrome', 'browser', 'resources',
438 'about_credits.tmpl'), 'rb').read()
439 template_contents = "<!-- Generated by licenses.py; do not edit. -->"
440 template_contents += EvaluateTemplate(file_template,
441 {'entries': '\n'.join(entries)},
442 escape=False)
444 if len(sys.argv) == 3:
445 with open(sys.argv[2], 'w') as output_file:
446 output_file.write(template_contents)
447 elif len(sys.argv) == 2:
448 print template_contents
450 return True
453 def main():
454 command = 'help'
455 if len(sys.argv) > 1:
456 command = sys.argv[1]
458 if command == 'scan':
459 if not ScanThirdPartyDirs():
460 return 1
461 elif command == 'credits':
462 if not GenerateCredits():
463 return 1
464 else:
465 print __doc__
466 return 1
469 if __name__ == '__main__':
470 sys.exit(main())