pytorch
194 строки · 7.5 Кб
1#!/usr/bin/env python3
2import argparse
3import os
4
5
6mydir = os.path.dirname(__file__)
7licenses = {'LICENSE', 'LICENSE.txt', 'LICENSE.rst', 'COPYING.BSD'}
8
9
10def collect_license(current):
11collected = {}
12for root, dirs, files in os.walk(current):
13license = list(licenses & set(files))
14if license:
15name = root.split('/')[-1]
16license_file = os.path.join(root, license[0])
17try:
18ident = identify_license(license_file)
19except ValueError:
20raise ValueError('could not identify license file '
21f'for {root}') from None
22val = {
23'Name': name,
24'Files': [root],
25'License': ident,
26'License_file': [license_file],
27}
28if name in collected:
29# Only add it if the license is different
30if collected[name]['License'] == ident:
31collected[name]['Files'].append(root)
32collected[name]['License_file'].append(license_file)
33else:
34collected[name + f' ({root})'] = val
35else:
36collected[name] = val
37return collected
38
39
40def create_bundled(d, outstream, include_files=False):
41"""Write the information to an open outstream"""
42collected = collect_license(d)
43sorted_keys = sorted(collected.keys())
44outstream.write('The Pytorch repository and source distributions bundle '
45'several libraries that are \n')
46outstream.write('compatibly licensed. We list these here.')
47files_to_include = []
48for k in sorted_keys:
49c = collected[k]
50files = ',\n '.join(c['Files'])
51license_file = ',\n '.join(c['License_file'])
52outstream.write('\n\n')
53outstream.write(f"Name: {c['Name']}\n")
54outstream.write(f"License: {c['License']}\n")
55outstream.write(f"Files: {files}\n")
56outstream.write(' For details, see')
57if include_files:
58outstream.write(' the files concatenated below: ')
59files_to_include += c['License_file']
60else:
61outstream.write(': ')
62outstream.write(license_file)
63for fname in files_to_include:
64outstream.write('\n\n')
65outstream.write(fname)
66outstream.write('\n' + '-' * len(fname) + '\n')
67with open(fname, 'r') as fid:
68outstream.write(fid.read())
69
70
71def identify_license(f, exception=''):
72"""
73Read f and try to identify the license type
74This is __very__ rough and probably not legally binding, it is specific for
75this repo.
76"""
77def squeeze(t):
78"""Remove 'n and ' ', normalize quotes
79"""
80t = t.replace('\n', '').replace(' ', '')
81t = t.replace('``', '"').replace("''", '"')
82return t
83
84with open(f) as fid:
85txt = fid.read()
86if not exception and 'exception' in txt:
87license = identify_license(f, 'exception')
88return license + ' with exception'
89txt = squeeze(txt)
90if 'ApacheLicense' in txt:
91# Hmm, do we need to check the text?
92return 'Apache-2.0'
93elif 'MITLicense' in txt:
94# Hmm, do we need to check the text?
95return 'MIT'
96elif 'BSD-3-ClauseLicense' in txt:
97# Hmm, do we need to check the text?
98return 'BSD-3-Clause'
99elif 'BSD3-ClauseLicense' in txt:
100# Hmm, do we need to check the text?
101return 'BSD-3-Clause'
102elif 'BoostSoftwareLicense-Version1.0' in txt:
103# Hmm, do we need to check the text?
104return 'BSL-1.0'
105elif squeeze("Clarified Artistic License") in txt:
106return 'Clarified Artistic License'
107elif all([squeeze(m) in txt.lower() for m in bsd3_txt]):
108return 'BSD-3-Clause'
109elif all([squeeze(m) in txt.lower() for m in bsd3_v1_txt]):
110return 'BSD-3-Clause'
111elif all([squeeze(m) in txt.lower() for m in bsd2_txt]):
112return 'BSD-2-Clause'
113elif all([squeeze(m) in txt.lower() for m in bsd3_src_txt]):
114return 'BSD-Source-Code'
115elif any([squeeze(m) in txt.lower() for m in mit_txt]):
116return 'MIT'
117else:
118raise ValueError('unknown license')
119
120mit_txt = ['permission is hereby granted, free of charge, to any person ',
121'obtaining a copy of this software and associated documentation ',
122'files (the "software"), to deal in the software without ',
123'restriction, including without limitation the rights to use, copy, ',
124'modify, merge, publish, distribute, sublicense, and/or sell copies ',
125'of the software, and to permit persons to whom the software is ',
126'furnished to do so, subject to the following conditions:',
127
128'the above copyright notice and this permission notice shall be ',
129'included in all copies or substantial portions of the software.',
130
131'the software is provided "as is", without warranty of any kind, ',
132'express or implied, including but not limited to the warranties of ',
133'merchantability, fitness for a particular purpose and ',
134'noninfringement. in no event shall the authors or copyright holders ',
135'be liable for any claim, damages or other liability, whether in an ',
136'action of contract, tort or otherwise, arising from, out of or in ',
137'connection with the software or the use or other dealings in the ',
138'software.',
139]
140
141bsd3_txt = ['redistribution and use in source and binary forms, with or without '
142'modification, are permitted provided that the following conditions '
143'are met:',
144
145'redistributions of source code',
146
147'redistributions in binary form',
148
149'neither the name',
150
151'this software is provided by the copyright holders and '
152'contributors "as is" and any express or implied warranties, '
153'including, but not limited to, the implied warranties of '
154'merchantability and fitness for a particular purpose are disclaimed.',
155]
156
157# BSD2 is BSD3 without the "neither the name..." clause
158bsd2_txt = bsd3_txt[:3] + bsd3_txt[4:]
159
160# This BSD3 variant leaves "and contributors" out of the last clause of BSD-3,
161# which is still valid BSD-3
162v1 = bsd3_txt[4].replace('and contributors', '')
163bsd3_v1_txt = bsd3_txt[:3] + [v1]
164
165# This source variant of BSD-3 leaves the "redistributions in binary form" out
166# which is https://spdx.org/licenses/BSD-Source-Code.html
167bsd3_src_txt = bsd3_txt[:2] + bsd3_txt[4:]
168
169
170if __name__ == '__main__':
171third_party = os.path.relpath(mydir)
172parser = argparse.ArgumentParser(
173description="Generate bundled licenses file",
174)
175parser.add_argument(
176"--out-file",
177type=str,
178default=os.environ.get(
179"PYTORCH_THIRD_PARTY_BUNDLED_LICENSE_FILE",
180str(os.path.join(third_party, 'LICENSES_BUNDLED.txt'))
181),
182help="location to output new bundled licenses file",
183)
184parser.add_argument(
185"--include-files",
186action="store_true",
187default=False,
188help="include actual license terms to the output",
189)
190args = parser.parse_args()
191fname = args.out_file
192print(f"+ Writing bundled licenses to {args.out_file}")
193with open(fname, 'w') as fid:
194create_bundled(third_party, fid, args.include_files)
195