@@ -14,8 +14,8 @@ class License:
1414
1515 name : str # SPDX Full name
1616 spdx_id : str # SPDX Identifier
17- trove_classifier : Optional [str ]
18- probability : float
17+ trove_classifier : Optional [str ] # Python package classifier
18+ probability : float # Confidence level of the license inference
1919
2020 @staticmethod
2121 def from_inferred (
@@ -33,14 +33,30 @@ def from_inferred(
3333def guess_license_in_file (
3434 filename : Union [str , PathLike [str ]],
3535) -> Optional [License ]:
36- """Guess license from file."""
37- try :
38- with open (filename , encoding = "utf-8" ) as f :
39- license_text = f .read ()
40- except UnicodeDecodeError :
41- with open (filename , encoding = "latin-1" ) as f :
42- license_text = f .read ()
36+ """Attempt to identify the license of a given file.
4337
44- probable_license = infer_license .api .probabilities (license_text )
38+ Args:
39+ filename (Union[str, os.PathLike[str]]): Path to the file to analyze
4540
46- return None if not probable_license else License .from_inferred (* probable_license [0 ])
41+ Returns:
42+ Optional[License]: The most probable license if found, None if no license could be detected
43+ """
44+ try :
45+ with open (filename , "rb" ) as f :
46+ file_bytes = f .read ()
47+ try :
48+ license_text = file_bytes .decode ("utf-8" )
49+ except UnicodeDecodeError :
50+ license_text = file_bytes .decode ("latin-1" )
51+ except (FileNotFoundError , PermissionError , IsADirectoryError ):
52+ # Return None for file access issues
53+ return None
54+ except OSError :
55+ # Handle other OS-level file errors
56+ return None
57+
58+ probable_licenses = infer_license .api .probabilities (license_text )
59+
60+ return (
61+ None if not probable_licenses else License .from_inferred (* probable_licenses [0 ])
62+ )
0 commit comments