licenses.py¶
clew/licenses.py
Each file's declared licence: its `SPDX-License-Identifier` header, read into `file_licenses` (S5).
ingest_file_licenses
int clew.licenses.ingest_file_licenses(Path db_path, Path repo_root, IndexCache|None cache=None)
Record every indexed file's declared licence.
Source · 34 lines
def ingest_file_licenses(db_path: Path, repo_root: Path, cache: IndexCache | None = None) -> int:
"""MEMOIZED ON CONTENT like `file_docs`, so an unchanged file is not re-read. THE TABLE IS
ALWAYS CREATED: empty means "no file declares one", absent would mean "this layer never ran".
@brief Build the licence layer.
@return Row count.
"""
from .filedocs import _indexed_files
conn = sqlite3.connect(str(db_path))
try:
conn.executescript(_DDL)
conn.execute("DELETE FROM file_licenses")
resolved: dict[str, str] = {}
rows = []
for rel in _indexed_files(conn):
if (
within_repo(repo_root / rel, repo_root, setting=f"licence of {rel}", memo=resolved)
is None
):
continue
found = license_of(cache, repo_root, rel)
if found:
rows.append((rel, found[0], found[1]))
conn.executemany(
"INSERT INTO file_licenses (file_path, license, line) VALUES (?, ?, ?)", rows
)
conn.commit()
finally:
conn.close()
logger.info("file_licenses: %d file(s) declare an SPDX licence", len(rows))
return len(rows)
Activity · 17 steps
Requirements
refresh_file_license
None clew.licenses.refresh_file_license(sqlite3.Connection conn, Path repo_root, str rel, IndexCache cache)
Rewrite one edited file's licence row (the fast tier).
Source · 12 lines
def refresh_file_license(
conn: sqlite3.Connection, repo_root: Path, rel: str, cache: IndexCache
) -> None:
"""@brief The same row `ingest_file_licenses` writes, for one file. @return None."""
if conn.execute("SELECT 1 FROM sqlite_master WHERE name = 'file_licenses'").fetchone() is None:
return
conn.execute("DELETE FROM file_licenses WHERE file_path = ?", (rel,))
found = license_of(cache, repo_root, rel)
if found:
conn.execute(
"INSERT INTO file_licenses (file_path, license, line) VALUES (?, ?, ?)", (rel, *found)
)1 more lines, not shown
Activity · 6 steps
Requirements
spdx_of
tuple[str, int] | None clew.licenses.spdx_of(str text)
The SPDX expression a file's header declares, and its line.
Called by _license_of
Tested by
Calls none
Source · 14 lines
def spdx_of(text: str) -> tuple[str, int] | None:
"""Any comment style — `//`, `#`, `/* */`, `--`, `<!-- -->`, `;` — because the tag is matched
where it stands, not after a comment prefix this module would have to know per language.
@brief Read the SPDX identifier.
@return Expression and line, or None.
"""
for number, line in enumerate(text.splitlines()[:_HEAD_LINES], start=1):
match = _SPDX.search(line)
if match and match.group(1).strip():
return " ".join(match.group(1).split()), number
return None