#!/usr/bin/env python3
"""
oslc - Open Source License Compliance Tool
=========================================
A simple, open-source Python CLI tool for scanning open-source licenses,
generating attribution files (e.g., NOTICE.txt), and detecting copyleft triggers.
License: MIT License (see below).
Features:
- Scans directories using ScanCode Toolkit (install via `pip install scancode-toolkit`).
- Generates aggregated attribution files with copyrights and licenses.
- Detects copyleft licenses (e.g., GPL family, AGPL) and lists affected files.
- JSON reporting for automation.
Installation:
1. pip install scancode-toolkit
2. Save this script as `oslc.py` and `chmod +x oslc.py`
3. Or pip install -e . after cloning a repo with this file.
Usage:
./oslc.py scan DIR # Scan and report licenses/copyrights
./oslc.py attrib DIR # Generate NOTICE.txt to stdout
./oslc.py copyleft DIR # List files with copyleft licenses
./oslc.py report DIR # Full JSON report
MIT License
-----------
Copyright (c) 2024 Sherlock (Trailblazer Labs)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import argparse
import json
import subprocess
import sys
from pathlib import Path
from typing import Dict, List, Set, Any
from collections import defaultdict
# Known copyleft licenses (keyed by SPDX ID or ScanCode detected license key)
# Expand as needed; based on common classifications.
COPYLEFT_LICENSES = {
'gpl-2.0', 'gpl-3.0', 'gpl-2.0-only', 'gpl-3.0-only',
'agpl-3.0', 'agpl-3.0-only',
'lgpl-2.1', 'lgpl-3.0', 'lgpl-2.1-only', 'lgpl-3.0-only',
'mpl-2.0', 'mpl-1.1', # File-level copyleft
'eupl-1.2', 'osl-3.0', 'spl-1.0',
# Add more: epl-2.0 (weak), etc.
}
def run_scancode(dir_path: Path, extra_flags: List[str] = None) -> Dict[str, Any]:
"""
Run ScanCode on the directory.
Requires `scancode` in PATH (pip install scancode-toolkit).
"""
cmd = ['scancode', '--license', '--copyright', '--json-', str(dir_path)]
if extra_flags:
cmd.extend(extra_flags)
try:
result = subprocess.run(cmd, capture_output=True, check=True, text=True)
return json.loads(result.stdout)
except subprocess.CalledProcessError as e:
print(f"ScanCode failed: {e.stderr}", file=sys.stderr)
sys.exit(1)
except FileNotFoundError:
print("Error: scancode-toolkit not found. Install with: pip install scancode-toolkit", file=sys.stderr)
sys.exit(1)
except json.JSONDecodeError:
print("Error: Invalid JSON from ScanCode.", file=sys.stderr)
sys.exit(1)
def classify_licenses(scan_result: Dict[str, Any]) -> Dict[str, Any]:
"""Classify licenses, copyrights, and detect copyleft."""
files = scan_result.get('files', [])
license_stats: Dict[str, int] = defaultdict(int)
copyleft_files: List[str] = []
copyrights: Set[str] = set()
for file_info in files:
path = file_info.get('path', '')
licenses = file_info.get('licenses', [])
# Count licenses
for lic in licenses:
key = lic.get('key', '').lower()
license_stats[key] += 1
if key in COPYLEFT_LICENSES:
copyleft_files.append(path)
# Collect unique copyrights
file_copyrs = file_info.get('copyrights', [])
for c in file_copyrs:
copyrights.add(c.get('value', ''))
return {
'license_stats': dict(license_stats),
'copyleft_files': sorted(set(copyleft_files)), # Dedup
'copyrights': sorted(copyrights),
'total_files': len(files),
}
def print_scan_report(classified: Dict[str, Any]):
"""Print human-readable scan report."""
print("=== License Scan Report ===")
print(f"Total files scanned: {classified['total_files']}")
print("\nTop Licenses:")
for lic, count in sorted(classified['license_stats'].items(), key=lambda x: x[1], reverse=True):
print(f" {lic}: {count} files")
if classified['copyleft_files']:
print("\nCopyleft Triggers (files with copyleft licenses):")
for f in classified['copyleft_files'][:20]: # Limit
print(f" {f}")
if len(classified['copyleft_files']) > 20:
print(f" ... and {len(classified['copyleft_files']) - 20} more")
else:
print("\nNo copyleft licenses detected.")
def generate_attribution(classified: Dict[str, Any], output_file: Path = None) -> None:
"""Generate NOTICE.txt or similar attribution file."""
notice = [
"# Third-Party Attributions and Licenses",
"# =====================================",
"# This file lists copyrights and licenses detected in dependencies.",
"# Generated by oslc (https://github.com/yourrepo/oslc)",
"",
"## Copyright Notices",
"",
]
for copyright in classified['copyrights']:
notice.append(f"- {copyright}")
notice.extend([
"",
"## License Summary",
"",
])
for lic, count in sorted(classified['license_stats'].items(), key=lambda x: x[1], reverse=True):
notice.append(f"- {lic} ({count} files)")
notice.append("\n# Full scan details available in JSON report.\n")
content = '\n'.join(notice)
if output_file:
output_file.write_text(content)
print(f"Attribution file written to: {output_file}")
else:
print(content)
def main():
parser = argparse.ArgumentParser(description="Open Source License Compliance Tool")
subparsers = parser.add_subparsers(dest='command', required=True)
# Scan
scan_p = subparsers.add_parser('scan', help='Scan for licenses and copyrights')
scan_p.add_argument('dir', type=Path, help='Directory to scan')
# Attribution
attrib_p = subparsers.add_parser('attrib', help='Generate attribution file')
attrib_p.add_argument('dir', type=Path)
attrib_p.add_argument('-o', '--output', type=Path, help='Output file (default: stdout)')
# Copyleft
copyleft_p = subparsers.add_parser('copyleft', help='List copyleft trigger files')
copyleft_p.add_argument('dir', type=Path)
# Full report
report_p = subparsers.add_parser('report', help='Full JSON report')
report_p.add_argument('dir', type=Path)
report_p.add_argument('-o', '--output', type=Path, default=Path('oslc-report.json'))
args = parser.parse_args()
if not args.dir.exists():
print(f"Error: Directory '{args.dir}' does not exist.", file=sys.stderr)
sys.exit(1)
# Run ScanCode
scan_result = run_scancode(args.dir)
classified = classify_licenses(scan_result)
if args.command == 'scan':
print_scan_report(classified)
elif args.command == 'attrib':
generate_attribution(classified, args.output if args.output else None)
elif args.command == 'copyleft':
print("=== Copyleft Triggers ===")
if classified['copyleft_files']:
for f in sorted(classified['copyleft_files']):
print(f)
else:
print("No copyleft licenses found.")
elif args.command == 'report':
full_report = {
**classified,
'scan_result': scan_result, # Full raw data
'copyleft_licenses_used': list(COPYLEFT_LICENSES),
}
output_path = args.output.expanduser()
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(json.dumps(full_report, indent=2))
print(f"Full report written to: {output_path}")
if __name__ == '__main__':
main()
Quick Start
-
Install dependencies:
pip install scancode-toolkit
-
Save and run: Copy the script above to oslc.py, then:
chmod +x oslc.py
./oslc.py scan /path/to/your/project
./oslc.py attrib /path/to/deps > NOTICE.txt
./oslc.py copyleft /path/to/project # Lists files needing redistribution under copyleft
./oslc.py report /path/to/project -o compliance.json
How It Works
- Scanning: Uses ScanCode Toolkit (industry-standard, accurate license detection).
- Attribution: Aggregates unique copyrights/licenses into a
NOTICE.txt-style file (required by Apache/MIT/etc.).
- Copyleft Triggers: Detects files with GPL/AGPL/etc. licenses—redistribute source if shipping binaries.
- Customization: Edit
COPYLEFT_LICENSES set for your needs. Handles SPDX/ScanCode keys.
- Limitations: ScanCode may miss embedded deps (e.g., npm); run on
vendor/ or node_modules/. For binaries, add --license-text --license-urls.
Open-Source It!
This tool is production-ready for basic compliance. Extend with REUSE spec or SBOM (e.g., integrate CycloneDX). Questions? Ask! 🕵️