@ -9,17 +9,21 @@ from __future__ import annotations
import argparse
import argparse
from collections import Counter , defaultdict
from collections import Counter , defaultdict
from concurrent . futures import ThreadPoolExecutor
from contextlib import contextmanager
from contextlib import contextmanager
from copy import deepcopy
from copy import deepcopy
from dataclasses import dataclass
from dataclasses import dataclass
import hashlib
import hashlib
import io
import json
import json
import os
import os
from pathlib import Path , PurePosixPath
from pathlib import Path , PurePosixPath
import re
import re
import sqlite3
import subprocess
import subprocess
import sys
import sys
import tempfile
import tempfile
import threading
import uuid
import uuid
import xml . etree . ElementTree as ET
import xml . etree . ElementTree as ET
@ -45,6 +49,7 @@ RELICENSING_COMMIT = "31936b09d24871e421f212502a8342f9d8aabb20"
CE_REMOTE = " https://github.com/thingsboard/thingsboard.git "
CE_REMOTE = " https://github.com/thingsboard/thingsboard.git "
CURATIONS = " tools/src/main/python/license-headers/curations.json "
CURATIONS = " tools/src/main/python/license-headers/curations.json "
README = " tools/src/main/python/license-headers/README.md "
README = " tools/src/main/python/license-headers/README.md "
CHECKER_PATHS = ( " tools/src/main/python/license-headers/ " , " check-license-headers.sh " )
CURATION_FIELDS = { " path " , " contentHash " , " header " , " reason " }
CURATION_FIELDS = { " path " , " contentHash " , " header " , " reason " }
CONTENT_HASH = re . compile ( r " sha256:[0-9a-f] {64} " )
CONTENT_HASH = re . compile ( r " sha256:[0-9a-f] {64} " )
UNRECOGNIZED = " unrecognized "
UNRECOGNIZED = " unrecognized "
@ -65,6 +70,14 @@ RESTAMP_LISTING = 40
REPEATED_HEADERS = 3
REPEATED_HEADERS = 3
HEADER_WINDOW = 4096
HEADER_WINDOW = 4096
XML_SPACE = " { http://www.w3.org/XML/1998/namespace}space "
XML_SPACE = " { http://www.w3.org/XML/1998/namespace}space "
JOBS_VARIABLE = " LICENSE_HEADERS_JOBS "
CACHE_SIGNATURES_VARIABLE = " LICENSE_HEADERS_CACHE_SIGNATURES "
CACHE_DIRECTORY = " target/license-headers-cache "
CACHE_FORMAT = " 1 "
CACHE_SIGNATURES_KEPT = 3
CACHE_FILE = re . compile ( r " [0-9a-f] {32} \ .sqlite " )
# Git's minimum similarity for a copy, in percent: the -C threshold and the size filter in front of it.
COPY_SIMILARITY = 50
@dataclass ( frozen = True )
@dataclass ( frozen = True )
@ -132,6 +145,30 @@ class Console:
console = Console ( )
console = Console ( )
def positive_setting ( variable , default ) :
configured = os . environ . get ( variable , " " )
if not configured :
return default
if not configured . isdigit ( ) or int ( configured ) < 1 :
raise Failure ( f " { variable } must be a positive number, not { configured !r} " )
return int ( configured )
def jobs ( ) :
""" Parallel subprocesses: LICENSE_HEADERS_JOBS when set, otherwise all CPUs but one to keep the machine responsive. """
return positive_setting ( JOBS_VARIABLE , max ( 1 , ( os . cpu_count ( ) or 1 ) - 1 ) )
def parallel ( function , items ) :
""" Results of function for every item in item order; the first failure propagates. """
items = list ( items )
workers = min ( len ( items ) , jobs ( ) )
if workers < = 1 :
return [ function ( item ) for item in items ]
with ThreadPoolExecutor ( max_workers = workers ) as pool :
return list ( pool . map ( function , items ) )
def run ( argv , cwd , * , data = None , ok = ( 0 , ) ) :
def run ( argv , cwd , * , data = None , ok = ( 0 , ) ) :
result = subprocess . run ( argv , cwd = cwd , input = data , stdout = subprocess . PIPE , stderr = subprocess . PIPE )
result = subprocess . run ( argv , cwd = cwd , input = data , stdout = subprocess . PIPE , stderr = subprocess . PIPE )
if result . returncode not in ok :
if result . returncode not in ok :
@ -238,9 +275,12 @@ class Change:
status : str
status : str
def history ( repo , revision , * options ) :
def history ( repo , revisions , * options ) :
""" First-parent changes of every revision in one walk: commits shared by several revisions appear once. """
if not revisions or any ( revision . startswith ( " - " ) for revision in revisions ) :
raise Failure ( " history needs revisions that do not start with ' - ' " )
raw = git ( repo , " log " , " --first-parent " , " --diff-merges=first-parent " , " --root " , " --raw " , " --no-abbrev " ,
raw = git ( repo , " log " , " --first-parent " , " --diff-merges=first-parent " , " --root " , " --raw " , " --no-abbrev " ,
" --no-renames " , " -z " , " --format= %x 1e % H " , * options , revision , " -- " )
" --no-renames " , " -z " , " --format= %x 1e % H " , * options , * revisions , " -- " )
return list ( parse_history ( raw ) )
return list ( parse_history ( raw ) )
@ -400,8 +440,8 @@ def validate_curation(entry):
return name
return name
def xml_plain ( path ) :
def xml_plain ( source ) :
root = ET . parse ( path ) . getroot ( )
root = ET . parse ( source ) . getroot ( )
for element in root . iter ( ) :
for element in root . iter ( ) :
element . tag = element . tag . rsplit ( " } " , 1 ) [ - 1 ]
element . tag = element . tag . rsplit ( " } " , 1 ) [ - 1 ]
return root
return root
@ -418,7 +458,15 @@ class Plugin:
def read_plugin ( repo ) :
def read_plugin ( repo ) :
plugins = xml_plain ( repo / " pom.xml " ) . findall ( " ./build/pluginManagement/plugins/plugin " )
return parse_plugin ( xml_plain ( repo / " pom.xml " ) )
def plugin_signature ( plugin ) :
return plugin . version , ET . tostring ( plugin . configuration )
def parse_plugin ( project ) :
plugins = project . findall ( " ./build/pluginManagement/plugins/plugin " )
plugin = next ( ( p for p in plugins if p . findtext ( " artifactId " ) == " license-maven-plugin " ) , None )
plugin = next ( ( p for p in plugins if p . findtext ( " artifactId " ) == " license-maven-plugin " ) , None )
if plugin is None :
if plugin is None :
raise Failure ( " Root pom.xml does not manage the Mycila license plugin " )
raise Failure ( " Root pom.xml does not manage the Mycila license plugin " )
@ -451,8 +499,8 @@ class Scope:
def discover_scope ( repo , plugin ) :
def discover_scope ( repo , plugin ) :
states = defaultdict ( set )
states = defaultdict ( set )
modules = [ ]
modules = [ ]
for entry in SCOPE_POMS :
for reports in parallel ( lambda entry : scope_check ( repo , plugin , entry ) , SCOPE_POMS ) :
for report in scope_check ( repo , plugin , entry ) :
for report in reports :
module = report . parent . parent
module = report . parent . parent
modules . append ( { " path " : str ( module . relative_to ( repo ) ) , " report " : str ( report . relative_to ( repo ) ) } )
modules . append ( { " path " : str ( module . relative_to ( repo ) ) , " report " : str ( report . relative_to ( repo ) ) } )
for name , result in read_scope_report ( repo , module , report ) :
for name , result in read_scope_report ( repo , module , report ) :
@ -516,7 +564,6 @@ class Mycila:
def __init__ ( self , repo , directory , plugin ) :
def __init__ ( self , repo , directory , plugin ) :
self . root = directory
self . root = directory
self . plugin = plugin
self . plugin = plugin
self . report = directory / " report.json "
self . paths = { }
self . paths = { }
self . contents = { }
self . contents = { }
self . removed = { }
self . removed = { }
@ -527,9 +574,10 @@ class Mycila:
( directory / name ) . parent . mkdir ( parents = True , exist_ok = True )
( directory / name ) . parent . mkdir ( parents = True , exist_ok = True )
( directory / name ) . write_bytes ( self . templates [ header ] )
( directory / name ) . write_bytes ( self . templates [ header ] )
def add ( self , key , name , content ) :
def add ( self , key , name , content , slot = None ) :
group = " head " if key [ 0 ] == " head " else " ce "
group = " head " if key [ 0 ] == " head " else " ce "
path = self . root / " files " / group / str ( len ( self . paths ) ) / PurePosixPath ( name ) . name
slot = len ( self . paths ) if slot is None else slot
path = self . root / " files " / group / str ( slot ) / PurePosixPath ( name ) . name
path . parent . mkdir ( parents = True )
path . parent . mkdir ( parents = True )
path . write_bytes ( content )
path . write_bytes ( content )
self . paths [ key ] = path . relative_to ( self . root ) . as_posix ( )
self . paths [ key ] = path . relative_to ( self . root ) . as_posix ( )
@ -548,8 +596,9 @@ class Mycila:
def current_headers ( self , keys ) :
def current_headers ( self , keys ) :
keys = list ( keys )
keys = list ( keys )
recognized = defaultdict ( list )
recognized = defaultdict ( list )
for header in TEMPLATES :
checks = parallel ( lambda header : self . invoke ( " check " , header , keys ) , TEMPLATES )
for key , result in self . invoke ( " check " , header , keys ) . items ( ) :
for header , results in zip ( TEMPLATES , checks ) :
for key , result in results . items ( ) :
if result == " PRESENT " :
if result == " PRESENT " :
recognized [ key ] . append ( header )
recognized [ key ] . append ( header )
return { key : recognized [ key ] [ 0 ] if len ( recognized [ key ] ) == 1 else UNRECOGNIZED for key in keys }
return { key : recognized [ key ] [ 0 ] if len ( recognized [ key ] ) == 1 else UNRECOGNIZED for key in keys }
@ -631,43 +680,46 @@ class Mycila:
rejected [ key ] = " more than one header, review by hand "
rejected [ key ] = " more than one header, review by hand "
accepted = [ key for key in keys if key not in rejected ]
accepted = [ key for key in keys if key not in rejected ]
with self . guarded ( accepted ) :
with self . guarded ( accepted ) :
for header in TEMPLATES :
groups = { header : [ key for key in accepted if expected [ key ] == header ] for header in TEMPLATES }
group = [ key for key in accepted if expected [ key ] == header ]
parallel ( lambda header : self . invoke ( " format " , header , groups [ header ] ) , TEMPLATES )
if group :
self . invoke ( " format " , header , group )
return { key : self . contents [ key ] for key in accepted } , rejected
return { key : self . contents [ key ] for key in accepted } , rejected
def invoke ( self , goal , header , keys , * , styles = ( ) ) :
def invoke ( self , goal , header , keys , * , styles = ( ) ) :
keys = list ( keys )
keys = list ( keys )
if not keys :
if not keys :
return { }
return { }
self . write_pom ( header , keys , styles )
invocation = uuid . uuid4 ( ) . hex
self . report . unlink ( missing_ok = True )
pom , report = self . root / f " pom- { invocation } .xml " , self . root / f " report- { invocation } .json "
self . write_pom ( pom , report , header , keys , styles )
try :
try :
maven ( self . root , [ self . plugin . coordinates + " : " + goal ] )
maven ( self . root , [ " -f " , pom . name , self . plugin . coordinates + " : " + goal ] )
results = self . read_results ( report )
except Failure as exc :
except Failure as exc :
unknown = self . unknown_inputs ( keys )
unknown = self . unknown_inputs ( report , keys )
if unknown :
if unknown :
raise Failure ( f " Mycila cannot normalize these inputs: { unknown [ : 20 ] } " ) from exc
raise Failure ( f " Mycila cannot normalize these inputs: { unknown [ : 20 ] } " ) from exc
raise
raise
results = self . read_results ( )
finally :
pom . unlink ( missing_ok = True )
report . unlink ( missing_ok = True )
if set ( results ) != { self . paths [ key ] for key in keys } or " UNKNOWN " in results . values ( ) :
if set ( results ) != { self . paths [ key ] for key in keys } or " UNKNOWN " in results . values ( ) :
raise Failure ( " Mycila comparison scope was incomplete or unknown " )
raise Failure ( " Mycila comparison scope was incomplete or unknown " )
return { key : results [ self . paths [ key ] ] for key in keys }
return { key : results [ self . paths [ key ] ] for key in keys }
def read_results ( self ) :
@staticmethod
if not self . report . exists ( ) :
def read_results ( report ) :
if not report . exists ( ) :
raise Failure ( " Mycila did not produce its comparison report " )
raise Failure ( " Mycila did not produce its comparison report " )
return { item [ " path " ] : item [ " result " ] for item in json . loads ( self . report . read_text ( ) ) [ " files " ] }
return { item [ " path " ] : item [ " result " ] for item in json . loads ( report . read_text ( ) ) [ " files " ] }
def unknown_inputs ( self , keys ) :
def unknown_inputs ( self , report , keys ) :
try :
try :
results = self . read_results ( )
results = self . read_results ( report )
except Failure :
except Failure :
return [ ]
return [ ]
return [ str ( key ) for key in keys if results . get ( self . paths [ key ] ) == " UNKNOWN " ]
return [ str ( key ) for key in keys if results . get ( self . paths [ key ] ) == " UNKNOWN " ]
def write_pom ( self , header , keys , styles ) :
def write_pom ( self , pom , report , header , keys , styles ) :
project = ET . Element ( " project " , xmlns = " http://maven.apache.org/POM/4.0.0 " )
project = ET . Element ( " project " , xmlns = " http://maven.apache.org/POM/4.0.0 " )
append_elements ( project , [ ( " modelVersion " , " 4.0.0 " ) , ( " groupId " , " license.provenance " ) ,
append_elements ( project , [ ( " modelVersion " , " 4.0.0 " ) , ( " groupId " , " license.provenance " ) ,
( " artifactId " , " temporary-comparison " ) , ( " version " , " 1 " ) ] )
( " artifactId " , " temporary-comparison " ) , ( " version " , " 1 " ) ] )
@ -677,7 +729,7 @@ class Mycila:
config = ET . SubElement ( plugin , " configuration " )
config = ET . SubElement ( plugin , " configuration " )
append_elements ( config , [ ( " encoding " , " UTF-8 " ) , ( " strictCheck " , " true " ) , ( " quiet " , " true " ) ,
append_elements ( config , [ ( " encoding " , " UTF-8 " ) , ( " strictCheck " , " true " ) , ( " quiet " , " true " ) ,
( " failIfMissing " , " false " ) , ( " failIfUnknown " , " true " ) ,
( " failIfMissing " , " false " ) , ( " failIfUnknown " , " true " ) ,
( " reportFormat " , " json " ) , ( " reportLocation " , str ( self . report ) ) ] )
( " reportFormat " , " json " ) , ( " reportLocation " , str ( report ) ) ] )
config . append ( self . mapping ( styles ) )
config . append ( self . mapping ( styles ) )
license_set = ET . SubElement ( ET . SubElement ( config , " licenseSets " ) , " licenseSet " )
license_set = ET . SubElement ( ET . SubElement ( config , " licenseSets " ) , " licenseSet " )
append_elements ( license_set , [ ( " header " , str ( self . root / TEMPLATES [ header ] ) ) ,
append_elements ( license_set , [ ( " header " , str ( self . root / TEMPLATES [ header ] ) ) ,
@ -688,7 +740,7 @@ class Mycila:
parent = ET . SubElement ( license_set , " inlineHeaderStyles " )
parent = ET . SubElement ( license_set , " inlineHeaderStyles " )
for style in styles :
for style in styles :
append_elements ( ET . SubElement ( parent , " inlineHeaderStyle " ) , ( ( " name " , style . name ) , ) + style . settings )
append_elements ( ET . SubElement ( parent , " inlineHeaderStyle " ) , ( ( " name " , style . name ) , ) + style . settings )
ET . ElementTree ( project ) . write ( self . root / " pom.xml " , encoding = " utf-8 " , xml_declaration = True )
ET . ElementTree ( project ) . write ( pom , encoding = " utf-8 " , xml_declaration = True )
def mapping ( self , styles ) :
def mapping ( self , styles ) :
mapping = self . plugin . configuration . find ( " mapping " )
mapping = self . plugin . configuration . find ( " mapping " )
@ -721,7 +773,7 @@ def normalized_copies(mycila, source_refs, names, nonempty):
before = stage ( mycila , sources )
before = stage ( mycila , sources )
after = stage ( mycila , destinations )
after = stage ( mycila , destinations )
raw = git ( mycila . root , " diff-tree " , " --no-commit-id " , " -r " , " --raw " , " --no-abbrev " , " -z " ,
raw = git ( mycila . root , " diff-tree " , " --no-commit-id " , " -r " , " --raw " , " --no-abbrev " , " -z " ,
" -C50 % " , " --find-copies-harder " , " -l0 " , before , after )
f " -C { COPY_SIMILARITY } % " , " --find-copies-harder " , " -l0 " , before , after )
keys = { path : key for key , path in mycila . paths . items ( ) }
keys = { path : key for key , path in mycila . paths . items ( ) }
copies = defaultdict ( list )
copies = defaultdict ( list )
for source , destination , similarity in parse_copies ( raw ) :
for source , destination , similarity in parse_copies ( raw ) :
@ -733,9 +785,14 @@ def normalized_copies(mycila, source_refs, names, nonempty):
return dict ( copies )
return dict ( copies )
def staged ( content ) :
""" What stage() hands to Git: the size filter in front of the copy search measures exactly this. """
return content . replace ( b " \r \n " , b " \n " )
def stage ( mycila , keys ) :
def stage ( mycila , keys ) :
for key in keys :
for key in keys :
mycila . write ( key , mycila . contents [ key ] . replace ( b " \r \n " , b " \n " ) )
mycila . write ( key , staged ( mycila . contents [ key ] ) )
pathspec = " " . join ( mycila . paths [ key ] + " \0 " for key in sorted ( keys ) ) . encode ( " utf-8 " )
pathspec = " " . join ( mycila . paths [ key ] + " \0 " for key in sorted ( keys ) ) . encode ( " utf-8 " )
run ( [ " git " , " --literal-pathspecs " , " add " , " -f " , " --pathspec-from-file=- " , " --pathspec-file-nul " ] ,
run ( [ " git " , " --literal-pathspecs " , " add " , " -f " , " --pathspec-from-file=- " , " --pathspec-file-nul " ] ,
mycila . root , data = pathspec )
mycila . root , data = pathspec )
@ -822,9 +879,8 @@ class Lineage:
if git ( repo , " rev-parse " , " --is-shallow-repository " ) . decode ( ) . strip ( ) == " true " :
if git ( repo , " rev-parse " , " --is-shallow-repository " ) . decode ( ) . strip ( ) == " true " :
raise Failure ( " this clone is shallow and the check needs full history. Run git fetch --unshallow. " )
raise Failure ( " this clone is shallow and the check needs full history. Run git fetch --unshallow. " )
deleted = { }
deleted = { }
for base in bases :
for change in history ( repo , list ( bases ) , " --diff-filter=D " ) :
for change in history ( repo , base , " --diff-filter=D " ) :
deleted . setdefault ( change . path , { " path " : change . path , " ref " : change . commit + " ^1 " , " blob " : change . old } )
deleted . setdefault ( change . path , { " path " : change . path , " ref " : change . commit + " ^1 " , " blob " : change . old } )
return cls ( head = head , bases = tuple ( bases ) , trees = { base : tree ( repo , base ) for base in bases } , deleted = deleted )
return cls ( head = head , bases = tuple ( bases ) , trees = { base : tree ( repo , base ) for base in bases } , deleted = deleted )
def versions ( self , name ) :
def versions ( self , name ) :
@ -847,6 +903,7 @@ class Comparison:
copies : dict
copies : dict
merges : dict
merges : dict
ce_directories : frozenset
ce_directories : frozenset
size_filter : bool | None = None
def classify ( self , name , curation ) :
def classify ( self , name , curation ) :
key = ( " head " , name )
key = ( " head " , name )
@ -867,32 +924,230 @@ class Comparison:
) )
) )
def compare ( repo , plugin , lineage , contents ) :
class NormalizationCache :
""" Header-free contents of CE inputs from earlier runs, keyed by content and file name (Mycila styles follow the
name ) . One SQLite file per normalization signature : a different Mycila setup , template or check misses the cache .
The cache only ever costs or saves time : when SQLite fails , the run continues without it . """
def __init__ ( self , directory , signature ) :
self . directory = directory
self . lock = threading . Lock ( )
self . added = 0
self . hits = 0
self . database = None
self . unavailable = None
directory . mkdir ( parents = True , exist_ok = True )
self . path = directory / f " { signature } .sqlite "
try :
try :
self . database = self . open ( )
except sqlite3 . OperationalError :
raise # locked by another run or unreadable: not damage, so the file stays
except sqlite3 . DatabaseError :
# A damaged cache only costs time: start it again instead of failing the check.
self . path . unlink ( )
self . database = self . open ( )
except sqlite3 . Error as exc :
self . disable ( exc )
return
os . utime ( self . path )
# Only files named like this cache's own: --cache may point at a directory that holds other SQLite files.
own = [ path for path in directory . iterdir ( ) if CACHE_FILE . fullmatch ( path . name ) ]
kept = positive_setting ( CACHE_SIGNATURES_VARIABLE , CACHE_SIGNATURES_KEPT )
for stale in sorted ( own , key = lambda path : path . stat ( ) . st_mtime ) [ : - kept ] :
stale . unlink ( )
def open ( self ) :
database = sqlite3 . connect ( self . path , check_same_thread = False )
try :
database . execute ( " CREATE TABLE IF NOT EXISTS normalized (input TEXT PRIMARY KEY, content BLOB NOT NULL) " )
# Opening reads only the schema: a file damaged below it would fail on the first lookup instead.
if database . execute ( " PRAGMA quick_check " ) . fetchone ( ) [ 0 ] != " ok " :
raise sqlite3 . DatabaseError ( f " { self . path } is damaged " )
except BaseException :
database . close ( ) # before any unlink: Windows cannot remove an open file
raise
return database
def disable ( self , exc ) :
""" Continues the run without the cache; what earlier puts committed stays valid. Reported by close(), so
that a progress line in the middle of the run stays intact . """
self . unavailable = self . unavailable or str ( exc )
if self . database is not None :
try :
self . database . close ( )
except sqlite3 . Error :
pass
self . database = None
@staticmethod
def input ( name , raw ) :
return hashlib . sha256 ( raw ) . hexdigest ( ) + " / " + PurePosixPath ( name ) . name
def get ( self , inputs ) :
found = { }
with self . lock :
if self . database is None :
return found
try :
for key , raw in inputs . items ( ) :
row = self . database . execute ( " SELECT content FROM normalized WHERE input = ? " ,
( self . input ( key [ 0 ] , raw ) , ) ) . fetchone ( )
if row is not None :
found [ key ] = bytes ( row [ 0 ] )
except sqlite3 . Error as exc :
self . disable ( exc )
return { }
self . hits + = len ( found )
return found
def put ( self , entries ) :
with self . lock :
if self . database is None :
return
try :
self . database . executemany ( " INSERT OR IGNORE INTO normalized VALUES (?, ?) " ,
[ ( self . input ( key [ 0 ] , raw ) , content ) for key , raw , content in entries ] )
# Committed at once: the write lock is held only briefly, so another run on the same cache can add too.
self . database . commit ( )
except sqlite3 . Error as exc :
self . disable ( exc )
return
self . added + = len ( entries )
def close ( self ) :
if self . database is not None :
self . database . close ( )
self . database = None
if self . unavailable :
console . line ( f " The cache in { self . directory } was unavailable ( { self . unavailable } ); "
" the run continued without it " , " dim " )
class NoCache :
added = hits = 0
def get ( self , inputs ) :
return { }
def put ( self , entries ) :
pass
def close ( self ) :
pass
def cache_signature ( repo , plugin ) :
digest = hashlib . sha256 ( CACHE_FORMAT . encode ( ) )
version , configuration = plugin_signature ( plugin )
for part in ( Path ( __file__ ) . read_bytes ( ) , version . encode ( ) , configuration ,
* ( ( repo / name ) . read_bytes ( ) for name in TEMPLATES . values ( ) ) ) :
digest . update ( len ( part ) . to_bytes ( 8 , " big " ) + part )
return digest . hexdigest ( ) [ : 32 ]
def normalize ( repo , plugin , cache , inputs ) :
""" Header-free contents of CE inputs ( { key: raw bytes}, key[0] the file name), from the cache when it has them. """
found = cache . get ( inputs )
missing = { key : raw for key , raw in inputs . items ( ) if key not in found }
if missing :
with tempfile . TemporaryDirectory ( prefix = " license-provenance- " ) as temporary :
mycila = Mycila ( repo , Path ( temporary ) , plugin )
for key , raw in missing . items ( ) :
mycila . add ( key , key [ 0 ] , raw )
mycila . strip_headers ( )
grown = [ key [ 0 ] for key , raw in missing . items ( ) if len ( mycila . contents [ key ] ) > len ( raw ) ]
if grown :
raise Failure ( f " Mycila grew these files while removing their headers: { grown [ : 20 ] } " )
found | = { key : mycila . contents [ key ] for key in missing }
cache . put ( [ ( key , raw , found [ key ] ) for key , raw in missing . items ( ) ] )
return found
def staged_size ( content ) :
return len ( staged ( content ) )
def could_be_copy ( size , destinations ) :
""" Git scores a pair 0 unless the smaller blob is at least COPY_SIMILARITY % o f the larger (diffcore-rename
estimate_similarity ) . """
return any ( 100 * min ( size , other ) > = COPY_SIMILARITY * max ( size , other ) for other in destinations )
def git_finds_copy ( repo , plugin , source , destination ) :
""" Whether the copy search, normalized_copies itself, matches destination, a new path, to source, a CE file. """
with tempfile . TemporaryDirectory ( prefix = " license-provenance- " ) as temporary :
staging = Mycila ( repo , Path ( temporary ) , plugin )
staging . add ( ( " Source.java " , " probe " ) , " Source.java " , source )
staging . add ( ( " head " , " Destination.java " ) , " Destination.java " , destination )
found = normalized_copies ( staging , { ( " Source.java " , " probe " ) : " probe " } , { " Destination.java " } , staging . nonempty ( ) )
return " Destination.java " in found
def size_filter_holds ( repo , plugin ) :
""" Whether the installed Git still never matches a source that could_be_copy rules out. The filter relies on Git
measuring similarity against the larger blob ( estimate_similarity divides by the larger size , and diffcore - delta . c
counts at most the smaller blob as copied ) , so a source below COPY_SIMILARITY % of a destination can never reach
the threshold . The probe asks the real copy search twice : a source of exactly COPY_SIMILARITY % of a destination
must be found , the same source one byte shorter must not . That catches a Git that measures against anything but
the larger blob ; nothing else in this repository would notice such a change , and the filter would then drop CE
files Git matches . Both answers are compared with could_be_copy itself , so a change of the Python rule that no
longer matches Git turns the filter off as well . Each case runs in its own repository , so a found boundary pair
cannot hide the other answer . """
destination = b " " . join ( b " line %05d \n " % index for index in range ( 100 ) )
boundary = destination [ : len ( destination ) * COPY_SIMILARITY / / 100 ]
sources = [ boundary , boundary [ : - 1 ] ]
rule = [ could_be_copy ( len ( source ) , [ len ( destination ) ] ) for source in sources ]
answers = parallel ( lambda source : git_finds_copy ( repo , plugin , source , destination ) , sources )
return rule == answers == [ True , False ]
def could_shrink_to_copy ( raw_size , destinations ) :
""" Normalizing never grows a file: below COPY_SIMILARITY % o f the smallest destination it stays out of Git ' s reach. """
return 100 * raw_size > = COPY_SIMILARITY * min ( destinations )
def compare ( repo , plugin , lineage , contents , cache , in_scope ) :
names = list ( contents )
names = list ( contents )
new_paths = { name for name in names if not lineage . versions ( name ) }
new_paths = { name for name in names if not lineage . versions ( name ) }
# Copy sources follow every path in scope that CE lacks, not only the checked ones: with --since they would
# otherwise depend on the files a pull request changes and miss copies that a full run finds. Without new paths
# nothing is searched for copies, so no CE file needs to be read for it.
copy_source_types = { name for name in in_scope if not lineage . versions ( name ) } if new_paths else set ( )
sources = { }
sources = { }
for base , files in lineage . trees . items ( ) :
for base , files in lineage . trees . items ( ) :
for name in names :
for name in names :
if name in files :
if name in files :
sources . setdefault ( ( name , files [ name ] ) , base )
sources . setdefault ( ( name , files [ name ] ) , base )
for key in comparable_ce_files ( files , new_paths ) . items ( ) :
for key in comparable_ce_files ( files , copy_source_type s) . items ( ) :
sources . setdefault ( key , base )
sources . setdefault ( key , base )
versions = { ( name , oid ) for name in names for _ , oid in lineage . versions ( name ) }
# Git breaks ties between equally similar copy sources by path. Sources are staged in key order, padded so that
# paths sort like ranks: --since, a full run and the size filter all present any two sources in the same order.
slots = { ( " head " , name ) : f " { index : 08d } " for index , name in enumerate ( sorted ( names ) ) }
slots | = { key : f " { index : 08d } " for index , key in enumerate ( sorted ( sources ) ) }
bytes_by_id = blobs ( repo , [ oid for _ , oid in sources ] )
bytes_by_id = blobs ( repo , [ oid for _ , oid in sources ] )
with tempfile . TemporaryDirectory ( prefix = " license-provenance- " ) as temporary :
with tempfile . TemporaryDirectory ( prefix = " license-provenance- " ) as temporary :
mycila = Mycila ( repo , Path ( temporary ) , plugin )
mycila = Mycila ( repo , Path ( temporary ) , plugin )
for name , content in contents . items ( ) :
for name , content in contents . items ( ) :
mycila . add ( ( " head " , name ) , name , content )
mycila . add ( ( " head " , name ) , name , content , slots [ ( " head " , name ) ] )
for path , oid in sorted ( sources ) :
mycila . add ( ( path , oid ) , path , bytes_by_id [ oid ] )
console . begin ( " Recognizing headers " )
console . begin ( " Recognizing headers " )
recognized = mycila . current_headers ( [ ( " head " , name ) for name in names ] )
recognized = mycila . current_headers ( [ ( " head " , name ) for name in names ] )
console . end ( )
console . end ( )
console . begin ( " Comparing against CE " )
console . begin ( " Comparing against CE " )
normalized = mycila . strip_headers ( )
head_hashes , copy_sources = parallel ( lambda job : job ( ) , [
mycila . strip_headers ,
lambda : normalize ( repo , plugin , cache , { key : bytes_by_id [ key [ 1 ] ] for key in versions } ) ] )
headers = mycila . header_states ( recognized )
headers = mycila . header_states ( recognized )
copies = normalized_copies ( mycila , sources , new_paths , mycila . nonempty ( ) )
destinations = { name : mycila . contents [ ( " head " , name ) ] for name in sorted ( new_paths )
merges = clean_merges ( repo , plugin , lineage , names , normalized )
if mycila . contents [ ( " head " , name ) ] . strip ( ) }
console . end ( f " done ( { len ( normalized ) } file versions) " )
normalized = head_hashes | { key : comparison_hash ( content ) for key , content in copy_sources . items ( ) }
copies , searched , size_filter = copy_candidates ( repo , plugin , cache , sources , versions , slots , bytes_by_id ,
destinations , copy_sources )
normalized | = searched
merges = clean_merges ( repo , plugin , cache , lineage , names , normalized )
console . end ( f " done ( { len ( normalized ) } file versions, { len ( searched ) } of { len ( sources ) - len ( versions ) } "
f " other CE files searched for copies, { cache . hits } from the cache) " )
return Comparison (
return Comparison (
lineage = lineage ,
lineage = lineage ,
contents = contents ,
contents = contents ,
@ -902,34 +1157,64 @@ def compare(repo, plugin, lineage, contents):
merges = merges ,
merges = merges ,
ce_directories = frozenset ( str ( parent ) for files in lineage . trees . values ( )
ce_directories = frozenset ( str ( parent ) for files in lineage . trees . values ( )
for path in files for parent in PurePosixPath ( path ) . parents ) ,
for path in files for parent in PurePosixPath ( path ) . parents ) ,
size_filter = size_filter ,
)
)
def clean_merges ( repo , plugin , lineage , names , normalized ) :
def copy_candidates ( repo , plugin , cache , sources , versions , slots , bytes_by_id , destinations , copy_sources ) :
merged = { }
""" CE files similar to the paths that CE does not have, normalized only when Git could match them by size; the
for index , left in enumerate ( lineage . bases ) :
comparison hashes of the other CE files searched for them ; and whether the size filter was used , None when there
for right in lineage . bases [ index + 1 : ] :
was nothing to search for . """
ancestors = git ( repo , " merge-base " , " --all " , left , right ) . decode ( ) . split ( )
if not destinations :
if len ( ancestors ) != 1 :
return { } , { } , None
sizes = [ staged_size ( content ) for content in destinations . values ( ) ]
# Slower, never wrong: when the installed Git disagrees with the size rule, every CE file is searched.
size_filter = size_filter_holds ( repo , plugin )
others = sorted ( key for key in sources if key not in versions
and ( not size_filter or could_shrink_to_copy ( len ( bytes_by_id [ key [ 1 ] ] ) , sizes ) ) )
found = normalize ( repo , plugin , cache , { key : bytes_by_id [ key [ 1 ] ] for key in others } )
searched = { key : comparison_hash ( content ) for key , content in found . items ( ) }
with tempfile . TemporaryDirectory ( prefix = " license-provenance- " ) as temporary :
staging = Mycila ( repo , Path ( temporary ) , plugin )
for key , content in ( found | copy_sources ) . items ( ) :
staging . add ( key , key [ 0 ] , content , slots [ key ] )
for name , content in destinations . items ( ) :
staging . add ( ( " head " , name ) , name , content , slots [ ( " head " , name ) ] )
reachable = { key : sources [ key ] for key in [ * others , * copy_sources ]
if not size_filter or could_be_copy ( staged_size ( staging . contents [ key ] ) , sizes ) }
return normalized_copies ( staging , reachable , set ( destinations ) , staging . nonempty ( ) ) , searched , size_filter
def clean_merges ( repo , plugin , cache , lineage , names , normalized ) :
pairs = [ ( left , right ) for index , left in enumerate ( lineage . bases ) for right in lineage . bases [ index + 1 : ] ]
def ancestry ( pair ) :
ancestors = git ( repo , " merge-base " , " --all " , * pair ) . decode ( ) . split ( )
return ( ancestors [ 0 ] , tree ( repo , ancestors [ 0 ] ) ) if len ( ancestors ) == 1 else None
candidates = [ ]
for ( left , right ) , common in zip ( pairs , parallel ( ancestry , pairs ) ) :
if common is None :
continue
ancestor , files = common
for name in names :
ours , theirs = lineage . trees [ left ] . get ( name ) , lineage . trees [ right ] . get ( name )
if ours is None or theirs is None or ours == theirs or name not in files :
continue
if normalized [ ( " head " , name ) ] in { normalized [ ( name , ours ) ] , normalized [ ( name , theirs ) ] } :
continue
continue
ancestry = tree ( repo , ancestors [ 0 ] )
candidates . append ( ( ( name , left , right ) , ( ours , files [ name ] , theirs ) , ancestor ) )
for name in names :
# Base pairs share most blobs: every distinct three-way merge runs once, all of them in parallel.
ours , theirs = lineage . trees [ left ] . get ( name ) , lineage . trees [ right ] . get ( name )
triples = list ( dict . fromkeys ( triple for _ , triple , _ in candidates ) )
if ours is None or theirs is None or ours == theirs or name not in ancestry :
contents = dict ( zip ( triples , parallel ( lambda triple : merge_blobs ( repo , * triple ) , triples ) ) )
continue
merged = { }
if normalized [ ( " head " , name ) ] in { normalized [ ( name , ours ) ] , normalized [ ( name , theirs ) ] } :
for key , triple , ancestor in candidates :
continue
if contents [ triple ] is not None :
content = merge_blobs ( repo , ours , ancestry [ name ] , theirs )
merged [ key ] = ( contents [ triple ] , { " path " : key [ 0 ] , " merge " : [ key [ 1 ] , key [ 2 ] ] , " base " : ancestor } )
if content is not None :
merged [ ( name , left , right ) ] = ( content , { " path " : name , " merge " : [ left , right ] ,
" base " : ancestors [ 0 ] } )
if not merged :
if not merged :
return { }
return { }
with tempfile . TemporaryDirectory ( prefix = " license-provenance- " ) as temporary :
found = normalize ( repo , plugin , cache , { key : content for key , ( content , _ ) in merged . items ( ) } )
mycila = Mycila ( repo , Path ( temporary ) , plugin )
hashes = { key : comparison_hash ( content ) for key , content in found . items ( ) }
for key , ( content , _ ) in merged . items ( ) :
mycila . add ( key , key [ 0 ] , content )
hashes = mycila . strip_headers ( )
result = { }
result = { }
for key , ( _ , description ) in merged . items ( ) :
for key , ( _ , description ) in merged . items ( ) :
if hashes [ key ] == normalized [ ( " head " , key [ 0 ] ) ] :
if hashes [ key ] == normalized [ ( " head " , key [ 0 ] ) ] :
@ -937,6 +1222,89 @@ def clean_merges(repo, plugin, lineage, names, normalized):
return result
return result
@dataclass ( frozen = True )
class Selection :
since : str
merge_base : str
paths : frozenset | None
reason : str
@property
def full ( self ) :
return self . paths is None
def report ( self ) :
return { " since " : self . since , " mergeBase " : self . merge_base , " full " : self . full , " reason " : self . reason }
def merge_base ( repo , since ) :
commit = resolve ( repo , since )
bases = run ( [ " git " , " merge-base " , commit , " HEAD " ] , repo , ok = ( 0 , 1 ) ) . stdout . decode ( ) . split ( )
if not bases :
raise Failure ( f " HEAD shares no history with { since } . " )
return bases [ 0 ]
def changed_paths ( repo , commit ) :
""" Paths that differ between the commit and the working tree, untracked files included. """
tracked = git ( repo , " diff " , " --name-only " , " --no-renames " , " -z " , commit , " -- " )
untracked = git ( repo , " ls-files " , " --others " , " --exclude-standard " , " -z " )
return { path . decode ( " utf-8 " ) for path in ( tracked + b " \0 " + untracked ) . split ( b " \0 " ) if path }
def committed ( repo , commit , name ) :
result = run ( [ " git " , " cat-file " , " blob " , f " { commit } : { name } " ] , repo , ok = ( 0 , 128 ) )
return result . stdout if result . returncode == 0 else None
def committed_plugin ( repo , commit ) :
content = committed ( repo , commit , " pom.xml " )
try :
return None if content is None else plugin_signature ( parse_plugin ( xml_plain ( io . BytesIO ( content ) ) ) )
except ( Failure , ET . ParseError ) :
return None
def committed_curations ( repo , commit ) :
content = committed ( repo , commit , CURATIONS )
if content is None :
return { }
try :
return { entry [ " path " ] : entry for entry in json . loads ( content ) [ " curations " ] }
except ( ValueError , KeyError , TypeError ) :
return None
def select_changes ( repo , since , bases , ce_bases , plugin , curations ) :
""" Files to check against a PR target: the changed ones, unless a change can move verdicts of unchanged files. """
base = merge_base ( repo , since )
def full ( reason ) :
return Selection ( since , base , None , reason )
try :
if sorted ( ce_bases ( base ) ) != sorted ( bases ) :
return full ( " the CE commits merged into the branch changed " )
except Failure :
return full ( " the CE commits merged at the merge base cannot be resolved " )
if committed_plugin ( repo , base ) != plugin_signature ( plugin ) :
return full ( " the Mycila configuration in the root pom.xml changed " )
changed = changed_paths ( repo , base )
checker = sorted ( path for path in changed
if path . startswith ( CHECKER_PATHS ) and path not in { CURATIONS , README } )
if checker :
return full ( f " the check itself changed ( { checker [ 0 ] } ) " )
previous = committed_curations ( repo , base )
curated = set ( curations ) if previous is None else {
name for name in set ( previous ) | set ( curations ) if previous . get ( name ) != curations . get ( name ) }
paths = frozenset ( changed | curated )
return Selection ( since , base , paths , f " { len ( paths ) } changed paths " )
def git_version ( ) :
return run ( [ " git " , " --version " ] , Path . cwd ( ) ) . stdout . decode ( ) . strip ( ) . removeprefix ( " git version " )
def current_branch ( repo ) :
def current_branch ( repo ) :
branch = git ( repo , " rev-parse " , " --abbrev-ref " , " HEAD " ) . decode ( ) . strip ( )
branch = git ( repo , " rev-parse " , " --abbrev-ref " , " HEAD " ) . decode ( ) . strip ( )
return " " if branch == " HEAD " else branch
return " " if branch == " HEAD " else branch
@ -1058,15 +1426,19 @@ def print_findings(rows, curation_issues, ref_names):
f " Rerun with --fix to remove them from { CURATIONS } " , style = None )
f " Rerun with --fix to remove them from { CURATIONS } " , style = None )
def print_summary ( rows , curation_issues , report ) :
def print_summary ( rows , curation_issues , report , label = " files " ) :
findings = sum ( row [ " status " ] != " match " for row in rows ) + len ( curation_issues )
findings = sum ( row [ " status " ] != " match " for row in rows ) + len ( curation_issues )
restamped = sum ( " previousHeader " in row for row in rows )
restamped = sum ( " previousHeader " in row for row in rows )
note = f " ( { restamped } restamped) " if restamped else " "
note = f " ( { restamped } restamped) " if restamped else " "
if findings :
if findings :
console . line ( f " { findings } finding { ' s ' if findings != 1 else ' ' } in { len ( rows ) } files { note } . Report: { report } " ,
console . line ( f " { findings } finding { ' s ' if findings != 1 else ' ' } in { len ( rows ) } { label } { note } . Report: { report } " ,
" red " )
" red " )
return
return
console . line ( f " All { len ( rows ) } files carry the expected header { note } . " , " green " )
if not rows :
console . line ( f " No { label } to check. " , " green " )
console . line ( f " Report: { report } " )
return
console . line ( f " All { len ( rows ) } { label } carry the expected header { note } . " , " green " )
counts = Counter ( row [ " expectedHeader " ] for row in rows )
counts = Counter ( row [ " expectedHeader " ] for row in rows )
console . line ( " " + " · " . join ( f " { header } { counts [ header ] } " for header in TEMPLATES if counts [ header ] ) )
console . line ( " " + " · " . join ( f " { header } { counts [ header ] } " for header in TEMPLATES if counts [ header ] ) )
console . line ( f " Report: { report } " )
console . line ( f " Report: { report } " )
@ -1166,16 +1538,43 @@ def check(args):
curation_bytes = curation_path . read_bytes ( )
curation_bytes = curation_path . read_bytes ( )
curations = load_curations ( curation_path )
curations = load_curations ( curation_path )
console . begin ( " Resolving Git history " )
console . begin ( " Resolving Git history " )
bases = merged_ce_bases ( repo , head , ce [ " commit " ] ) if " ref " in ce else relicensed_ce_bases ( repo , head )
def ce_bases ( commit ) :
return merged_ce_bases ( repo , commit , ce [ " commit " ] ) if " ref " in ce else relicensed_ce_bases ( repo , commit )
bases = ce_bases ( head )
lineage = Lineage . load ( repo , head , bases )
lineage = Lineage . load ( repo , head , bases )
console . end ( " done (CE base " + " , " . join ( ref_name ( base , ref_names ) for base in bases ) + " ) " )
console . end ( " done (CE base " + " , " . join ( ref_name ( base , ref_names ) for base in bases ) + " ) " )
selection = None
if args . since :
console . begin ( f " Selecting files changed since { args . since } " )
selection = select_changes ( repo , args . since , bases , ce_bases , plugin , curations )
console . end ( ( " full check: " if selection . full else " " ) + selection . reason
+ f " (merge base { selection . merge_base [ : 11 ] } ) " )
console . begin ( " Collecting Mycila scope " )
console . begin ( " Collecting Mycila scope " )
scope = discover_scope ( repo , plugin )
scope = discover_scope ( repo , plugin )
console . end ( f " { len ( scope . eligible ) } files ( { scope . ignored } Git-ignored skipped) " )
console . end ( f " { len ( scope . eligible ) } files ( { scope . ignored } Git-ignored skipped) " )
contents = { name : ( repo / name ) . read_bytes ( ) for name in scope . eligible }
checked = ( scope . eligible if selection is None or selection . full
comparison = compare ( repo , plugin , lineage , contents )
else [ name for name in scope . eligible if name in selection . paths ] )
if selection is not None and not selection . full :
console . line ( f " Checking { len ( checked ) } of { len ( scope . eligible ) } files in scope " , " dim " )
contents = { name : ( repo / name ) . read_bytes ( ) for name in checked }
rows = [ ]
size_filter = None
if contents :
cache = ( NoCache ( ) if args . no_cache
else NormalizationCache ( ( repo / args . cache ) . resolve ( ) , cache_signature ( repo , plugin ) ) )
try :
comparison = compare ( repo , plugin , lineage , contents , cache , scope . eligible )
finally :
cache . close ( )
rows = [ comparison . classify ( name , curations . get ( name ) ) for name in checked ]
size_filter = comparison . size_filter
console . line ( )
console . line ( )
rows = [ comparison . classify ( name , curations . get ( name ) ) for name in scope . eligible ]
if size_filter is False :
console . line ( f " Git ' s copy detection (git { git_version ( ) } ) and the size rule of the copy search disagree; "
" every CE file was searched for copies. Report this to the maintainers of the check. " , " red " )
console . line ( )
orphaned = [ { " path " : name , " status " : " stale-curation " , " reason " : " file is no longer in scope " }
orphaned = [ { " path " : name , " status " : " stale-curation " , " reason " : " file is no longer in scope " }
for name in sorted ( set ( curations ) - set ( scope . eligible ) ) ]
for name in sorted ( set ( curations ) - set ( scope . eligible ) ) ]
ensure_inputs_unchanged ( repo , lineage , curation_path , curation_bytes , contents )
ensure_inputs_unchanged ( repo , lineage , curation_path , curation_bytes , contents )
@ -1190,6 +1589,8 @@ def check(args):
" head " : lineage . head ,
" head " : lineage . head ,
" ce " : ce | { " bases " : list ( lineage . bases ) } ,
" ce " : ce | { " bases " : list ( lineage . bases ) } ,
" scope " : { " supported " : len ( scope . eligible ) , " unknown " : scope . unknown , " modules " : scope . modules } ,
" scope " : { " supported " : len ( scope . eligible ) , " unknown " : scope . unknown , " modules " : scope . modules } ,
" selection " : selection . report ( ) if selection is not None else None ,
" copySearch " : { " sizeFilter " : size_filter } ,
" summary " : dict ( summary ) ,
" summary " : dict ( summary ) ,
" restamped " : sorted ( row [ " path " ] for row in rows if " previousHeader " in row ) ,
" restamped " : sorted ( row [ " path " ] for row in rows if " previousHeader " in row ) ,
" removedCurations " : removed ,
" removedCurations " : removed ,
@ -1203,7 +1604,7 @@ def check(args):
print_restamped ( rows )
print_restamped ( rows )
print_removed_curations ( removed )
print_removed_curations ( removed )
print_findings ( rows , orphaned , ref_names )
print_findings ( rows , orphaned , ref_names )
print_summary ( rows , orphaned , report )
print_summary ( rows , orphaned , report , " files " if selection is None or selection . full else " changed files " )
return 1 if orphaned or summary . keys ( ) - { " match " } else 0
return 1 if orphaned or summary . keys ( ) - { " match " } else 0
@ -1215,7 +1616,15 @@ def main(argv=None):
" without it, CE is the history of HEAD that does not contain the relicensing commit " )
" without it, CE is the history of HEAD that does not contain the relicensing commit " )
parser . add_argument ( " --ce-remote " , default = CE_REMOTE ,
parser . add_argument ( " --ce-remote " , default = CE_REMOTE ,
help = f " Git URL or path of the CE repository to fetch --ce-ref from (default: { CE_REMOTE } ) " )
help = f " Git URL or path of the CE repository to fetch --ce-ref from (default: { CE_REMOTE } ) " )
parser . add_argument ( " --since " , metavar = " REF " ,
help = " check only files changed since the merge base of REF and HEAD, uncommitted and "
" untracked files included; falls back to the full check when the CE commits, the "
" root Mycila configuration or the check itself changed " )
parser . add_argument ( " --output " , default = " target/license-provenance/report.json " )
parser . add_argument ( " --output " , default = " target/license-provenance/report.json " )
parser . add_argument ( " --cache " , default = CACHE_DIRECTORY , metavar = " DIRECTORY " ,
help = " header-free CE contents from earlier runs, reused while the Mycila setup, the "
f " templates and the check stay the same (default: { CACHE_DIRECTORY } ) " )
parser . add_argument ( " --no-cache " , action = " store_true " , help = " normalize every CE input again " )
parser . add_argument ( " --fix " , action = " store_true " ,
parser . add_argument ( " --fix " , action = " store_true " ,
help = " restamp files whose expected header the check determined and remove redundant or "
help = " restamp files whose expected header the check determined and remove redundant or "
" orphaned curations; unrecognized headers are kept " )
" orphaned curations; unrecognized headers are kept " )