2 # Copyright 2014 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 """Checks third-party licenses for the purposes of the Android WebView build.
8 The Android tree includes a snapshot of Chromium in order to power the system
9 WebView. This tool checks that all code uses open-source licenses compatible
10 with Android, and that we meet the requirements of those licenses. It can also
11 be used to generate an Android NOTICE file for the third-party code.
13 It makes use of src/tools/licenses.py and the README.chromium files on which
14 it depends. It also makes use of a data file, third_party_files_whitelist.txt,
15 which whitelists indicidual files which contain third-party code but which
16 aren't in a third-party directory with a README.chromium file.
21 import multiprocessing
29 REPOSITORY_ROOT
= os
.path
.abspath(os
.path
.join(
30 os
.path
.dirname(__file__
), '..', '..'))
32 # Import third_party/PRESUBMIT.py via imp to avoid importing a random
33 # PRESUBMIT.py from $PATH, also make sure we don't generate a .pyc file.
34 sys
.dont_write_bytecode
= True
36 imp
.load_source('PRESUBMIT', \
37 os
.path
.join(REPOSITORY_ROOT
, 'third_party', 'PRESUBMIT.py'))
39 sys
.path
.append(os
.path
.join(REPOSITORY_ROOT
, 'third_party'))
41 sys
.path
.append(os
.path
.join(REPOSITORY_ROOT
, 'tools'))
44 import copyright_scanner
47 class InputApi(object):
49 self
.os_path
= os
.path
50 self
.os_walk
= os
.walk
52 self
.ReadFile
= _ReadFile
53 self
.change
= InputApiChange()
55 class InputApiChange(object):
57 self
.RepositoryRoot
= lambda: REPOSITORY_ROOT
60 def GetIncompatibleDirectories():
61 """Gets a list of third-party directories which use licenses incompatible
62 with Android. This is used by the snapshot tool.
64 A list of directories.
68 for directory
in _FindThirdPartyDirs():
69 if directory
in known_issues
.KNOWN_ISSUES
:
70 result
.append(directory
)
73 metadata
= licenses
.ParseDir(directory
, REPOSITORY_ROOT
,
74 require_license_file
=False,
75 optional_keys
=['License Android Compatible'])
76 except licenses
.LicenseError
as e
:
77 print 'Got LicenseError while scanning ' + directory
79 if metadata
.get('License Android Compatible', 'no').upper() == 'YES':
81 license
= re
.split(' [Ll]icenses?$', metadata
['License'])[0]
82 if not third_party
.LicenseIsCompatibleWithAndroid(InputApi(), license
):
83 result
.append(directory
)
86 def GetUnknownIncompatibleDirectories():
87 """Gets a list of third-party directories which use licenses incompatible
88 with Android which are not present in the known_issues.py file.
89 This is used by the AOSP bot.
91 A list of directories.
93 incompatible_directories
= frozenset(GetIncompatibleDirectories())
94 known_incompatible
= []
95 input_api
= InputApi()
96 for path
, exclude_list
in known_issues
.KNOWN_INCOMPATIBLE
.iteritems():
97 path
= copyright_scanner
.ForwardSlashesToOsPathSeps(input_api
, path
)
98 for exclude
in exclude_list
:
99 exclude
= copyright_scanner
.ForwardSlashesToOsPathSeps(input_api
, exclude
)
100 if glob
.has_magic(exclude
):
101 exclude_dirname
= os
.path
.dirname(exclude
)
102 if glob
.has_magic(exclude_dirname
):
103 print ('Exclude path %s contains an unexpected glob expression,' \
104 ' skipping.' % exclude
)
105 exclude
= exclude_dirname
106 known_incompatible
.append(os
.path
.normpath(os
.path
.join(path
, exclude
)))
107 known_incompatible
= frozenset(known_incompatible
)
108 return incompatible_directories
.difference(known_incompatible
)
111 class ScanResult(object):
112 Ok
, Warnings
, Errors
= range(3)
114 # Needs to be a top-level function for multiprocessing
115 def _FindCopyrightViolations(files_to_scan_as_string
):
116 return copyright_scanner
.FindCopyrightViolations(
117 InputApi(), REPOSITORY_ROOT
, files_to_scan_as_string
)
119 def _ShardList(l
, shard_len
):
120 return [l
[i
:i
+ shard_len
] for i
in range(0, len(l
), shard_len
)]
122 def _CheckLicenseHeaders(excluded_dirs_list
, whitelisted_files
):
123 """Checks that all files which are not in a listed third-party directory,
124 and which do not use the standard Chromium license, are whitelisted.
126 excluded_dirs_list: The list of directories to exclude from scanning.
127 whitelisted_files: The whitelist of files.
129 ScanResult.Ok if all files with non-standard license headers are whitelisted
130 and the whitelist contains no stale entries;
131 ScanResult.Warnings if there are stale entries;
132 ScanResult.Errors if new non-whitelisted entries found.
134 input_api
= InputApi()
135 files_to_scan
= copyright_scanner
.FindFiles(
136 input_api
, REPOSITORY_ROOT
, ['.'], excluded_dirs_list
)
137 sharded_files_to_scan
= _ShardList(files_to_scan
, 2000)
138 pool
= multiprocessing
.Pool()
139 offending_files_chunks
= pool
.map_async(
140 _FindCopyrightViolations
, sharded_files_to_scan
).get(999999)
143 # Flatten out the result
145 [item
for sublist
in offending_files_chunks
for item
in sublist
]
147 (unknown
, missing
, stale
) = copyright_scanner
.AnalyzeScanResults(
148 input_api
, whitelisted_files
, offending_files
)
151 print 'The following files contain a third-party license but are not in ' \
152 'a listed third-party directory and are not whitelisted. You must ' \
153 'add the following files to the whitelist.\n%s' % \
154 '\n'.join(sorted(unknown
))
156 print 'The following files are whitelisted, but do not exist.\n%s' % \
157 '\n'.join(sorted(missing
))
159 print 'The following files are whitelisted unnecessarily. You must ' \
160 'remove the following files from the whitelist.\n%s' % \
161 '\n'.join(sorted(stale
))
164 return ScanResult
.Errors
165 elif stale
or missing
:
166 return ScanResult
.Warnings
171 def _ReadFile(full_path
, mode
='rU'):
172 """Reads a file from disk. This emulates presubmit InputApi.ReadFile func.
174 full_path: The path of the file to read.
176 The contents of the file as a string.
179 with
open(full_path
, mode
) as f
:
183 def _ReadLocalFile(path
, mode
='rb'):
184 """Reads a file from disk.
186 path: The path of the file to read, relative to the root of the repository.
188 The contents of the file as a string.
191 return _ReadFile(os
.path
.join(REPOSITORY_ROOT
, path
), mode
)
194 def _FindThirdPartyDirs():
195 """Gets the list of third-party directories.
197 The list of third-party directories.
200 # Please don't add here paths that have problems with license files,
201 # as they will end up included in Android WebView snapshot.
202 # Instead, add them into known_issues.py.
204 # Temporary until we figure out how not to check out quickoffice on the
205 # Android license check bot. Tracked in crbug.com/350472.
206 os
.path
.join('chrome', 'browser', 'resources', 'chromeos', 'quickoffice'),
207 # Placeholder directory, no third-party code.
208 os
.path
.join('third_party', 'adobe'),
209 # Apache 2.0 license. See
210 # https://code.google.com/p/chromium/issues/detail?id=140478.
211 os
.path
.join('third_party', 'bidichecker'),
212 # Isn't checked out on clients
213 os
.path
.join('third_party', 'gles2_conform'),
214 # The llvm-build doesn't exist for non-clang builder
215 os
.path
.join('third_party', 'llvm-build'),
216 # Binaries doesn't apply to android
217 os
.path
.join('third_party', 'widevine'),
218 # third_party directories in this tree aren't actually third party, but
219 # provide a way to shadow experimental buildfiles into those directories.
220 os
.path
.join('build', 'secondary'),
221 # Not shipped, Chromium code
222 os
.path
.join('tools', 'swarming_client'),
224 third_party_dirs
= licenses
.FindThirdPartyDirs(prune_paths
, REPOSITORY_ROOT
)
225 return licenses
.FilterDirsWithFiles(third_party_dirs
, REPOSITORY_ROOT
)
229 """Checks that license meta-data is present for all third-party code and
230 that all non third-party code doesn't contain external copyrighted code.
232 ScanResult.Ok if everything is in order;
233 ScanResult.Warnings if there are non-fatal problems (e.g. stale whitelist
235 ScanResult.Errors otherwise.
238 third_party_dirs
= _FindThirdPartyDirs()
240 # First, check designated third-party directories using src/tools/licenses.py.
241 all_licenses_valid
= True
242 for path
in sorted(third_party_dirs
):
244 licenses
.ParseDir(path
, REPOSITORY_ROOT
)
245 except licenses
.LicenseError
, e
:
246 if not (path
in known_issues
.KNOWN_ISSUES
):
247 print 'Got LicenseError "%s" while scanning %s' % (e
, path
)
248 all_licenses_valid
= False
250 # Second, check for non-standard license text.
251 whitelisted_files
= copyright_scanner
.LoadWhitelistedFilesList(InputApi())
252 licenses_check
= _CheckLicenseHeaders(third_party_dirs
, whitelisted_files
)
254 return licenses_check
if all_licenses_valid
else ScanResult
.Errors
257 class TemplateEntryGenerator(object):
261 def _ReadFileGuessEncoding(self
, name
):
263 with
open(name
, 'rb') as input_file
:
264 contents
= input_file
.read()
266 return contents
.decode('utf8')
267 except UnicodeDecodeError:
269 # If it's not UTF-8, it must be CP-1252. Fail otherwise.
270 return contents
.decode('cp1252')
272 def MetadataToTemplateEntry(self
, metadata
):
275 'name': metadata
['Name'],
276 'url': metadata
['URL'],
277 'license': self
._ReadFileGuessEncoding
(metadata
['License File']),
278 'toc_href': 'entry' + str(self
.toc_index
),
282 def GenerateNoticeFile():
283 """Generates the contents of an Android NOTICE file for the third-party code.
284 This is used by the snapshot tool.
286 The contents of the NOTICE file.
289 generator
= TemplateEntryGenerator()
290 # Start from Chromium's LICENSE file
291 entries
= [generator
.MetadataToTemplateEntry({
292 'Name': 'The Chromium Project',
293 'URL': 'http://www.chromium.org',
294 'License File': os
.path
.join(REPOSITORY_ROOT
, 'LICENSE') })
297 third_party_dirs
= _FindThirdPartyDirs()
298 # We provide attribution for all third-party directories.
299 # TODO(mnaganov): Limit this to only code used by the WebView binary.
300 for directory
in sorted(third_party_dirs
):
301 metadata
= licenses
.ParseDir(directory
, REPOSITORY_ROOT
,
302 require_license_file
=False)
303 license_file
= metadata
['License File']
304 if license_file
and license_file
!= licenses
.NOT_SHIPPED
:
305 entries
.append(generator
.MetadataToTemplateEntry(metadata
))
307 env
= jinja2
.Environment(
308 loader
=jinja2
.FileSystemLoader(os
.path
.dirname(__file__
)),
309 extensions
=['jinja2.ext.autoescape'])
310 template
= env
.get_template('licenses_notice.tmpl')
311 return template
.render({ 'entries': entries
}).encode('utf8')
314 def _ProcessIncompatibleResult(incompatible_directories
):
315 if incompatible_directories
:
316 print ("Incompatibly licensed directories found:\n" +
317 "\n".join(sorted(incompatible_directories
)))
318 return ScanResult
.Errors
322 class FormatterWithNewLines(optparse
.IndentedHelpFormatter
):
323 def format_description(self
, description
):
324 paras
= description
.split('\n')
325 formatted_paras
= [textwrap
.fill(para
, self
.width
) for para
in paras
]
326 return '\n'.join(formatted_paras
) + '\n'
328 parser
= optparse
.OptionParser(formatter
=FormatterWithNewLines(),
329 usage
='%prog [options]')
330 parser
.description
= (__doc__
+
332 ' scan Check licenses.\n'
333 ' notice Generate Android NOTICE file on stdout.\n'
334 ' incompatible_directories Scan for incompatibly'
335 ' licensed directories.\n'
336 ' all_incompatible_directories Scan for incompatibly'
337 ' licensed directories (even those in'
338 ' known_issues.py).\n'
339 ' display_copyrights Display autorship on the files'
340 ' using names provided via stdin.\n')
341 (_
, args
) = parser
.parse_args()
344 return ScanResult
.Errors
346 if args
[0] == 'scan':
347 scan_result
= _Scan()
348 if scan_result
== ScanResult
.Ok
:
351 elif args
[0] == 'notice':
352 print GenerateNoticeFile()
354 elif args
[0] == 'incompatible_directories':
355 return _ProcessIncompatibleResult(GetUnknownIncompatibleDirectories())
356 elif args
[0] == 'all_incompatible_directories':
357 return _ProcessIncompatibleResult(GetIncompatibleDirectories())
358 elif args
[0] == 'display_copyrights':
359 files
= sys
.stdin
.read().splitlines()
361 zip(files
, copyright_scanner
.FindCopyrights(InputApi(), '.', files
)):
362 print f
, '\t', ' / '.join(sorted(c
))
365 return ScanResult
.Errors
367 if __name__
== '__main__':