1,259 matches across 25 files for error lang:Go
snippet_mode: auto · sorted by relevance
5import (
6 "encoding/csv"
7▶ "errors"
8 "fmt"
9 "os"
· · ·
409//
410// target accepts the same forms as --coupling-for and is validated against HEAD
411▶// before the walk, so a caller passing a bad path gets an immediate error rather
412// than paying for a full traversal first.
413func CouplingForJSONReport(repoPath, target string, limit int) (string, error) {
· · ·
413▶func CouplingForJSONReport(repoPath, target string, limit int) (string, error) {
414 resolved, err := resolveCouplingTarget(repoPath, target)
415 if err != nil {
· · ·
427// which needs the rendered data rather than stdout side effects. A limit > 0
428// caps the pair list (strongest first); limit <= 0 returns every pair.
429▶func CouplingJSONReport(repoPath string, limit int) (string, error) {
430 observer := newCouplingObserver()
431 if _, err := runHistory(repoPath, observer); err != nil {
· · ·
442// object.Tree.Files().ForEach surfaces whatever the callback returns, so it is
443// compared back at the call site and discarded.
444▶var errStopTreeWalk = errors.New("stop tree walk")
445
446// couplingTargetCandidates returns the repo-relative forms to try for a
+ 30 more matches in this file
5import (
6 "context"
7▶ "errors"
8 "fmt"
9 "io"
· · ·
126// collected --depth commits. iter.ForEach surfaces whatever the callback
127// returns, so we can compare it back at the call site directly.
128▶var errStopIter = errors.New("history: stop iteration")
129
130// Bucketing divides [From, To] into N equal time slices. Used by the timeline
· · ·
202// (newest first → oldest first), and feeds every commit's first-parent diff
203// to the observer.
204▶func runHistory(repoPath string, observer CommitObserver) (HistoryWindow, error) {
205 // Turn GC back on because we have no idea how much we are about to process
206 EnableGc()
· · ·
208 repo, err := git.PlainOpenWithOptions(repoPath, &git.PlainOpenOptions{DetectDotGit: true})
209 if err != nil {
210▶ return HistoryWindow{}, fmt.Errorf("open git repository: %w", err)
211 }
212
· · ·
213 head, err := repo.Head()
214 if err != nil {
215▶ if errors.Is(err, plumbing.ErrReferenceNotFound) {
216 observer.Finalise(HistoryWindow{}, emptySnapshot())
217 return HistoryWindow{}, nil
+ 15 more matches in this file
378// Timeline selects an over-time view. With ByAuthor, runs the author
379// timeline report (plan 04); alone, runs the languages-over-time report
380▶// (plan 05). With Hotspots set, the combination errors out.
381var Timeline = false
382
· · ·
528 t := strings.Split(s, ":")
529 if len(t) != 2 {
530▶ printError(fmt.Sprintf("ignoring malformed count-as rule %q: expected format <from>:<to>", s))
531 continue
532 }
· · ·
548 // extension, so no mapping was registered. Warn rather than silently
549 // ignoring the rule, since count-as cannot mint new categories yet.
550▶ printError(fmt.Sprintf("ignoring count-as rule %q: target %q is not a known language or extension", s, t[1]))
551 }
552}
· · ·
586// Because regex patterns and paths legitimately contain ':', name and baselang
587// are peeled from the right and the pattern is whatever remains in between.
588▶func parseCountAsPattern(s string) (CountRule, error) {
589 engine := MatchGlob
590 rest := s
· · ·
602 lastColon := strings.LastIndex(rest, ":")
603 if lastColon == -1 {
604▶ return CountRule{}, fmt.Errorf("expected format [engine:]pattern:name:baselang")
605 }
606 baseLanguage := rest[lastColon+1:]
+ 9 more matches in this file
77// existing default-named file (so a bare `--report` is non-destructive),
78// then collects data and renders the HTML output.
79▶func runReport(paths []string) error {
80 path := "."
81 if len(paths) > 0 {
· · ·
108// The io.Reader / io.Writer seam keeps the function unit-testable without
109// poking at os.Stdin / os.Stderr.
110▶func confirmReportOverwrite(outPath string, usedDefaultName, stdinIsTTY bool, in io.Reader, out io.Writer) error {
111 if !usedDefaultName {
112 return nil
· · ·
115 return nil
116 } else if err != nil {
117▶ // Some other stat error (permission?) — let the subsequent
118 // os.Create surface the underlying problem with a clearer
119 // "create report file: ..." wrapper instead of a stat error
· · ·
119▶ // "create report file: ..." wrapper instead of a stat error
120 // nobody asked for.
121 return nil
· · ·
122 }
123 if !stdinIsTTY {
124▶ return fmt.Errorf("%s already exists; rerun with --report=%s to overwrite explicitly", outPath, outPath)
125 }
126 _, _ = fmt.Fprintf(out, "%s already exists. Overwrite? [y/N]: ", outPath)
+ 7 more matches in this file
147
148 errLogger := log.New(os.Stderr, "scc-mcp: ", log.LstdFlags)
149▶ if err := server.ServeStdio(mcpServer, server.WithErrorLogger(errLogger)); err != nil {
150 _, _ = fmt.Fprintf(os.Stderr, "scc-mcp: server error: %v\n", err)
151 os.Exit(1)
· · ·
150▶ _, _ = fmt.Fprintf(os.Stderr, "scc-mcp: server error: %v\n", err)
151 os.Exit(1)
152 }
· · ·
218}
219
220▶func mcpAnalyzeHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
221 args := request.GetArguments()
222
· · ·
230 absPath, err := filepath.Abs(path)
231 if err != nil {
232▶ return mcp.NewToolResultError(fmt.Sprintf("invalid path: %v", err)), nil
233 }
234
· · ·
235 // Verify path can be accessed
236 if _, err := os.Stat(absPath); err != nil {
237▶ return mcp.NewToolResultError(fmt.Sprintf("path cannot be accessed: %s: %v", absPath, err)), nil
238 }
239
+ 11 more matches in this file
274// scc's analysis modes (ULOC, line-length, per-file table) are gated by
275// process-wide globals. The report mode flips them on inside a single
276▶// invocation; we snapshot and restore via defer so panics, errors, or
277// in-process re-entrancy don't leak state into a later scc call.
278type reportFlagState struct {
· · ·
308// snapshotted and restored via defer, but callers should not assume the
309// flags retain their on-entry values during the call.
310▶func CollectReportData(path string) (ReportData, error) {
311 start := time.Now()
312
· · ·
475// rollup and a flat per-file slice. Reuses aggregateLanguageSummary by
476// feeding it the same FileJobs through a buffered channel.
477▶func walkAndAggregate(path string) ([]*FileJob, []LanguageSummary, Totals, error) {
478 if path == "" {
479 path = "."
· · ·
483 info, err := os.Stat(fpath)
484 if err != nil {
485▶ return nil, nil, Totals{}, fmt.Errorf("file or directory could not be read: %s", fpath)
486 }
487
· · ·
502 if len(dirPaths) > 0 {
503 fileWalker := gocodewalker.NewParallelFileWalker(dirPaths, potentialFilesQueue)
504▶ fileWalker.SetErrorHandler(func(e error) bool {
505 printError(e.Error())
506 return true
+ 3 more matches in this file
6 "bytes"
7 "cmp"
8▶ "errors"
9 "slices"
10 "strings"
· · ·
12
13var (
14▶ errMissingShebang = errors.New("missing shebang")
15 errUnknownShebang = errors.New("unknown shebang")
16 errUnableToDetermineShebangCmd = errors.New("unable to determine shebang command")
· · ·
15▶ errUnknownShebang = errors.New("unknown shebang")
16 errUnableToDetermineShebangCmd = errors.New("unable to determine shebang command")
17)
· · ·
16▶ errUnableToDetermineShebangCmd = errors.New("unable to determine shebang command")
17)
18
· · ·
19▶// DetectLanguage detects a language based on the filename returns the language extension and error
20func DetectLanguage(name string) ([]string, string) {
21 extension := ""
+ 2 more matches in this file
3import (
4 "context"
5▶ "errors"
6 "fmt"
7 "math"
· · ·
63
64 if filterBad(loc) {
65▶ log.Error().Str(uniqueCode, "bfee4bd8").Str("loc", loc.String()).Msg("filter bad")
66 return
67 }
· · ·
71 res, err := process(1, loc)
72 if err != nil {
73▶ log.Error().Str(uniqueCode, "03ec75c3").Err(err).Str("loc", loc.String()).Send()
74 w.WriteHeader(http.StatusBadRequest)
75 _, _ = w.Write([]byte("something bad happened sorry"))
· · ·
108 addr := ":8080"
109 log.Info().Str(uniqueCode, "1876ce1e").Str("addr", addr).Msg("serving")
110▶ if err := http.ListenAndServe(addr, nil); err != nil && !errors.Is(err, http.ErrServerClosed) {
111 log.Error().Str(uniqueCode, "c28556e8").Err(err).Send()
112 os.Exit(1)
· · ·
111▶ log.Error().Str(uniqueCode, "c28556e8").Err(err).Send()
112 os.Exit(1)
113 }
+ 7 more matches in this file
372// walks history with baseline seeding, and writes the chosen format to
373// stdout or FileOutput.
374▶func runAuthorsReport(repoPath string) error {
375 observer := newHistoryAuthorsObserver()
376 if _, err := runHistory(repoPath, observer); err != nil {
· · ·
392}
393
394▶func renderAuthors(o *historyAuthorsObserver) (string, error) {
395 switch strings.ToLower(Format) {
396 case "", "tabular", "wide":
· · ·
401 return renderAuthorsJSON(o)
402 default:
403▶ return "", fmt.Errorf("unsupported --format %q for --by-author (supported: tabular, csv, json)", Format)
404 }
405}
· · ·
582}
583
584▶func renderAuthorsCSV(o *historyAuthorsObserver) (string, error) {
585 var sb strings.Builder
586 sb.WriteString(formatWindowComment(o.window))
· · ·
615 }
616 w.Flush()
617▶ if err := w.Error(); err != nil {
618 return "", err
619 }
+ 1 more matches in this file
21// the output (highest-scoring first); limit <= 0 returns every scored file.
22// HistoryDepth and the mailmap folding behave exactly as on the CLI path.
23▶func HotspotsJSONReport(repoPath string, limit int) (string, error) {
24 observer := newHotspotsObserver()
25 if _, err := runHistory(repoPath, observer); err != nil {
· · ·
32// --hotspots is set. Opens the repo at repoPath, walks history, and writes
33// the chosen format to stdout or FileOutput.
34▶func runHotspotsReport(repoPath string) error {
35 observer := newHotspotsObserver()
36 if _, err := runHistory(repoPath, observer); err != nil {
· · ·
218
219// renderHotspots returns the formatted output for the chosen --format.
220▶func renderHotspots(o *hotspotsObserver) (string, error) {
221 switch strings.ToLower(Format) {
222 case "", "tabular", "wide":
· · ·
227 return renderHotspotsJSON(o)
228 default:
229▶ return "", fmt.Errorf("unsupported --format %q for --hotspots (supported: tabular, csv, json)", Format)
230 }
231}
· · ·
321}
322
323▶func renderHotspotsCSV(o *hotspotsObserver) (string, error) {
324 var sb strings.Builder
325 sb.WriteString(formatWindowComment(o.window))
+ 3 more matches in this file
190// when --by-author --timeline is set. Opens the repo, walks the window with
191// the configured bucket count, and writes the chosen format.
192▶func runAuthorTimelineReport(repoPath string) error {
193 observer := newHistoryAuthorTimelineObserver(HistoryBuckets)
194 if _, err := runHistory(repoPath, observer); err != nil {
· · ·
210}
211
212▶func renderAuthorTimeline(o *historyAuthorTimelineObserver) (string, error) {
213 switch strings.ToLower(Format) {
214 case "", "tabular", "wide":
· · ·
219 return renderAuthorTimelineJSON(o)
220 default:
221▶ return "", fmt.Errorf("unsupported --format %q for --by-author --timeline (supported: tabular, csv, json)", Format)
222 }
223}
· · ·
361}
362
363▶func renderAuthorTimelineCSV(o *historyAuthorTimelineObserver) (string, error) {
364 var sb strings.Builder
365 sb.WriteString(formatWindowComment(o.window))
· · ·
383 }
384 w.Flush()
385▶ if err := w.Error(); err != nil {
386 return "", err
387 }
+ 1 more matches in this file
4
5import (
6▶ "errors"
7 "fmt"
8 "os"
· · ·
15)
16
17▶func printShellCompletion(cmd *cobra.Command, command string) error {
18 switch command {
19 case "bash":
· · ·
26 return cmd.GenPowerShellCompletion(os.Stdout)
27 default:
28▶ return errors.New("Unknown shell: " + command)
29 }
30}
· · ·
71 b, err := os.ReadFile(filename)
72 if err != nil {
73▶ fmt.Fprintf(os.Stderr, "Error reading flags from a file: %s\n", err)
74 os.Exit(1)
75 }
· · ·
89 if !isCompletionInvocation(os.Args) {
90 noConfig, findRoot, explicitPath := preScanConfig(os.Args)
91▶ var discoverErr error
92 globalTokens, projectTokens, discoverErr = discoverConfigArgs(noConfig, findRoot, explicitPath)
93 if discoverErr != nil {
+ 5 more matches in this file
66 }
67
68▶ var err error
69 symPath, err = filepath.EvalSymlinks(path)
70 if err != nil {
· · ·
71▶ printError(err.Error())
72 return nil
73 }
· · ·
74 fileInfo, err = os.Lstat(symPath)
75 if err != nil {
76▶ printError(err.Error())
77 return nil
78 }
185// walks the window with the configured bucket count, and writes the chosen
186// format.
187▶func runLanguagesTimelineReport(repoPath string) error {
188 observer := newHistoryLanguagesObserver(HistoryBuckets)
189 if _, err := runHistory(repoPath, observer); err != nil {
· · ·
205}
206
207▶func renderLanguagesTimeline(o *historyLanguagesObserver) (string, error) {
208 switch strings.ToLower(Format) {
209 case "", "tabular", "wide":
· · ·
214 return renderLanguagesTimelineJSON(o)
215 default:
216▶ return "", fmt.Errorf("unsupported --format %q for --timeline (supported: tabular, csv, json)", Format)
217 }
218}
· · ·
274}
275
276▶func renderLanguagesTimelineCSV(o *historyLanguagesObserver) (string, error) {
277 var sb strings.Builder
278 sb.WriteString(formatWindowComment(o.window))
· · ·
299 }
300 w.Flush()
301▶ if err := w.Error(); err != nil {
302 return "", err
303 }
+ 1 more matches in this file
36// compiled into this binary, which is the *old* constants.go (compiled before
37// this run rewrote it), so LANGUAGES.md always lagged the JSON by one pass.
38▶func loadLanguages() (map[string]processor.Language, error) {
39 files, _ := os.ReadDir(".")
40 langs := map[string]processor.Language{}
· · ·
44 file, err := os.Open(f.Name())
45 if err != nil {
46▶ return nil, fmt.Errorf("failed to open file '%s': %v", f.Name(), err)
47 }
48
· · ·
52 if err := json.NewDecoder(file).Decode(&data); err != nil {
53 _ = file.Close()
54▶ return nil, fmt.Errorf("failed to validate json in file '%s': %v", f.Name(), err)
55 }
56 _ = file.Close()
· · ·
61 for _, h := range lang.Heuristics {
62 if _, err := regexp.Compile(h.Pattern); err != nil {
63▶ return nil, fmt.Errorf("invalid heuristic regex %q for language '%s' in file '%s': %v", h.Pattern, name, f.Name(), err)
64 }
65 }
· · ·
74
75// encodes the language database as string literals in constants.go
76▶func generateConstants(langs map[string]processor.Language) error {
77 buf := &bytes.Buffer{}
78
+ 7 more matches in this file
16// ProcessResult runs the same pipeline as Process but returns structured results
17// instead of formatting to stdout. Useful for programmatic consumers like MCP servers.
18▶func ProcessResult() ([]LanguageSummary, error) {
19 ProcessConstants()
20 processFlags()
· · ·
34 s, err := os.Stat(fpath)
35 if err != nil {
36▶ return nil, fmt.Errorf("file or directory could not be read: %s", fpath)
37 }
38
· · ·
56
57 fileWalker := gocodewalker.NewParallelFileWalker(dirPaths, potentialFilesQueue)
58▶ fileWalker.SetErrorHandler(func(e error) bool {
59 printError(e.Error())
60 return true
· · ·
59▶ printError(e.Error())
60 return true
61 })
· · ·
80 excludePathRegexes = append(excludePathRegexes, regexpResult)
81 } else {
82▶ printError(err.Error())
83 }
84 }
+ 1 more matches in this file
185
186// discoverConfigArgs resolves the global and project config sources
187▶func discoverConfigArgs(noConfig, findRoot bool, explicitPath string) (globalTokens, projectTokens []string, err error) {
188 // Global source: --config wins, else SCC_CONFIG_PATH (when non-empty and not
189 // disabled), else nothing. No default location, no home-dir stat.
· · ·
202 if readErr != nil {
203 // Explicit source the user asked for: surface and exit non-zero.
204▶ return nil, nil, fmt.Errorf("could not read config file %q: %w", globalPath, readErr)
205 }
206 globalTokens = tokens
· · ·
229// readConfigFile reads and tokenizes a config source, recording it for trace
230// output and unknown-flag attribution.
231▶func readConfigFile(path, label string) (tokens []string, err error) {
232 defer func() {
233 if r := recover(); r != nil {
· · ·
234▶ err = fmt.Errorf("panic while reading config: %v", r)
235 }
236 }()
· · ·
325 return real
326 }
327▶ boolFunc := func(real func(string) error) func(string) error {
328 if b.inert {
329 return func(string) error { return nil }
+ 9 more matches in this file
35// parses them, and produces a matcher. Respects the existing --no-ignore
36// (Ignore) and --no-scc-ignore (SccIgnore) flag globals.
37▶func buildHistoryIgnore(repo *git.Repository, head plumbing.Hash) (*historyIgnore, error) {
38 commit, err := repo.CommitObject(head)
39 if err != nil {
· · ·
46
47 var patterns []gitignore.Pattern
48▶ err = tree.Files().ForEach(func(f *object.File) error {
49 if f.Mode == filemode.Dir || f.Mode == filemode.Submodule || f.Mode == filemode.Symlink {
50 return nil
4
5import (
6▶ "errors"
7 "fmt"
8 "io"
· · ·
11
12// validateHistoryFlags checks the global flag state for the history reports
13▶// (--hotspots, --by-author, --timeline). Hard errors are returned and should
14// abort the run; recoverable conditions are written to warnDst as a single
15// line each and execution continues.
· · ·
16▶func validateHistoryFlags(warnDst io.Writer) error {
17 if !Hotspots && !ByAuthor && !Timeline {
18 return nil
· · ·
20
21 if HistoryDepth < 0 {
22▶ return errors.New("--depth must be >= 0 (0 means entire history)")
23 }
24
· · ·
25 if Timeline && HistoryBuckets < 1 {
26▶ return errors.New("--buckets must be >= 1")
27 }
28
14 levelDebug
15 levelWarn
16▶ levelError
17)
18
· · ·
25 case levelWarn:
26 return "WARN"
27▶ case levelError:
28 return "ERROR"
29 default:
· · ·
28▶ return "ERROR"
29 default:
30 return ""
· · ·
92
93// Used when explicitly for os.exit output when crashing out
94▶func printError(msg string) {
95 doPrint(os.Stderr, levelError, msg, nil)
96}
· · ·
95▶ doPrint(os.Stderr, levelError, msg, nil)
96}
97
+ 4 more matches in this file
156// unexported alias type carries the same field tags but none of the methods, so
157// marshaling it does not recurse.
158▶func (fileJob *FileJob) MarshalJSON() ([]byte, error) {
159 type alias FileJob
160 if Cognitive {
· · ·
223// mirroring FileJob.MarshalJSON: present (even at 0) when the metric is on,
224// omitted when off. See FileJob.MarshalJSON for the rationale.
225▶func (l LanguageSummary) MarshalJSON() ([]byte, error) {
226 type alias LanguageSummary
227 if Cognitive {
17func TestIsWhitespace(t *testing.T) {
18 if !isWhitespace(' ') {
19▶ t.Errorf("Expected to be true")
20 }
21}
· · ·
25
26 if !isBinary(0, 0) {
27▶ t.Errorf("Expected to be true")
28 }
29}
· · ·
33
34 if isBinary(0, 0) {
35▶ t.Errorf("Expected to be false")
36 }
37}
· · ·
51 CountStats(&fileJob)
52 if fileJob.Lines != 0 {
53▶ t.Errorf("Zero lines expected got %d", fileJob.Lines)
54 }
55
· · ·
60 CountStats(&fileJob)
61 if fileJob.Lines != 1 {
62▶ t.Errorf("One line expected got %d", fileJob.Lines)
63 }
64
+ 132 more matches in this file
22
23// ReadFile actually reads the file into a buffer size controlled by LargeByteCount
24▶func (reader *FileReader) ReadFile(path string, size int) ([]byte, error) {
25 fd, err := os.Open(path)
26 if err != nil {
· · ·
27▶ return nil, fmt.Errorf("error opening %s: %v", path, err)
28 }
29 defer func(file *os.File) {
· · ·
46 _, err = reader.Buffer.ReadFrom(fd)
47 if err != nil {
48▶ return nil, fmt.Errorf("error reading %s: %w", path, err)
49 }
50
14)
15
16▶func writeTestFile(path, content string) error {
17 return os.WriteFile(path, []byte(content), 0o644)
18}
· · ·
37
38 if !data.GitAvailable {
39▶ t.Errorf("expected GitAvailable=true for fixture repo, got false")
40 }
41 if data.RepoName == "" {
· · ·
42▶ t.Errorf("expected RepoName to be derived from path, got empty")
43 }
44 if data.SccVersion == "" {
· · ·
45▶ t.Errorf("expected SccVersion to be set")
46 }
47 if data.GeneratedAt.IsZero() {
· · ·
48▶ t.Errorf("expected GeneratedAt to be set")
49 }
50
+ 89 more matches in this file
29}
30
31▶func runSCC(args ...string) (string, error) {
32 args = slices.Insert(args, 0, sccTestFlag)
33 cmd := exec.Command(sccBinPath, args...)
· · ·
269 }
270 if !strings.Contains(output, "MATLAB") {
271▶ t.Errorf("can not find MATLAB, output: %s", output)
272 }
273 if !strings.Contains(output, "Objective C") {
· · ·
274▶ t.Errorf("can not find Objective C, output:\n%s", output)
275 }
276}
· · ·
280 output, err := runSCC("--not-a-real-option")
281 if err == nil {
282▶ t.Fatal("scc should exit with error code")
283 }
284 if !strings.Contains(output, "Error: unknown flag: --not-a-real-option") {
· · ·
284▶ if !strings.Contains(output, "Error: unknown flag: --not-a-real-option") {
285 t.Fatalf("scc should report invalid options, output:\n%s", output)
286 }
+ 28 more matches in this file