Repository navigation
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Major rewrite of corediff into a subcommand-based CLI with powerful database indexing capabilities.
Architecture
cmd/corediff+internal/packagesscan,db index,db merge,db info,updateDatabase indexing (
db index)-pflag treats positional args as package names, processed concurrently (cd3 db index -d m2.db -p pkg1 pkg2 pkg3)--composerindexes all packages from composer.json + lock--update: re-check all previously tracked packages for new versionsreplacesupport--parallelflag--cache-dirScanning
--suspectflag for suspect-only output--path-filterfor scoping scan results--textfor scanning all valid UTF-8 fileswalkFileshelper with glob-based exclusion patternsNormalize pipeline
Self-update
corediff updatecommand with pre/post version displaysyscall.Execbug: use resolved exe path instead ofos.Args[0]Other
sanseciomodule pathTest plan
go test ./...passescorediff scanagainst a Magento installationcorediff db index -pwith multiple packagescorediff update