Merge "collectd: add config file templates as package_data"
[yardstick.git] / tests / ci / pip_license.py
1 # Copyright (c) 2017 Intel Corporation
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import pkg_resources
16 import pip.req
17 import sys
18
19
20 def get_pkg_license(pkg):
21     """
22     Given a package reference (as from requirements.txt),
23     return license listed in package metadata.
24     NOTE: This function does no error checking and is for
25     demonstration purposes only.
26
27     can-pip-or-setuptools-distribute-etc-list-the-license-used-by-each-install
28     https://stackoverflow.com/a/19086260
29     https://stackoverflow.com/users/308066/dkamins
30     """
31     try:
32         pkgs = pkg_resources.working_set.resolve(pkg, replace_conflicting=True)
33         # pkgs = pkg_resources.require(pkg)
34     except pkg_resources.DistributionNotFound as e:
35         sys.stderr.write("%s\n" % e)
36         return None
37     pkg = pkgs[0]
38     try:
39         info = pkg.get_metadata_lines('METADATA')
40     except IOError:
41         try:
42             info = pkg.get_metadata_lines('PKG-INFO')
43         except IOError:
44             info = []
45     licenses = []
46     for line in info:
47         if "License:" in line:
48             lic = line.split(': ', 1)[1]
49             if "UNKNOWN" not in lic:
50                 # try this type first
51                 licenses.append(lic)
52                 # break
53         elif "License ::" in line:
54             licenses.append(" ".join(line.split(':: ')[1:3]))
55     return "; ".join(licenses)
56
57 # quick and dirty hack
58
59
60 def main():
61
62     reqs = list(pip.req.parse_requirements("../../requirements.txt", session='hack'))
63     lines = []
64     for req in reqs:
65         pkg = pkg_resources.parse_requirements([req.name])
66         lic = get_pkg_license(pkg)
67         markers = req.markers
68         if markers:
69             mark = "; " + str(req.markers)
70         else:
71             mark = ""
72         line = "{0}{1}\t\t# {2}\n".format(req.req, mark, lic)
73         sys.stdout.write(line)
74         lines.append(line)
75     with open("requirements.txt", "w") as rrr:
76         rrr.writelines(lines)
77
78
79 if __name__ == '__main__':
80     main()