Skip to content

V3: subcommand CLI, packagist indexing, incremental DB, self-update - #28

Merged
gwillem merged 45 commits into
mainfrom
v3
Feb 17, 2026
Merged

gwillem merged 45 commits into
mainfrom
v3

Conversation

@gwillem

@gwillem gwillem commented Feb 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Major rewrite of corediff into a subcommand-based CLI with powerful database indexing capabilities.

Architecture

  • Restructured into cmd/corediff + internal/ packages
  • Subcommand CLI: scan, db index, db merge, db info, update
  • New binary CDDB format with XXH3 hashing (legacy xxhash64 auto-detected)
  • Map-based O(1) hash lookups replacing sorted-slice binary search

Database indexing (db index)

  • Packagist: -p flag treats positional args as package names, processed concurrently (cd3 db index -d m2.db -p pkg1 pkg2 pkg3)
  • Composer: --composer indexes all packages from composer.json + lock
  • Git URLs: direct git repository indexing with tag discovery
  • --update: re-check all previously tracked packages for new versions
  • Manifest tracking for incremental indexing (skip already-indexed versions)
  • Monorepo sub-package detection and composer replace support
  • Concurrent indexing with --parallel flag
  • Incremental HashDB writes with Ctrl-C safety (flush on interrupt)
  • Git clone caching via --cache-dir
  • Composer auth.json support for private repositories

Scanning

  • --suspect flag for suspect-only output
  • --path-filter for scoping scan results
  • --text for scanning all valid UTF-8 files
  • CDC chunking for precise change detection
  • Shared walkFiles helper with glob-based exclusion patterns

Normalize pipeline

  • Optimized from 86 ns to 25 ns/line, zero allocations
  • Reusable 10 MB scanner buffer across files

Self-update

  • corediff update command with pre/post version display
  • Fixed syscall.Exec bug: use resolved exe path instead of os.Args[0]

Other

  • Rebrand to sansecio module path
  • AGPL-3.0 license
  • Updated README to match current CLI

Test plan

  • go test ./... passes
  • Manual test: corediff scan against a Magento installation
  • Manual test: corediff db index -p with multiple packages
  • Manual test: corediff update

Extract shared code from flat cmd/ package into internal/:
- internal/hashdb: HashDB type with Load/Save/Contains/Add
- internal/normalize: line normalization, hashing, file extension checks
- internal/path: app root detection, path exclusion patterns
- internal/highlight: suspect pattern detection

New CLI at cmd/corediff/ with subcommands:
- scan (default): unchanged scan behavior
- db add: hash files into DB (fixed broken call signature)
- db merge: combine databases (now functional)

Single file scanning skips app root check automatically.
HashDB is now a struct with sorted main slice and unsorted append
buffer. Contains uses binary search. New 16-byte CDDB header
(magic + version + count) for format validation. OpenReadOnly
marks DB immutable, OpenReadWrite allows mutation. Save compacts
and writes atomically.
OpenReadOnly now uses syscall.Mmap to map the DB file directly into
memory, avoiding allocation and copy. 19x faster open, 2750x less
memory vs OpenReadWrite. Close() releases the mapping. Callers
updated with defer db.Close().
- Fix db add: pass --no-platform flag to addPath, skip path hashes
  when enabled, validate app root for directories
- Add db info subcommand showing hash count, file size, format version
- Improve db merge stats: report duplicates removed
- Add CDC chunking for minified code (normalize.HashLine splits long
  lines into content-defined chunks before hashing)
- Update parseFileWithDB to use HashLine for multi-hash support
- Regenerate fixture/sample.db in CDDB format
- Add integration tests for db add, merge, info
- Add chunker package with tests and benchmarks
Index Composer packages by querying the Packagist API and bare-cloning
the git repo, walking tree objects directly without checkout. Falls back
to zip download when git source is unavailable.

- Move -d/--database to dbCmd parent, add --cache-dir for persistent clones
- Add --packagist flag with version pinning (vendor/pkg:1.0.0 or @1.0.0)
- Add normalize.HashReader for shared line hashing from io.Reader
- New internal/packagist package: API client with recorded testdata
- New internal/gitindex package: CloneAndIndex, CloneAndIndexWithDir, IndexZip
- Store paths with vendor/ prefix matching Composer install layout
- Global -v flag (was per-command), -vv logs HTTP and per-file, -vvv per-line hashes
- Integration test for psr/log (skipped in -short mode)
Parses composer.json for repository URLs and composer.lock for the full
dependency tree (skipping metapackages and platform packages). Uses
source/dist info directly from the lock file instead of querying repo
APIs. Indexes packages in parallel with GOMAXPROCS workers.

Also extracts buildHTTPClient and indexPackage helpers from executePackagist,
exports InstallHTTPTransport for pre-concurrent setup, and refactors
verbose logging levels (-v package info, -vv HTTP, -vvv paths, -vvvv lines).
Benchmarks showed map lookups ~10x faster than binary search at 20M entries.
The sorted main slice is kept only for CDDB file format serialization.
Rename db index to db add throughout, mark completed items,
remove detailed plans for finished steps, update architecture diagram.
Single Open() replaces OpenReadOnly/OpenReadWrite. Save() builds
the uint64 slice inline. Removes syscall/unsafe dependencies and
~230 lines of code.

Also updates CI workflow to actions v4/v5 and Go 1.24.
Track indexed package@version pairs in an append-only .manifest file
(sibling of the .db file). Skip already-indexed versions on subsequent
runs. Add --update flag to re-check all previously indexed packages
for new versions. Manifest is updated per-version via OnVersionDone
callback, so progress survives crashes. Also change HashReader to
return (new, total) counts and improve indexRef log line to show
hash rate after completion.
When indexing multiple versions of a package, adjacent versions share
99.99% of their files. Track seen blob SHA1 hashes across versions so
unchanged files are skipped entirely — no file read, UTF-8 check, or
line hashing. For large packages like aws/aws-sdk-php this reduces
work from ~432M to ~1M hash operations (~400x faster for subsequent
versions).
Parse composer.json "replace" sections during git indexing and record
replaced packages in the manifest. In --composer mode, replaced packages
are automatically skipped, avoiding redundant downloads for monorepos
like magento/magento2 that publish ~230 sub-packages.
Support reading raw sequential uint64 databases (no CDDB header) by
detecting format via magic bytes. Also clean up PLAN.md to reflect
current state.
Allow `db add <git-url>` to clone a repo, discover version tags,
and index all versions — skipping already-indexed ones via the
manifest. Includes composer.json name detection for path prefixes,
annotated tag resolution, and semver tag filtering.
- Load repositories from ~/.composer/config.json and merge with
  project repos when indexing via --composer
- Extend --update to handle git URL manifest entries by fetching
  new tags, filtering already-indexed versions, and indexing
- Refactor executeGitURL to reuse shared updateGitURLEntry helper
- Add doc/architecture.md with component overview and flow diagrams
When indexing a git monorepo, pre-scan the tree for sub-package
composer.json files. Use their name to store files under canonical
vendor paths (e.g. vendor/magento/module-catalog/Block/Product.php
instead of vendor/magento/magento2ce/app/code/...). Record each
sub-package's name@version in the manifest so --composer mode can
match them precisely.
Collect unique dependency versions from composer.lock across all tags
when indexing a git URL. After the main repo is indexed, group deps
by package and index each via single-clone multi-ref (with zip fallback).

- Export ParseLockPackages in composer package
- Add IndexResult struct, CollectLockDeps option to gitindex
- Filter out replaced packages from lock deps
- Skip replaced packages during --update (was querying packagist for
  every monorepo sub-package)
- Stop writing redundant @Version manifest entries for sub-packages
  covered by replace: entries
- Document manifest format and dep-following in architecture.md
Only explicitly added packages (via --packagist or git URL) are now
tracked for new version checks. Composer deps and version-pinned adds
are one-shot and skip tracking, avoiding wasteful rechecks of 200+ deps.
IndexZip now checks <cache-dir>/zip/<sha256>.zip before downloading.
Also default --cache-dir to ./cache and wire CacheDir through IndexOptions.
- Add bytes.Contains regex guard (89% regex cost reduction)
- Switch from xxhash64 to xxh3 (1.45x faster hashing)
- Change HashLine to callback API (eliminates per-line slice alloc)
- Export ChunkThreshold for fast-path single hash in HashLine
- Add minSize early-exit for short lines
- Add benchmarks and doc/benchmark.md with stage breakdown
HashReader now accepts an optional buf parameter. All file-walk loops
allocate once via normalize.NewScanBuf() and reuse across files.
Saves ~180 µs and 10 MB per file scanned.
… function

Legacy databases (headerless, CDDB v1) use xxhash64 while new CDDB v2
databases use XXH3. Previously HashLine and PathHash were hardcoded to
xxh3.Hash, ignoring the switchable Hash variable. This caused hash
mismatches when scanning against legacy databases.

- Add Version field to HashDB, populated by Open() from format detection
- Add UsesXXHash64() to check if DB needs legacy hash function
- Make HashLine/PathHash use the Hash variable instead of xxh3.Hash directly
- Call UseXXHash64() in scan when legacy DB is detected
- Bump CDDB version to 2 (XXH3), support reading v0/v1 (xxhash64)
- Update CLAUDE.md to document dual hash algorithm support
Add vendor/aws/aws-sdk-php/src/data/** and
vendor/symfony/intl/Resources/data/** to excludePaths, matching
the upstream change in setup.go (PR #27).
…unk display

- Prefer comma boundaries in CDC chunker for semantically meaningful chunks
  that align with PHP arrays and JS objects
- Reduce chunk sizes (mask 0x3F, min 32, max 128) for more granular output
- Pass chunk bytes through HashLine callback so scan displays only mismatched
  chunks instead of full lines
- Add end-to-end scan benchmark to doc/benchmark.md (v3 1.40x faster)
- Add chunker test fixtures and tests for comma preference and change detection
- Remove dynamic hash function threading (hashFn params, DefaultHashFn,
  UsesXXHash64) — single var Hash = xxh3.Hash in normalize package
- Reject legacy/v1 databases with clear re-index message
- Remove cespare/xxhash/v2 dependency
- Extract concurrentMerger for parallel indexing in db_index.go
- Extract walkFiles helper shared by walkPath and addPath
- Fix s.validate() error being silently discarded
- Fix hardcoded db version display in db info
- Switch HashReader to emit callback pattern (no hashdb dependency)
…de, unexport internal symbols

- Fix fmt.Println(fmt.Sprintf(...)) double-wrapping in db_index and gitindex
- Replace minLen helper with builtin min(), use b.Loop() and range-over-int
- Use slices.Collect(maps.Keys(...)) for map-to-slice conversions
- Replace empty slice literals with var declarations
- Remove dead code: newLoggingHTTPClient, useZip variable, duplicate system( pattern
- Replace logLevel int with verbose bool (dead numeric levels 1-2)
- Remove inappropriate fmt.Println from IsValidUtf8 library function
- Check discarded errors: Flock unlock, tree.Files().ForEach
- Move Verbose assignment from buildHTTPClient to each call site
- Fix misleading NoPlatform description in scan command
- Unexport internal-only symbols: normalize.{scanExts,hashFunc,normLine},
  gitindex.subPackage, composer.normalizeRepoURL
Move extension and UTF-8 validity checks from walkPath and addPath
callbacks into walkFiles, so "what is a code file" is defined once.
- Rename Go module from github.com/gwillem/corediff to github.com/sansecio/corediff
- Update branding references from Willem de Groot to Sansec BV
- Extract self-update from scan into dedicated `corediff update` subcommand
- Add global `--version` flag to print version and exit
- Update default hash DB URL to m2.db3
- Add download progress messages when syncing default database
- Add release target to justfile
- Point DB version mismatch error to `corediff update`
- Handle second return value from urlfilecache.ToPath
- Build & upload release targets in parallel
- Move indexing doc from docs/ to doc/, clean up completed TODO items
…nd scanning

Adds -p/--parallel global option (defaults to GOMAXPROCS). Scanning now
uses a worker pool with buffered per-file output to avoid interleaving.
Indexing's concurrentMerger accepts the same configurable limit.
Hashes are now persisted to disk as they're computed during indexing,
so Ctrl-C never destroys previous results. OpenForWrite keeps a write
handle open, Add/Merge append incrementally, and a SIGINT handler
flushes progress before exit. Crash recovery truncates uncommitted
trailing bytes on next open.
Enables indexing many packages in one invocation:
  cd3 db index -d m2.db -p brick/math composer/ca-bundle guzzlehttp/guzzle

Packages are processed concurrently via concurrentMerger.
@gwillem gwillem changed the title WIP V3 V3: subcommand CLI, packagist indexing, incremental DB, self-update Feb 17, 2026
@gwillem
gwillem merged commit ede9766 into main Feb 17, 2026
1 check passed
@gwillem
gwillem deleted the v3 branch February 17, 2026 11:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant