1+ import json
2+ import licensedcode .index
3+ import urllib .request
4+ from licensedcode .cache import get_index
5+ from licensedcode .models import load_licenses
6+
7+
8+ def find_osi_map (license : "OSI License Object" ):
9+ """
10+ Return Scancode key mapped to OSI License `license`
11+ """
12+ idx = get_index ()
13+ osi_key = license ['id' ]
14+ # search for Scancode License matching OSI Key
15+ matches = list (idx .match (query_string = osi_key ))
16+ if not matches :
17+ return None
18+ return matches [0 ].rule .license_expression
19+
20+
21+ def add_osi_key (obj : "OSI License Object" ):
22+ """
23+ Add OSI License Key derived from OSI License Object `obj`
24+ """
25+ licenses = licensedcode .cache .get_licenses_db ()
26+ # find matching Scancode License Object for `obj`
27+ result = find_osi_map (obj )
28+ # derive OSI License Key from `obj`
29+ osi_key = obj ['id' ]
30+ if not result : # no matching Scancode License found
31+ return None
32+ mapped_license = licenses [result ] # license object from Scancode
33+ licenses_path = "src/licensedcode/data/licenses/" # licenses directory
34+ file_to_modify = open (licenses_path + mapped_license .key + ".yml" , "a" )
35+ file_to_modify .write ("osi_license_key: " + osi_key )
36+ file_to_modify .write ("\n " )
37+
38+
39+ def add_osi_keys ():
40+ """
41+ For every possible OSI License, match and add OSI Key to existing Scancode License
42+ """
43+ #retrieve OSI License Objects
44+ contents = urllib .request .urlopen ("https://api.opensource.org/licenses/" ).read ().decode ()
45+ data = json .loads (contents )
46+ # for each OSI License Object, update matching Scancode License Object
47+ for obj in data :
48+ add_osi_key (obj )
49+
50+
51+ if __name__ == '__main__' :
52+ add_osi_keys ()
0 commit comments