55Basierend auf ThirdPartyLicenses
66"""
77
8+ import os
89import subprocess
910import sys
1011import json
1112from typing import List , Optional
1213from dataclasses import dataclass
14+ from pathlib import Path
1315
1416
1517@dataclass
1618class PackageLicense :
1719 """Lizenzinformationen eines Packages"""
1820 name : str
1921 version : str
20- license : str
22+ license : str = "Unknown"
2123 license_text : Optional [str ] = None
2224 url : Optional [str ] = None
2325 author : Optional [str ] = None
2426
27+ def __post_init__ (self ):
28+ if not self .license :
29+ self .license = "Unknown"
30+
2531
2632class LicenseGenerator :
2733 """
@@ -56,6 +62,24 @@ def get_licenses(self,
5662 """
5763 licenses = []
5864
65+ # Vorab-Parsing von requirements.txt falls angegeben
66+ req_names = None
67+ if requirements_file and os .path .exists (requirements_file ):
68+ req_names = set ()
69+ import re
70+ try :
71+ with open (requirements_file , 'r' , encoding = 'utf-8' ) as f :
72+ for line in f :
73+ line = line .strip ()
74+ if not line or line .startswith (('#' , '-' )):
75+ continue
76+ clean = line .split (';' )[0 ].strip ()
77+ pkg_match = re .split (r'[=><~@!\s\[]' , clean )[0 ].strip ()
78+ if pkg_match :
79+ req_names .add (pkg_match .lower ().replace ('_' , '-' ))
80+ except Exception :
81+ req_names = None
82+
5983 try :
6084 # pip-licenses verwenden wenn verfügbar
6185 if self ._pip_licenses_available :
@@ -64,67 +88,100 @@ def get_licenses(self,
6488 '--format=json' , '--with-license-file' , '--with-urls' ],
6589 capture_output = True ,
6690 text = True ,
67- encoding = 'utf-8'
91+ encoding = 'utf-8' ,
92+ errors = 'replace'
6893 )
6994
70- if result .returncode == 0 :
95+ if result .returncode == 0 and result . stdout :
7196 data = json .loads (result .stdout )
7297 for pkg in data :
98+ pkg_name = pkg .get ('Name' , '' )
99+ if req_names is not None and pkg_name .lower ().replace ('_' , '-' ) not in req_names :
100+ continue
101+ lic_val = pkg .get ('License' )
73102 licenses .append (PackageLicense (
74- name = pkg . get ( 'Name' , '' ) ,
103+ name = pkg_name ,
75104 version = pkg .get ('Version' , '' ),
76- license = pkg . get ( 'License' , 'Unknown' ) ,
105+ license = lic_val if lic_val else 'Unknown' ,
77106 license_text = pkg .get ('LicenseText' , None ),
78107 url = pkg .get ('URL' , None ),
79108 author = pkg .get ('Author' , None )
80109 ))
81110 else :
82- # Fallback: pip show
111+ # Fallback: pip list + batch pip show
83112 result = subprocess .run (
84113 [sys .executable , '-m' , 'pip' , 'list' , '--format=json' ],
85114 capture_output = True ,
86115 text = True ,
87- encoding = 'utf-8'
116+ encoding = 'utf-8' ,
117+ errors = 'replace'
88118 )
89119
90- if result .returncode == 0 :
120+ if result .returncode == 0 and result . stdout :
91121 packages = json .loads (result .stdout )
122+ filtered_packages = []
92123 for pkg in packages :
93124 name = pkg .get ('name' , '' )
94- version = pkg .get ('version' , '' )
95-
96- # Details holen
97- detail = subprocess .run (
98- [sys .executable , '-m' , 'pip' , 'show' , name ],
99- capture_output = True ,
100- text = True ,
101- encoding = 'utf-8'
102- )
103-
104- license_name = "Unknown"
105- author = None
106- url = None
107-
108- if detail .returncode == 0 :
109- for line in detail .stdout .split ('\n ' ):
110- if line .startswith ('License:' ):
111- license_name = line .split (':' , 1 )[1 ].strip ()
112- elif line .startswith ('Author:' ):
113- author = line .split (':' , 1 )[1 ].strip ()
114- elif line .startswith ('Home-page:' ):
115- url = line .split (':' , 1 )[1 ].strip ()
116-
125+ if req_names is not None and name .lower ().replace ('_' , '-' ) not in req_names :
126+ continue
127+ filtered_packages .append (pkg )
128+
129+ batch_size = 40
130+ names = [p .get ('name' , '' ) for p in filtered_packages if p .get ('name' )]
131+ details_by_name = {}
132+
133+ for i in range (0 , len (names ), batch_size ):
134+ chunk = names [i :i + batch_size ]
135+ try :
136+ detail = subprocess .run (
137+ [sys .executable , '-m' , 'pip' , 'show' ] + chunk ,
138+ capture_output = True ,
139+ text = True ,
140+ encoding = 'utf-8' ,
141+ errors = 'replace'
142+ )
143+ if detail .returncode == 0 and detail .stdout :
144+ current_pkg = {}
145+ for line in detail .stdout .splitlines ():
146+ if line .startswith ('---' ):
147+ if current_pkg .get ('name' ):
148+ details_by_name [current_pkg ['name' ].lower ().replace ('_' , '-' )] = current_pkg
149+ current_pkg = {}
150+ elif line .startswith ('Name:' ):
151+ current_pkg ['name' ] = line .split (':' , 1 )[1 ].strip ()
152+ elif line .startswith ('License:' ):
153+ current_pkg ['license' ] = line .split (':' , 1 )[1 ].strip ()
154+ elif line .startswith ('Author:' ):
155+ current_pkg ['author' ] = line .split (':' , 1 )[1 ].strip ()
156+ elif line .startswith ('Home-page:' ):
157+ current_pkg ['url' ] = line .split (':' , 1 )[1 ].strip ()
158+ if current_pkg .get ('name' ):
159+ details_by_name [current_pkg ['name' ].lower ().replace ('_' , '-' )] = current_pkg
160+ except Exception :
161+ pass
162+
163+ for pkg in filtered_packages :
164+ raw_name = pkg .get ('name' , '' )
165+ norm_key = raw_name .lower ().replace ('_' , '-' )
166+ info = details_by_name .get (norm_key , {})
117167 licenses .append (PackageLicense (
118- name = name ,
119- version = version ,
120- license = license_name ,
121- author = author ,
122- url = url
168+ name = raw_name ,
169+ version = pkg . get ( ' version' , '' ) ,
170+ license = info . get ( 'license' ) or 'Unknown' ,
171+ author = info . get ( ' author' ) ,
172+ url = info . get ( ' url' )
123173 ))
124174
125175 except Exception as e :
126176 print (f"Fehler beim Sammeln der Lizenzen: { e } " )
127177
178+ # Finale Filterung falls req_names angegeben
179+ if req_names is not None :
180+ licenses = [
181+ lic for lic in licenses
182+ if lic .name .lower ().replace ('_' , '-' ) in req_names
183+ ]
184+
128185 return licenses
129186
130187 def generate_notice_file (self ,
@@ -148,6 +205,10 @@ def generate_notice_file(self,
148205 return False
149206
150207 try :
208+ parent_dir = Path (output_path ).parent
209+ if str (parent_dir ) and str (parent_dir ) != '.' :
210+ parent_dir .mkdir (parents = True , exist_ok = True )
211+
151212 lines = [
152213 "THIRD-PARTY SOFTWARE NOTICES AND INFORMATION" ,
153214 "" ,
@@ -190,6 +251,10 @@ def generate_json(self, output_path: str) -> bool:
190251 licenses = self .get_licenses ()
191252
192253 try :
254+ parent_dir = Path (output_path ).parent
255+ if str (parent_dir ) and str (parent_dir ) != '.' :
256+ parent_dir .mkdir (parents = True , exist_ok = True )
257+
193258 data = []
194259 for lic in licenses :
195260 data .append ({
@@ -238,13 +303,14 @@ def check_license_compatibility(self,
238303
239304 for lic in licenses :
240305 license_ok = False
306+ lic_str = lic .license if lic .license else 'Unknown'
241307 for allowed in allowed_licenses :
242- if allowed .lower () in lic . license .lower ():
308+ if allowed .lower () in lic_str .lower ():
243309 license_ok = True
244310 break
245311
246- if not license_ok and lic . license != 'Unknown' :
247- problematic .append (f"{ lic .name } : { lic . license } " )
312+ if not license_ok and lic_str != 'Unknown' :
313+ problematic .append (f"{ lic .name } : { lic_str } " )
248314
249315 return problematic
250316
0 commit comments