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. 5 6 """Build the NOTICE file distributed with the NaCl SDK from a set of given 7 license files.""" 8 9 import optparse 10 import os 11 import sys 12 13 14 def Trace(msg): 15 if Trace.verbose: 16 print msg 17 18 Trace.verbose = False 19 20 21 def FindFiles(files): 22 found = [f for f in files if os.path.exists(f)] 23 24 if Trace.verbose: 25 for f in sorted(set(files) - set(found)): 26 Trace('Skipping %s. File doesn\'t exist.\n' % (f,)) 27 28 return found 29 30 31 def CreateLicenseDict(files): 32 # Many of the license files are duplicates. Create a map of license text to 33 # filename. 34 license_dict = {} 35 for filename in files: 36 license_text = open(filename).read() 37 license_text = license_text.replace('\r\n', '\n') 38 license_dict.setdefault(license_text, []).append(filename) 39 40 # Flip the dictionary (map tuple of filenames -> license text). 41 return dict((tuple(value), key) for key, value in license_dict.iteritems()) 42 43 44 def WriteLicense(output_file, root, license_text, license_filenames): 45 Trace('Writing license for files:\n' + '\n'.join(license_filenames)) 46 output_file.write('=' * 70 + '\n') 47 for filename in sorted(license_filenames): 48 filename = os.path.relpath(filename, root) 49 license_dir = os.path.dirname(filename) 50 if not license_dir: 51 license_dir = 'native_client_sdk' 52 53 output_file.write('%s is licensed as follows\n' % (license_dir,)) 54 output_file.write(' (Cf. %s):\n' % (filename,)) 55 output_file.write('=' * 70 + '\n') 56 output_file.write(license_text) 57 58 59 def Generate(output_filename, root, files): 60 found_files = FindFiles(files) 61 license_dict = CreateLicenseDict(found_files) 62 with open(output_filename, 'w') as output_file: 63 for i, license_filenames in enumerate(sorted(license_dict.iterkeys())): 64 license_text = license_dict[license_filenames] 65 if i: 66 output_file.write('\n\n\n') 67 WriteLicense(output_file, root, license_text, license_filenames) 68 69 70 def main(args): 71 parser = optparse.OptionParser() 72 parser.add_option('-v', '--verbose', help='Verbose output.', 73 action='store_true') 74 parser.add_option('-o', '--output', help='Output file') 75 parser.add_option('--root', help='Root for all paths') 76 77 options, args = parser.parse_args(args) 78 Trace.verbose = options.verbose 79 80 if not options.output: 81 parser.error('No output file given. See -o.') 82 if not options.root: 83 parser.error('No root directory given. See --root.') 84 85 Generate(options.output, options.root, args) 86 Trace('Done.') 87 88 return 0 89 90 91 if __name__ == '__main__': 92 sys.exit(main(sys.argv[1:])) 93