Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ Local scans inspect up to eight directory levels and 10,000 filesystem entries b

Path roles filter the files used as detection evidence. Fixtures, vendored files, caches and build output do not contribute tools or dependencies. Language file matching also excludes generated files, tests, examples, benchmarks, fuzz targets, documentation and helper scripts. Ranking, inferred style and inferred source directories use the remaining source-role files and unclassified paths such as `main.go`. Project manifests can establish a language without counting as source files. Test files remain available for test-tool detection, and generated lockfiles remain dependency evidence. These filters do not change external line-count totals.

The bounded scan respects `.gitignore` rules from the project root and directories it visits. Ignored untracked paths are excluded from detection, while tracked source and new files that are not ignored remain available. Each included submodule uses its own rules.

Remote sources are shallow-cloned by default. Use `--depth 0` for a full clone, `--keep` to preserve the clone, or `--dir ./somewhere` to clone into a specific directory. Use `--cache ./cache` to keep one shallow checkout per HTTPS URL and reuse it across runs. Cache mode cannot be combined with `--depth 0` or `--dir`.

Use `brief --json --notebooks .` to add Jupyter code-cell statistics. The `notebooks` field reports kernel language and its metadata source, code cells, physical source lines and bytes, with saved-output bytes kept separate. `output_bytes` counts the original serialized JSON for code-cell `outputs` fields, including JSON syntax and whitespace. It supports notebook formats 3 and 4, follows scan exclusions and reports malformed or oversized files. Parsing is limited to 32 files, 8.39 MB per file and 33.55 MB read in total. Opt-in scans can detect known kernel languages when code cells are present and the notebooks meet the existing language-evidence rules. Parsing remains opt-in and external line counts are retained; code and saved outputs are never returned.
Expand Down
37 changes: 21 additions & 16 deletions detect/detect.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"github.com/BurntSushi/toml"
"github.com/git-pkgs/brief"
"github.com/git-pkgs/brief/kb"
"github.com/git-pkgs/gitignore"
"github.com/git-pkgs/licenses"
"github.com/git-pkgs/manifests"
"github.com/git-pkgs/purl"
Expand Down Expand Up @@ -80,8 +81,10 @@ type Engine struct {
detectedEcosystems map[string]bool // ecosystems whose language was detected

// Lazily populated caches
tracked map[string]bool // git-tracked files relative to Root, nil when TrackedOnly is off
tracked map[string]bool // git-tracked files relative to Root
trackedDirs map[string]bool // directories that contain at least one tracked file
ignoreMatchers map[string]*gitignore.Matcher
ignoreTrackedLoaded bool
trackedDeps map[string]bool // whether a deps directory contains git-tracked files
fileExts map[string]int // cached file extension counts in the project
fileRoles map[string]roles.Set
Expand Down Expand Up @@ -231,7 +234,7 @@ func (e *Engine) addTrackedFiles(prefix string, output []byte) {
// isTracked reports whether a path relative to Root should be considered.
// Always true when TrackedOnly is off. The root itself is always allowed.
func (e *Engine) isTracked(rel string) bool {
if e.tracked == nil {
if !e.TrackedOnly || e.tracked == nil {
return true
}
if rel == "" || rel == "." {
Expand Down Expand Up @@ -442,7 +445,7 @@ func (e *Engine) validateOptions() error {
const selfModulePath = "github.com/git-pkgs/brief"

func (e *Engine) detectSelf(report *brief.Report) {
data, err := e.safeReadFile("go.mod")
data, err := e.readEvidenceFile("go.mod")
if err != nil {
return
}
Expand Down Expand Up @@ -689,7 +692,7 @@ func (e *Engine) exists(pattern string) bool {
continue
}
info, err := fs.Stat(e.projectFS(), filepath.ToSlash(candidate))
if err == nil && info.IsDir() && e.isTracked(candidate) {
if err == nil && info.IsDir() && e.isTracked(candidate) && !e.ignoredProjectPath(candidate, true) {
return true
}
}
Expand All @@ -713,7 +716,8 @@ func (e *Engine) exactFileExists(file string) bool {
return false
}
info, err := fs.Stat(e.projectFS(), filepath.ToSlash(file))
return err == nil && info.Mode().IsRegular() && e.isTracked(filepath.FromSlash(file))
return err == nil && info.Mode().IsRegular() &&
e.isTracked(filepath.FromSlash(file)) && !e.ignoredProjectPath(file, false)
}

func (e *Engine) rootCandidates(file string) []string {
Expand Down Expand Up @@ -794,6 +798,7 @@ func (e *Engine) scanProjectDir(dirPath, relDir string, visited *int, routeOnly
return false
}
defer func() { _ = file.Close() }()
e.loadIgnoreRules(relDir)
dir, ok := file.(fs.ReadDirFile)
if !ok {
entries, err := fs.ReadDir(e.projectFS(), baseOrDot(filepath.ToSlash(relDir)))
Expand Down Expand Up @@ -847,7 +852,7 @@ func (e *Engine) scanProjectEntry(
return false
}
if !entry.IsDir() {
if entry.Type().IsRegular() && e.isTracked(rel) {
if entry.Type().IsRegular() && e.isTracked(rel) && !e.ignoredProjectPath(rel, false) {
e.fileRoles[rel] = e.pathRoles(rel)
e.indexedFiles = append(e.indexedFiles, rel)
if !routeOnly && e.projectEvidence(rel) {
Expand All @@ -872,7 +877,7 @@ func (e *Engine) scanProjectEntry(
}
nextRouteOnly = true
}
if !e.isTracked(rel) {
if !e.isTracked(rel) || e.ignoredProjectPath(rel, true) {
return false
}
if e.ScanDepth > 0 && pathDepth(rel) > e.ScanDepth {
Expand Down Expand Up @@ -969,7 +974,7 @@ func (e *Engine) contains(file string, patterns []string) bool {
}

for _, candidate := range files {
data, err := e.safeReadFile(candidate)
data, err := e.readEvidenceFile(candidate)
if err == nil && containsAny(string(data), patterns) {
return true
}
Expand Down Expand Up @@ -1049,7 +1054,7 @@ func (e *Engine) loadDeps() {
manifestPaths := e.manifestPaths()

for _, mf := range manifestPaths {
data, err := e.safeReadFile(mf)
data, err := e.readEvidenceFile(mf)
if err != nil {
continue
}
Expand Down Expand Up @@ -1187,7 +1192,7 @@ func (e *Engine) manifestPaths() []string {
}

func (e *Engine) addCargoWorkspaceManifestsFrom(cargoRoot string, add func(string)) {
data, err := e.safeReadFile(path.Join(cargoRoot, cargoManifestFile))
data, err := e.readEvidenceFile(path.Join(cargoRoot, cargoManifestFile))
if err != nil {
return
}
Expand Down Expand Up @@ -1274,7 +1279,7 @@ func baseOrDot(base string) string {
}

func (e *Engine) addGoWorkspaceManifestsFrom(base string, add func(string)) {
data, err := e.safeReadFile(path.Join(filepath.ToSlash(base), "go.work"))
data, err := e.readEvidenceFile(path.Join(filepath.ToSlash(base), "go.work"))
if err != nil {
return
}
Expand All @@ -1286,7 +1291,7 @@ func (e *Engine) addGoWorkspaceManifestsFrom(base string, add func(string)) {
}

func (e *Engine) addPackageWorkspaceManifestsFrom(base string, add func(string)) {
data, err := e.safeReadFile(path.Join(filepath.ToSlash(base), "package.json"))
data, err := e.readEvidenceFile(path.Join(filepath.ToSlash(base), "package.json"))
if err != nil {
return
}
Expand All @@ -1305,7 +1310,7 @@ func (e *Engine) addPackageWorkspaceManifestsFrom(base string, add func(string))
}

func (e *Engine) addPnpmWorkspaceManifestsFrom(base string, add func(string)) {
data, err := e.safeReadFile(path.Join(filepath.ToSlash(base), "pnpm-workspace.yaml"))
data, err := e.readEvidenceFile(path.Join(filepath.ToSlash(base), "pnpm-workspace.yaml"))
if err != nil {
return
}
Expand Down Expand Up @@ -1482,7 +1487,7 @@ func dependencyKey(ecosystem, name string) string {
// dot-separated key paths (e.g. "scripts.test" in package.json).
func (e *Engine) hasKey(file string, keys []string) bool {
for _, candidate := range e.rootCandidates(file) {
data, err := e.safeReadFile(candidate)
data, err := e.readEvidenceFile(candidate)
if err != nil {
continue
}
Expand Down Expand Up @@ -1559,7 +1564,7 @@ func (e *Engine) detectScripts() []brief.Script {
if !e.isTracked(filepath.FromSlash(src.Source.File)) {
continue
}
data, err := e.safeReadFile(src.Source.File)
data, err := e.readEvidenceFile(src.Source.File)
if err != nil {
continue
}
Expand Down Expand Up @@ -2147,7 +2152,7 @@ func (e *Engine) detectPlatforms() *brief.PlatformInfo {

for _, rt := range e.KB.Runtimes {
for _, file := range rt.Runtime.Files {
data, err := e.safeReadFile(file)
data, err := e.readEvidenceFile(file)
if err != nil {
continue
}
Expand Down
1 change: 1 addition & 0 deletions detect/detect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1985,6 +1985,7 @@ func TestTrackedOnlyIgnoresDepthOfUntrackedDirectories(t *testing.T) {

engine := New(loadKB(t), dir)
engine.ScanDepth = 1
engine.TrackedOnly = true
engine.tracked = map[string]bool{filepath.Join("one", "tracked.go"): true}
engine.trackedDirs = map[string]bool{"one": true}
engine.loadProjectFiles()
Expand Down
81 changes: 81 additions & 0 deletions detect/ignores.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package detect

import (
"io/fs"
"os"
"path/filepath"

"github.com/git-pkgs/gitignore"
)

const ignoreFileSizeLimit = 1 << 20

// loadIgnoreRules reads rules when the bounded scan reaches their directory.
// Each included submodule uses its own matcher, like a separate checkout.
func (e *Engine) loadIgnoreRules(dir string) {
if e.TrackedOnly {
return
}
file := filepath.Join(dir, ".gitignore")
var info fs.FileInfo
var err error
if e.fsOnly {
info, err = fs.Lstat(e.fsys, filepath.ToSlash(file))
} else {
info, err = os.Lstat(filepath.Join(e.Root, file))
}
if err != nil || !info.Mode().IsRegular() || info.Size() > ignoreFileSizeLimit {
return
}
data, err := e.safeReadFileLimit(file, ignoreFileSizeLimit+1)
if err != nil || len(data) == 0 || len(data) > ignoreFileSizeLimit {
return
}
root := e.analysisRootFor(dir)
local := e.pathAtAnalysisRoot(dir)
if local == "." {
local = ""
}
if e.ignoreMatchers == nil {
e.ignoreMatchers = make(map[string]*gitignore.Matcher)
}
matcher := e.ignoreMatchers[root]
if matcher == nil {
matcher = gitignore.New("")
e.ignoreMatchers[root] = matcher
}
matcher.AddPatterns(data, filepath.ToSlash(local))
}

func (e *Engine) ignoredProjectPath(rel string, isDir bool) bool {
if e.TrackedOnly {
return false
}
e.loadProjectFiles()
rel = filepath.Clean(rel)
matcher := e.ignoreMatchers[e.analysisRootFor(rel)]
if matcher == nil || !matcher.MatchPath(filepath.ToSlash(e.pathAtAnalysisRoot(rel)), isDir) {
return false
}
if e.fsOnly {
return true
}

// A tracked file remains visible even if its name matches an ignore rule.
// Only consult the index once a matching rule makes it necessary.
if !e.ignoreTrackedLoaded {
e.ignoreTrackedLoaded = true
_ = e.loadTracked(e.Root)
}
if isDir {
return !e.trackedDirs[rel] && !e.tracked[rel]
}
return !e.tracked[rel]
}

func (e *Engine) readEvidenceFile(file string) ([]byte, error) {
if e.ignoredProjectPath(file, false) {
return nil, fs.ErrNotExist
}
return e.safeReadFile(file)
}
82 changes: 82 additions & 0 deletions detect/ignores_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package detect

import (
"os"
"os/exec"
"path/filepath"
"slices"
"testing"
"testing/fstest"

"github.com/git-pkgs/brief"
)

func TestGitignoreKeepsTrackedAndNewProjectFiles(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git unavailable")
}
root := t.TempDir()
files := map[string]string{
".gitignore": "/scratch/\n/package.json\n/Makefile\n",
"scratch/pinned.go": "package project\n",
"scratch/foreign.rb": "puts 'scratch'\n",
"new.py": "print('new source')\n",
"package.json": `{"scripts":{"test":"echo scratch"},"devDependencies":{"eslint":"9.0.0"}}`,
"Makefile": "all:\n\techo scratch\n",
}
for name, data := range files {
file := filepath.Join(root, name)
if err := os.MkdirAll(filepath.Dir(file), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(file, []byte(data), 0644); err != nil {
t.Fatal(err)
}
}
gitFixtureCommand(t, root, "init", "-q")
gitFixtureCommand(t, root, "add", "-f", "scratch/pinned.go")

for _, trackedOnly := range []bool{false, true} {
engine := New(loadKB(t), root)
engine.TrackedOnly = trackedOnly
report, err := engine.Run()
if err != nil {
t.Fatal(err)
}
hasLanguage := func(name string) bool {
return slices.ContainsFunc(report.Languages, func(item brief.Detection) bool { return item.Name == name })
}
if !hasLanguage("Go") || hasLanguage("Ruby") || hasLanguage("JavaScript") || hasLanguage("Python") == trackedOnly {
t.Errorf("tracked=%t: incorrect language evidence: %v", trackedOnly, report.Languages)
}
if !trackedOnly && (len(report.Scripts) > 0 || len(report.Dependencies) > 0 || len(report.Manifests) > 0) {
t.Errorf("ignored exact paths leaked into the report: %v %v %v", report.Scripts, report.Dependencies, report.Manifests)
}
if !trackedOnly && (engine.contains("Makefile", []string{"echo scratch"}) || engine.hasKey("package.json", []string{"scripts.test"})) {
t.Error("ignored exact paths provided configuration evidence")
}
}
}

func TestGitignoreNestedRulesAndDirectoryPruning(t *testing.T) {
tree := fstest.MapFS{
".gitignore": {Data: []byte("/scratch/\n*.rb\n")},
"main.go": {Data: []byte("package project\n")},
"scratch/one.java": {},
"scratch/two.java": {},
"scratch/three.java": {},
"src/.gitignore": {Data: []byte("!allow.rb\n")},
"src/allow.rb": {},
"src/other.rb": {},
"tools/allow.rb": {},
}
engine := NewFS(loadKB(t), tree)
engine.ScanLimit = 10
engine.loadProjectFiles()
if !slices.Equal(engine.projectFiles, []string{".gitignore", "main.go", filepath.Join("src", ".gitignore"), filepath.Join("src", "allow.rb")}) {
t.Errorf("unexpected project files: %v", engine.projectFiles)
}
if engine.scanTruncated || engine.scanEntries != 9 {
t.Errorf("ignored directory consumed its children's scan budget: entries=%d truncated=%t", engine.scanEntries, engine.scanTruncated)
}
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ require (
github.com/git-pkgs/codemeta v0.3.0
github.com/git-pkgs/enrichment v0.7.5
github.com/git-pkgs/forge v0.11.0
github.com/git-pkgs/gitignore v1.3.0
github.com/git-pkgs/licenses v0.10.1-0.20261107154534-00c5bf03ade8
github.com/git-pkgs/magic v0.6.0
github.com/git-pkgs/manifests v0.14.0
Expand All @@ -31,7 +32,6 @@ require (
github.com/bazelbuild/buildtools v0.0.0-20260904073137-eaa4d125b423 // indirect
github.com/bmatcuk/doublestar/v4 v4.10.4 // indirect
github.com/ecosyste-ms/ecosystems-go v0.5.0 // indirect
github.com/git-pkgs/gitignore v1.3.0 // indirect
github.com/git-pkgs/pom v0.1.8 // indirect
github.com/git-pkgs/spdx v0.3.6 // indirect
github.com/git-pkgs/vers v0.7.2 // indirect
Expand Down
Loading