Ensure errors are handled or logged
if err != nil {
1// SPDX-License-Identifier: MIT23package processor45import (6 "context"7 "errors"8 "fmt"9 "io"10 "strings"11 "time"1213 "github.com/go-git/go-git/v5/plumbing"14 "github.com/go-git/go-git/v5/plumbing/filemode"15 fdiff "github.com/go-git/go-git/v5/plumbing/format/diff"16 "github.com/go-git/go-git/v5/plumbing/object"17 "github.com/go-git/go-git/v5/utils/merkletrie"18)1920// HistoryDepth is the maximum number of commits the history engine walks. 021// means "entire history". Wired to --depth in main.go.22var HistoryDepth = 10002324// LineRange is a half-open line span [Start, Start+Count) in 1-based line25// numbers. A FileChange carries one entry per contiguous run of added (or26// removed) lines emitted by go-git's diff.27type LineRange struct {28 Start int29 Count int30}3132// CommitInfo is the per-commit metadata handed to observers.33type CommitInfo struct {34 Hash plumbing.Hash35 Author string36 Email string37 When time.Time38}3940// FileChange is one changed file inside a commit. AddedRanges/RemovedRanges41// describe the diff against the first parent; LineTypes and Complexity are42// scc's classifier output for the new blob (one LineType per line, one entry43// in Complexity per line that fired a complexity tick).44type FileChange struct {45 Path string46 FromPath string // != Path on a detected rename; "" on a pure add47 Language string48 AddedRanges []LineRange49 RemovedRanges []LineRange50 LineTypes []LineType51 RemovedLineTypes []LineType // old-blob line types, for code-filtered removals52 Complexity []int53 NewBlob []byte54}5556// CommitObserver is implemented by each report's accumulator. The engine57// invokes Observe once per commit oldest-first, then Finalise once with the58// window metadata and a snapshot of the HEAD tree (latest language /59// complexity per surviving file).60type CommitObserver interface {61 Observe(c CommitInfo, changes []FileChange)62 Finalise(window HistoryWindow, head HeadSnapshot)63}6465// HistoryWindow describes the commit window the engine walked.66type HistoryWindow struct {67 Depth int68 Commits int69 From time.Time70 To time.Time71 Head plumbing.Hash72}7374// HeadFile is one file in the HEAD tree, classified by scc's engine.75type HeadFile struct {76 Path string77 Language string78 Complexity int6479 Cognitive int64 // nesting-weighted complexity; zero unless the Cognitive global is on80}8182// HeadSnapshot is the set of files in HEAD, keyed by path.83type HeadSnapshot struct {84 Files map[string]HeadFile85}8687// BaselineFile is one file from the window's start-commit tree, classified by88// scc's engine. Carries per-line type and complexity placement so observers89// can attribute lines that survive untouched from before the window.90type BaselineFile struct {91 Path string92 Language string93 LineTypes []LineType94 Complexity []int // 1-based line numbers that fired a complexity tick95}9697// BaselineSnapshot is the optional pre-walk state handed to observers that98// implement BaselineObserver. Files holds the classified contents of the99// window's start-commit tree (empty when the window covers all history);100// Mailmap is the parsed .mailmap from the HEAD tree, if present.101type BaselineSnapshot struct {102 Files map[string]BaselineFile103 Mailmap *mailmap104}105106// BaselineObserver is an optional extension to CommitObserver. When an107// observer implements it, the engine builds the baseline snapshot before the108// walk and calls Seed once. Observers that don't need the baseline (e.g.109// Hotspots) skip the expense by not implementing the interface.110type BaselineObserver interface {111 Seed(BaselineSnapshot)112}113114// MailmapObserver is an optional extension to CommitObserver. The engine115// always parses the repo's .mailmap from HEAD — one small blob — and hands116// it to observers that implement this, before the walk. Unlike117// BaselineObserver it does NOT trigger the expensive start-tree118// classification, so observers that only need author folding (e.g. Hotspots,119// the author timeline) can implement it cheaply.120type MailmapObserver interface {121 SetMailmap(*mailmap)122}123124// Bucketing divides [From, To] into N equal time slices. Used by the timeline125// reports (plans 04 and 05) to map per-commit timestamps to a fixed-resolution126// per-bucket series independent of terminal width.127type Bucketing struct {128 From time.Time129 To time.Time130 N int131 Width time.Duration132}133134// NewBucketing constructs a Bucketing covering [from, to] divided into n135// equal-width slices. n must be > 0; n <= 0 is normalised to 1 so callers can136// pass user input unchecked. A degenerate window (from == to or to before137// from) yields Width=0; all commits land in bucket 0 / N-1.138func NewBucketing(from, to time.Time, n int) Bucketing {139 if n <= 0 {140 n = 1141 }142 b := Bucketing{From: from, To: to, N: n}143 if to.After(from) {144 b.Width = to.Sub(from) / time.Duration(n)145 }146 return b147}148149// Index returns the 0..N-1 bucket slot for commit time t. Times before From150// clamp to 0 (defensive — should not happen given the walk window). Times at151// or after To clamp to N-1.152func (b Bucketing) Index(t time.Time) int {153 if b.N <= 0 {154 return 0155 }156 if b.Width <= 0 {157 return 0158 }159 if !t.After(b.From) {160 return 0161 }162 if !t.Before(b.To) {163 return b.N - 1164 }165 idx := int(t.Sub(b.From) / b.Width)166 if idx < 0 {167 return 0168 }169 if idx >= b.N {170 return b.N - 1171 }172 return idx173}174175// Start returns the wall-clock start time of bucket i. Indexes outside176// [0, N) are clamped.177func (b Bucketing) Start(i int) time.Time {178 if b.N <= 0 {179 return b.From180 }181 if i <= 0 {182 return b.From183 }184 if i >= b.N {185 i = b.N - 1186 }187 return b.From.Add(time.Duration(i) * b.Width)188}189190// emptySnapshot is what observers see when HEAD is missing or empty.191func emptySnapshot() HeadSnapshot {192 return HeadSnapshot{Files: map[string]HeadFile{}}193}194195// runHistory opens the repo at repoPath, walks up to HistoryDepth commits196// (newest first → oldest first), and feeds every commit's first-parent diff197// to the observer.198func runHistory(repoPath string, observer CommitObserver) (HistoryWindow, error) {199 // Turn GC back on because we have no idea how much we are about to process200 EnableGc()201202 repo, err := openRepository(repoPath)203 if err != nil {204 return HistoryWindow{}, fmt.Errorf("open git repository: %w", err)205 }206207 head, err := repo.Head()208 if err != nil {209 // An unborn HEAD (freshly initialised, no commits yet) and a HEAD we210 // simply could not resolve are the same error here, and there is no211 // signal to tell them apart: both are a symbolic HEAD naming a ref212 // that does not exist. So say what we actually know rather than213 // guess. The warning is verbose-gated like every other one, so this214 // does not shout at someone pointing a report at an empty repo — it215 // means the next resolution failure of this shape can be diagnosed216 // with --verbose instead of only looking like an empty table. That217 // silence is what made the worktree case (issue #765) hard to spot.218 if errors.Is(err, plumbing.ErrReferenceNotFound) {219 printWarnF("history: cannot resolve HEAD in %s, treating as an empty repository", repoPath)220 observer.Finalise(HistoryWindow{}, emptySnapshot())221 return HistoryWindow{}, nil222 }223 return HistoryWindow{}, fmt.Errorf("read HEAD: %w", err)224 }225226 // Walk the first-parent chain only. repo.Log visits every commit reachable227 // from HEAD, but commitChanges diffs each commit against its first parent,228 // so a merged branch's work was observed once on the branch and again229 // through the merge's first-parent diff (issue #783). Following230 // ParentHashes[0] matches the README's `git log --first-parent` semantics231 // and keeps every diff applied to the state it was computed against.232 collected := make([]*object.Commit, 0)233 commit, err := repo.CommitObject(head.Hash())234 if err != nil {235 return HistoryWindow{}, fmt.Errorf("walk log: %w", err)236 }237 for {238 var parent *object.Commit239 if commit.NumParents() > 0 {240 parent, err = commit.Parent(0)241 // A shallow clone (e.g. CI's default `git checkout --depth 1`)242 // stores a parent hash for its oldest commit but not the parent243 // object itself. That boundary commit cannot be diffed against its244 // missing parent, so stop before observing it and keep what we245 // walked. This is the same "no more history to walk" endpoint as a246 // root commit's zero parents, reached via a missing object instead.247 if errors.Is(err, plumbing.ErrObjectNotFound) {248 break249 }250 if err != nil {251 return HistoryWindow{}, fmt.Errorf("collect commits: %w", err)252 }253 }254 collected = append(collected, commit)255 if HistoryDepth > 0 && len(collected) >= HistoryDepth {256 break257 }258 if parent == nil {259 break260 }261 commit = parent262 }263264 if len(collected) == 0 {265 observer.Finalise(HistoryWindow{Head: head.Hash()}, emptySnapshot())266 return HistoryWindow{Head: head.Hash()}, nil267 }268269 window := HistoryWindow{270 Depth: HistoryDepth,271 Commits: len(collected),272 From: collected[len(collected)-1].Author.When,273 To: collected[0].Author.When,274 Head: head.Hash(),275 }276277 ignore, err := buildHistoryIgnore(repo, head.Hash())278 if err != nil {279 printWarnF("history: ignore matcher: %s", err)280 }281282 cache := newBlobClassifyCache()283284 if mo, ok := observer.(MailmapObserver); ok {285 mo.SetMailmap(loadMailmapForHead(collected[0]))286 }287288 if bo, ok := observer.(BaselineObserver); ok {289 baseline := buildBaselineForObserver(collected, ignore, cache)290 bo.Seed(baseline)291 }292293 ctx := context.Background()294 for i := len(collected) - 1; i >= 0; i-- {295 commit := collected[i]296 changes, err := commitChanges(ctx, commit, ignore, cache)297 if err != nil {298 printWarnF("history: diff %s: %s", commit.Hash, err)299 continue300 }301 observer.Observe(CommitInfo{302 Hash: commit.Hash,303 Author: commit.Author.Name,304 Email: commit.Author.Email,305 When: commit.Author.When,306 }, changes)307 }308309 snapshot, err := buildHeadSnapshot(collected[0], ignore, cache)310 if err != nil {311 printWarnF("history: head snapshot: %s", err)312 snapshot = emptySnapshot()313 }314315 observer.Finalise(window, snapshot)316 return window, nil317}318319// loadMailmapForHead parses .mailmap from the HEAD commit's tree. Returns320// nil when there is no .mailmap or the HEAD tree cannot be read. Cheap321// compared to building the full baseline, so observers that only need322// author folding (Hotspots, author timeline) can satisfy MailmapObserver323// without paying for the start-tree classification.324func loadMailmapForHead(headCommit *object.Commit) *mailmap {325 if headCommit == nil {326 return nil327 }328 tree, err := headCommit.Tree()329 if err != nil {330 return nil331 }332 return loadMailmapFromTree(tree)333}334335// buildBaselineForObserver loads the mailmap from HEAD and classifies the336// tree at the window's start commit. The start commit is the first-parent of337// the oldest commit in the window; if that commit has no parents (the window338// covers all history) the baseline files map is empty.339func buildBaselineForObserver(collected []*object.Commit, ignore *historyIgnore, cache *blobClassifyCache) (baseline BaselineSnapshot) {340 baseline = BaselineSnapshot{Files: map[string]BaselineFile{}}341 // Backstop for panics outside the per-file recover below — go-git's342 // tree.Files() iterator can itself panic on a corrupt object, and the343 // per-file handler is not in scope for that. Return whatever was344 // accumulated so far rather than crashing the report.345 defer func() {346 if r := recover(); r != nil {347 printWarnF("history: baseline walk panicked, using partial result: %v", r)348 }349 }()350 if len(collected) == 0 {351 return baseline352 }353354 baseline.Mailmap = loadMailmapForHead(collected[0])355356 oldest := collected[len(collected)-1]357 if oldest.NumParents() == 0 {358 return baseline359 }360 parent, err := oldest.Parent(0)361 if err != nil {362 printWarnF("history: baseline parent: %s", err)363 return baseline364 }365 tree, err := parent.Tree()366 if err != nil {367 printWarnF("history: baseline tree: %s", err)368 return baseline369 }370371 _ = tree.Files().ForEach(func(f *object.File) error {372 defer func() {373 if r := recover(); r != nil {374 name := "<unknown>"375 if f != nil {376 name = f.Name377 }378 printWarnF("history: skipping %s in baseline — panicked: %v", name, r)379 }380 }()381 if f.Mode == filemode.Dir || f.Mode == filemode.Submodule || f.Mode == filemode.Symlink {382 return nil383 }384 if ignore.Skip(f.Name) {385 return nil386 }387 reader, err := f.Reader()388 if err != nil {389 return nil390 }391 defer reader.Close()392 blob, err := io.ReadAll(reader)393 if err != nil {394 return nil395 }396 res := cache.classify(f.Hash, f.Name, blob)397 if !res.ok {398 return nil399 }400 baseline.Files[f.Name] = BaselineFile{401 Path: f.Name,402 Language: res.language,403 LineTypes: res.lineTypes,404 Complexity: res.complexLine,405 }406 return nil407 })408409 return baseline410}411412// buildHeadSnapshot walks the HEAD commit's tree and runs scc's classifier413// on each file. Used by hotspots (and future reports) to know each surviving414// file's current language and complexity.415func buildHeadSnapshot(headCommit *object.Commit, ignore *historyIgnore, cache *blobClassifyCache) (snap HeadSnapshot, err error) {416 snap = emptySnapshot()417 // Backstop for panics outside the per-file recover below — go-git's418 // tree.Files() iterator can itself panic on a corrupt object. Return the419 // partial snapshot with no error so the caller keeps what we collected.420 defer func() {421 if r := recover(); r != nil {422 printWarnF("history: HEAD snapshot walk panicked, using partial result: %v", r)423 err = nil424 }425 }()426427 tree, err := headCommit.Tree()428 if err != nil {429 return emptySnapshot(), err430 }431432 snap = HeadSnapshot{Files: map[string]HeadFile{}}433 err = tree.Files().ForEach(func(f *object.File) error {434 defer func() {435 if r := recover(); r != nil {436 name := "<unknown>"437 if f != nil {438 name = f.Name439 }440 printWarnF("history: skipping %s in HEAD snapshot — panicked: %v", name, r)441 }442 }()443 if f.Mode == filemode.Dir || f.Mode == filemode.Submodule || f.Mode == filemode.Symlink {444 return nil445 }446 if ignore.Skip(f.Name) {447 return nil448 }449 reader, err := f.Reader()450 if err != nil {451 return nil452 }453 defer reader.Close()454 blob, err := io.ReadAll(reader)455 if err != nil {456 return nil457 }458459 res := cache.classify(f.Hash, f.Name, blob)460 if !res.ok {461 return nil462 }463464 snap.Files[f.Name] = HeadFile{465 Path: f.Name,466 Language: res.language,467 Complexity: res.complexity,468 Cognitive: res.cognitive,469 }470 return nil471 })472 return snap, err473}474475// historyDiffOptions forces rename detection on. The rename-aware reports476// (author rollup, hotspots) depend on renames arriving as a single change477// rather than a delete + add pair, so pin it explicitly — a future go-git478// bump can't silently disable it.479var historyDiffOptions = &object.DiffTreeOptions{DetectRenames: true}480481// commitChanges computes the first-parent diff for commit and projects every482// change into a FileChange. Skips paths that the engine can't count483// (binary blobs, no language detected, submodules, symlinks, ignored paths).484// Deletes are dropped because hotspots-style reports can't render files that485// no longer exist.486//487// The outer recover catches anything the per-call wrappers don't (corrupt488// packfiles via go-git object resolution, future regressions in the diff489// pipeline). One bad commit becomes a warning, not a crash.490func commitChanges(ctx context.Context, commit *object.Commit, ignore *historyIgnore, cache *blobClassifyCache) (out []FileChange, err error) {491 defer func() {492 if r := recover(); r != nil {493 printWarnF("history: skipping commit %s — diff pipeline panicked: %v", commit.Hash, r)494 out = nil495 err = nil496 }497 }()498499 toTree, err := commit.Tree()500 if err != nil {501 return nil, err502 }503504 var fromTree *object.Tree505 if commit.NumParents() > 0 {506 parent, err := commit.Parent(0)507 // A shallow-clone boundary commit carries a parent hash whose object is508 // absent. Treat the missing parent as no parent (leave fromTree nil, so509 // the commit diffs against the empty tree) instead of failing — the510 // same end-of-history handling as commits with zero parents.511 if errors.Is(err, plumbing.ErrObjectNotFound) {512 return nil, nil513 }514 if err != nil {515 return nil, err516 }517 fromTree, err = parent.Tree()518 if errors.Is(err, plumbing.ErrObjectNotFound) {519 return nil, nil520 }521 if err != nil {522 return nil, err523 }524 }525526 changes, err := object.DiffTreeWithOptions(ctx, fromTree, toTree, historyDiffOptions)527 if err != nil {528 return nil, err529 }530531 out = make([]FileChange, 0, len(changes))532 for _, change := range changes {533 fc, ok := buildFileChange(change, ignore, cache)534 if !ok {535 continue536 }537 out = append(out, fc)538 }539 return out, nil540}541542// buildFileChange converts a single object.Change into a FileChange.543func buildFileChange(change *object.Change, ignore *historyIgnore, cache *blobClassifyCache) (FileChange, bool) {544 action, err := change.Action()545 if err != nil {546 return FileChange{}, false547 }548 if action == merkletrie.Delete {549 return FileChange{}, false550 }551552 path := change.To.Name553 fromPath := change.From.Name554 toEntry := change.To.TreeEntry555 if toEntry.Mode == filemode.Dir || toEntry.Mode == filemode.Submodule || toEntry.Mode == filemode.Symlink {556 return FileChange{}, false557 }558559 if ignore.Skip(path) {560 return FileChange{}, false561 }562563 languages, _ := DetectLanguage(path)564 if len(languages) == 0 {565 return FileChange{}, false566 }567568 patch, ok := safePatch(change)569 if !ok {570 return FileChange{}, false571 }572573 var added, removed []LineRange574 for _, fp := range patch.FilePatches() {575 if fp.IsBinary() {576 return FileChange{}, false577 }578 toLine, fromLine := 1, 1579 for _, chunk := range fp.Chunks() {580 lines := lineCount(chunk.Content())581 switch chunk.Type() {582 case fdiff.Equal:583 toLine += lines584 fromLine += lines585 case fdiff.Add:586 if lines > 0 {587 added = append(added, LineRange{Start: toLine, Count: lines})588 }589 toLine += lines590 case fdiff.Delete:591 if lines > 0 {592 removed = append(removed, LineRange{Start: fromLine, Count: lines})593 }594 fromLine += lines595 }596 }597 }598599 blob, err := readBlob(change.To.Tree, &toEntry)600 if err != nil {601 return FileChange{}, false602 }603604 res := cache.classify(toEntry.Hash, path, blob)605 if !res.ok {606 return FileChange{}, false607 }608609 // Classify the parent blob so removed lines can be filtered to code —610 // the timeline reports need a symmetric code-only delta. The blob cache611 // makes this near-free: the old blob is normally an earlier commit's612 // new blob. Skip entirely when there are no removals (pure adds, or613 // when the diff produced no removed ranges).614 var removedLineTypes []LineType615 if len(removed) > 0 && change.From.Name != "" {616 fromEntry := change.From.TreeEntry617 if fromEntry.Mode != filemode.Dir &&618 fromEntry.Mode != filemode.Submodule &&619 fromEntry.Mode != filemode.Symlink {620 if oldBlob, rerr := readBlob(change.From.Tree, &fromEntry); rerr == nil {621 if oldRes := cache.classify(fromEntry.Hash, change.From.Name, oldBlob); oldRes.ok {622 removedLineTypes = oldRes.lineTypes623 }624 }625 }626 }627628 return FileChange{629 Path: path,630 FromPath: fromPath,631 Language: res.language,632 AddedRanges: added,633 RemovedRanges: removed,634 LineTypes: res.lineTypes,635 RemovedLineTypes: removedLineTypes,636 Complexity: res.complexLine,637 NewBlob: blob,638 }, true639}640641// safePatch wraps change.Patch() with panic recovery. The underlying642// sergi/go-diff line-to-rune encoding panics when a file has more distinct643// lines than fit in the Unicode code-point space (generated SQL, huge644// minified bundles, vendored data files). Treat any panic or error as645// "skip this file" so one bad file does not abort the whole report.646func safePatch(change *object.Change) (patch *object.Patch, ok bool) {647 defer func() {648 if r := recover(); r != nil {649 path := ""650 if change != nil {651 path = change.To.Name652 if path == "" {653 path = change.From.Name654 }655 }656 printWarnF("history: skipping %s — diff library panicked: %v", path, r)657 patch = nil658 ok = false659 }660 }()661 p, err := change.Patch()662 if err != nil {663 return nil, false664 }665 return p, true666}667668// classifyFn is the indirect reference to classifyHistoryBlob used by669// safeClassify. Tests substitute a panicking stub to exercise the recover670// path; production behaviour is unchanged.671var classifyFn = classifyHistoryBlob672673// safeClassify wraps the classifier with panic recovery. The history walk674// feeds the classifier many more blob shapes than the working-tree counter675// ever sees (legacy encodings, partial UTF-8, oversized blobs, vendored676// data). A panic in any one path-blob pair must not abort the report —677// skip the file with a warning instead.678func safeClassify(path string, blob []byte) (job *FileJob, lineTypes []LineType, ok bool) {679 defer func() {680 if r := recover(); r != nil {681 printWarnF("history: skipping %s — classifier panicked: %v", path, r)682 job = nil683 lineTypes = nil684 ok = false685 }686 }()687 return classifyFn(path, blob)688}689690// readBlob fetches the raw bytes for a tree entry.691func readBlob(tree *object.Tree, entry *object.TreeEntry) ([]byte, error) {692 file, err := tree.TreeEntryFile(entry)693 if err != nil {694 return nil, err695 }696 reader, err := file.Reader()697 if err != nil {698 return nil, err699 }700 defer reader.Close()701 return io.ReadAll(reader)702}703704// blobClassifyResult is the cached output of classifyHistoryBlob for a single705// blob hash. ok=false means the classifier rejected the blob (binary, no706// language); the vectors are nil in that case.707type blobClassifyResult struct {708 language string709 complexity int64710 cognitive int64 // nesting-weighted complexity; zero unless the Cognitive global is on711 lineTypes []LineType712 complexLine []int713 cognitiveLine []int // 1-based lines that accrued cognitive weight; nil unless Cognitive is on714 ok bool715}716717// blobClassifyCache memoises classifyHistoryBlob output keyed by blob hash so718// the same blob seen in baseline, commit changes, and HEAD is classified once719// per runHistory. The walk is sequential, so no mutex is required.720type blobClassifyCache struct {721 entries map[plumbing.Hash]blobClassifyResult722}723724func newBlobClassifyCache() *blobClassifyCache {725 return &blobClassifyCache{entries: make(map[plumbing.Hash]blobClassifyResult)}726}727728// classify returns the classifier output for blob, computing and caching it729// on first sight. Slices in the returned result are shared between callers —730// they must be treated as read-only. Negative results (ok=false) are cached731// too so binary/unknown blobs aren't re-attempted.732func (c *blobClassifyCache) classify(hash plumbing.Hash, path string, blob []byte) blobClassifyResult {733 if c != nil {734 if hit, found := c.entries[hash]; found {735 return hit736 }737 }738 job, lineTypes, ok := safeClassify(path, blob)739 res := blobClassifyResult{ok: ok}740 if ok {741 res.language = job.Language742 res.complexity = job.Complexity743 res.cognitive = job.Cognitive744 res.lineTypes = lineTypes745 res.complexLine = complexityLineNumbers(job)746 res.cognitiveLine = cognitiveLineNumbers(job)747 }748 if c != nil {749 c.entries[hash] = res750 }751 return res752}753754// classifyHistoryBlob runs scc's existing classifier on a git blob's bytes755// and returns the resulting FileJob (Language / Complexity / Code / Comment756// / Blank populated) plus the per-line type vector. ok=false means the file757// is binary or the language could not be resolved.758func classifyHistoryBlob(path string, blob []byte) (*FileJob, []LineType, bool) {759 languages, extension := DetectLanguage(path)760 if len(languages) == 0 {761 return nil, nil, false762 }763 for _, l := range languages {764 LoadLanguageFeature(l)765 }766767 job := &FileJob{768 Location: path,769 Filename: basename(path),770 Extension: extension,771 PossibleLanguages: languages,772 Bytes: int64(len(blob)),773 Content: blob,774 TrackComplexityLines: true,775 }776777 job.Language = DetermineLanguage(job.Filename, job.Language, job.PossibleLanguages, job.Content)778 if job.Language == SheBang {779 cutoff := min(len(blob), 200)780 lang, err := DetectSheBang(blob[:cutoff])781 if err != nil {782 return nil, nil, false783 }784 job.Language = lang785 LoadLanguageFeature(lang)786 }787788 classifier := &historyLineCallback{}789 job.Callback = classifier790791 CountStats(job)792793 if job.Binary {794 return nil, nil, false795 }796797 return job, classifier.lineTypes, true798}799800// complexityLineNumbers returns the 1-based line numbers in job that fired a801// complexity tick. Convenience wrapper for observers that want per-line802// complexity placement (the per-line attribution reports in plans 03–04).803func complexityLineNumbers(job *FileJob) []int {804 out := make([]int, 0)805 for i, count := range job.ComplexityLine {806 if count > 0 {807 out = append(out, i+1)808 }809 }810 return out811}812813// cognitiveLineNumbers returns the 1-based line numbers in job that accrued814// cognitive weight. Mirrors complexityLineNumbers for the cognitive per-line815// array; returns an empty slice when cognitive tracking is off (CognitiveLine816// nil), so callers get the same shape either way.817func cognitiveLineNumbers(job *FileJob) []int {818 out := make([]int, 0)819 for i, weight := range job.CognitiveLine {820 if weight > 0 {821 out = append(out, i+1)822 }823 }824 return out825}826827type historyLineCallback struct {828 lineTypes []LineType829}830831func (h *historyLineCallback) ProcessLine(job *FileJob, currentLine int64, lineType LineType) bool {832 h.lineTypes = append(h.lineTypes, lineType)833 return true834}835836func basename(path string) string {837 if i := strings.LastIndex(path, "/"); i >= 0 {838 return path[i+1:]839 }840 return path841}842843func lineCount(s string) int {844 if s == "" {845 return 0846 }847 n := strings.Count(s, "\n")848 if !strings.HasSuffix(s, "\n") {849 n++850 }851 return n852}
Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.
Generated by searchcode.com · powered by code_get_file + code_get_findings