repometry 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +23 -20
  2. package/package.json +1 -1
  3. package/target/main/resources/config/process-plugins-v1.schema.json +4 -0
  4. package/target/main/resources/languages/go/parser.go +602 -0
  5. package/target/main/resources/languages/python/parser.py +312 -0
  6. package/target/main/resources/report/json/viewer-inspection-v1.schema.json +2 -1
  7. package/target/main/resources/viewer/files.css +1 -0
  8. package/target/main/ts/api/git/git-reader.d.ts +10 -2
  9. package/target/main/ts/api/git/git-reader.js +74 -35
  10. package/target/main/ts/api/git/git.d.ts +19 -1
  11. package/target/main/ts/api/git/git.js +97 -7
  12. package/target/main/ts/api/import/go-cover.d.ts +13 -0
  13. package/target/main/ts/api/import/go-cover.js +150 -0
  14. package/target/main/ts/api/import/lcov-files.d.ts +6 -1
  15. package/target/main/ts/api/import/lcov-files.js +27 -7
  16. package/target/main/ts/api/process/docker-tool-runner.js +5 -21
  17. package/target/main/ts/api/process/host-language-runner.d.ts +13 -0
  18. package/target/main/ts/api/process/host-language-runner.js +176 -0
  19. package/target/main/ts/api/process/plugin.d.ts +4 -1
  20. package/target/main/ts/api/process/plugin.js +7 -3
  21. package/target/main/ts/api/process/tool-snapshot.d.ts +3 -0
  22. package/target/main/ts/api/process/tool-snapshot.js +26 -0
  23. package/target/main/ts/cli/imports.d.ts +1 -0
  24. package/target/main/ts/cli/imports.js +5 -2
  25. package/target/main/ts/cli/main.js +46 -15
  26. package/target/main/ts/compose/analysis-files.d.ts +2 -1
  27. package/target/main/ts/compose/analysis-files.js +19 -5
  28. package/target/main/ts/compose/analysis-imports.js +2 -1
  29. package/target/main/ts/compose/analysis-report.d.ts +1 -0
  30. package/target/main/ts/compose/analysis-report.js +13 -12
  31. package/target/main/ts/compose/analysis-repository.d.ts +2 -1
  32. package/target/main/ts/compose/analysis-repository.js +42 -4
  33. package/target/main/ts/compose/analysis-sources.d.ts +5 -0
  34. package/target/main/ts/compose/analysis-sources.js +10 -3
  35. package/target/main/ts/compose/analyze-snapshot.d.ts +2 -1
  36. package/target/main/ts/compose/analyze-snapshot.js +5 -3
  37. package/target/main/ts/compose/diff-coverage.d.ts +2 -1
  38. package/target/main/ts/compose/diff-coverage.js +8 -6
  39. package/target/main/ts/compose/history-cache.d.ts +29 -0
  40. package/target/main/ts/compose/history-cache.js +57 -0
  41. package/target/main/ts/compose/inspect.d.ts +6 -1
  42. package/target/main/ts/compose/inspect.js +10 -10
  43. package/target/main/ts/compose/inspection-coverage.d.ts +9 -0
  44. package/target/main/ts/compose/inspection-coverage.js +9 -0
  45. package/target/main/ts/compose/languages.d.ts +6 -1
  46. package/target/main/ts/compose/languages.js +19 -6
  47. package/target/main/ts/compose/native-language-plugins.d.ts +6 -0
  48. package/target/main/ts/compose/native-language-plugins.js +40 -0
  49. package/target/main/ts/compose/plugin-list.d.ts +3 -8
  50. package/target/main/ts/compose/plugin-list.js +12 -5
  51. package/target/main/ts/compose/prepare-metabranch.js +1 -1
  52. package/target/main/ts/compose/process-plugins.js +6 -5
  53. package/target/main/ts/compose/review.d.ts +1 -2
  54. package/target/main/ts/compose/review.js +2 -2
  55. package/target/main/ts/core/engine/plan.js +5 -6
  56. package/target/main/ts/core/engine/plugin.d.ts +2 -0
  57. package/target/main/ts/core/model/file-types.d.ts +1 -0
  58. package/target/main/ts/core/model/file-types.js +14 -3
  59. package/target/main/ts/core/model/quality-summary.js +2 -0
  60. package/target/main/ts/core/model/source.d.ts +2 -0
  61. package/target/main/ts/core/usecases/inspect.d.ts +1 -1
  62. package/target/main/ts/core/usecases/inspect.js +1 -1
  63. package/target/main/ts/plugins/security/dockerfile.js +6 -15
  64. package/target/main/ts/report/html/app/viewer-language-bar.d.ts +2 -0
  65. package/target/main/ts/report/html/app/viewer-language-bar.js +5 -1
  66. package/target/main/ts/report/html/app/viewer-profile.js +9 -2
  67. package/target/main/ts/report/json/projections/commit-summary.d.ts +1 -0
  68. package/target/main/ts/report/json/projections/commit-summary.js +5 -0
  69. package/target/main/ts/report/json/projections/file-metrics.js +39 -44
  70. package/target/main/ts/report/json/projections/inspection-details.js +3 -2
  71. package/target/main/ts/report/json/store/directory.d.ts +3 -0
  72. package/target/main/ts/report/json/store/directory.js +19 -0
  73. package/target/main/ts/report/json/store/local-store.d.ts +14 -2
  74. package/target/main/ts/report/json/store/local-store.js +74 -60
  75. package/target/main/ts/report/json/store/object-store.d.ts +14 -0
  76. package/target/main/ts/report/json/store/object-store.js +73 -0
  77. package/target/main/ts/report/json/store/report-tree.d.ts +46 -0
  78. package/target/main/ts/report/json/store/report-tree.js +290 -0
  79. package/target/main/ts/report/json/store/store-check.d.ts +32 -0
  80. package/target/main/ts/report/json/store/store-check.js +144 -0
  81. package/target/main/ts/report/json/validation/report.d.ts +6 -1
  82. package/target/main/ts/report/json/validation/report.js +10 -4
  83. package/target/main/ts/report/json/wire/inspection-details-model.d.ts +1 -0
package/README.md CHANGED
@@ -15,34 +15,37 @@
15
15
 
16
16
  Git can serve as a project’s single source of truth for code, tests, docs, and CI configuration. Repometry lets you keep coverage and maintainability metrics alongside your code, commit by commit.
17
17
 
18
- ## Requirements
18
+ ## Demo
19
+ [https://idleware.github.io/repometry/](https://idleware.github.io/repometry/)
19
20
 
20
- Node.js 24 or newer.
21
+ ## Requirements
21
22
 
22
- ## Usage
23
+ Node.js >=24
23
24
 
24
- Run these commands in your repository.
25
+ ## Install
25
26
 
26
27
  ```sh
27
- # Analyze HEAD and save its inspection under .repometry/.
28
- npx repometry analyze
29
-
30
- # Build history for the last 50 commits, oldest first, skipping saved inspections.
31
- npx repometry analyze HEAD~50..HEAD --skip-saved
28
+ # Run without installing.
29
+ npx repometry help
32
30
 
33
- # Import coverage and scanner results. Repeat --import for each file.
34
- npx repometry analyze --import lcov=coverage/lcov.info --import sarif=results.sarif
35
-
36
- # Open the report locally on a free port. Use --port 3030 to choose a port.
37
- npx repometry view
31
+ # Or install the repometry command.
32
+ npm install --global repometry
33
+ ```
38
34
 
39
- # Export a static report to .repometry/report/html. Use -o DIR for another folder.
40
- npx repometry report html
35
+ ## Usage
41
36
 
42
- # List supported formats and get help for a command.
43
- npx repometry plugins
44
- npx repometry help analyze
45
- ```
37
+ Run these commands in your repository. Without an install, start each with `npx`.
38
+
39
+ | Command | What it does |
40
+ | --- | --- |
41
+ | `repometry analyze` | Analyze HEAD and save its inspection under `.repometry/`. |
42
+ | `repometry analyze HEAD~50..HEAD --skip-saved` | Build history for the last 50 commits, oldest first, skipping saved inspections. |
43
+ | `repometry analyze --import lcov=coverage/lcov.info --import sarif=results.sarif` | Import coverage and scanner results. Repeat `--import` for each file. |
44
+ | `repometry view` | Open the report locally on a free port. Use `--port 3030` to choose a port. |
45
+ | `repometry report html` | Export a static report to `.repometry/report/html`. Use `-o DIR` for another folder. |
46
+ | `repometry store check --repair --from git:repometry` | Check saved inspections. `--repair` restores missing data from a copy. |
47
+ | `repometry plugins` | List supported formats. |
48
+ | `repometry help analyze` | Get help for a command. |
46
49
 
47
50
  A report shows everything the store holds, so publish it only where you would publish that data.
48
51
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "repometry",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "description": "Track repository metrics without SaaS",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -21,6 +21,10 @@
21
21
  "items": { "type": "string", "pattern": "^[^\\u0000]*$" }
22
22
  },
23
23
  "scope": { "enum": ["file", "repository"] },
24
+ "fileIndependent": {
25
+ "type": "boolean",
26
+ "description": "Each file's results and diagnostics are independent of the other files supplied to a repository parser."
27
+ },
24
28
  "claims": {
25
29
  "type": "object",
26
30
  "additionalProperties": false,
@@ -0,0 +1,602 @@
1
+ package main
2
+
3
+ import (
4
+ "bytes"
5
+ "crypto/sha256"
6
+ "encoding/base64"
7
+ "encoding/json"
8
+ "fmt"
9
+ "go/ast"
10
+ "go/parser"
11
+ "go/token"
12
+ "os"
13
+ "path/filepath"
14
+ "reflect"
15
+ "sort"
16
+ "strconv"
17
+ )
18
+
19
+ const structuresContract = "repometry.code-structures/v1"
20
+
21
+ type processRequest struct {
22
+ Settings struct {
23
+ Duplication duplicationSettings `json:"duplication"`
24
+ } `json:"settings"`
25
+ Inputs struct {
26
+ Files struct {
27
+ Files []struct {
28
+ Path string `json:"path"`
29
+ } `json:"files"`
30
+ } `json:"files"`
31
+ } `json:"inputs"`
32
+ }
33
+
34
+ type codeStructure struct {
35
+ Path string `json:"path"`
36
+ Lines int `json:"lines"`
37
+ Functions int `json:"functions"`
38
+ CyclomaticFunctions []functionComplexity `json:"cyclomaticFunctions"`
39
+ CognitiveComplexity int `json:"cognitiveComplexity"`
40
+ CognitiveFunctions []functionComplexity `json:"cognitiveFunctions"`
41
+ Observations []observation `json:"observations"`
42
+ Clones cloneSource `json:"clones"`
43
+ CommentLines int `json:"commentLines"`
44
+ CodeLines []int `json:"codeLines"`
45
+ }
46
+
47
+ type functionComplexity struct {
48
+ Name string `json:"name,omitempty"`
49
+ Line int `json:"line"`
50
+ Column int `json:"column"`
51
+ Value int `json:"value"`
52
+ }
53
+
54
+ type observation struct {
55
+ Rule string `json:"rule"`
56
+ Value int `json:"value"`
57
+ Label string `json:"label"`
58
+ Line int `json:"line"`
59
+ EndLine int `json:"endLine"`
60
+ }
61
+
62
+ type duplicationSettings struct {
63
+ MinCodeLines int `json:"minCodeLines"`
64
+ MinNodes int `json:"minNodes"`
65
+ }
66
+
67
+ type cloneSource struct {
68
+ Path string `json:"path"`
69
+ Scheme string `json:"scheme"`
70
+ CodeLines []int `json:"codeLines"`
71
+ Candidates []candidate `json:"candidates"`
72
+ }
73
+
74
+ type candidate struct {
75
+ Start int `json:"start"`
76
+ End int `json:"end"`
77
+ Line int `json:"line"`
78
+ EndLine int `json:"endLine"`
79
+ CodeLines int `json:"codeLines"`
80
+ Nodes int `json:"nodes"`
81
+ Exact string `json:"exact"`
82
+ Similar string `json:"similar"`
83
+ }
84
+
85
+ type span struct {
86
+ start, end int
87
+ }
88
+
89
+ func main() {
90
+ if err := run(); err != nil {
91
+ fmt.Fprintln(os.Stderr, err)
92
+ os.Exit(1)
93
+ }
94
+ }
95
+
96
+ func run() error {
97
+ var request processRequest
98
+ request.Settings.Duplication = duplicationSettings{MinCodeLines: 12, MinNodes: 50}
99
+ if err := json.NewDecoder(os.Stdin).Decode(&request); err != nil {
100
+ return fmt.Errorf("read Go parser request: %w", err)
101
+ }
102
+
103
+ response := json.NewEncoder(os.Stdout)
104
+ files := request.Inputs.Files.Files
105
+ structures := make([]codeStructure, 0, len(files))
106
+ for _, file := range files {
107
+ structure, err := inspectFile(file.Path, request.Settings.Duplication)
108
+ if err != nil {
109
+ if err := response.Encode(map[string]any{
110
+ "kind": "diagnostic", "severity": "warning", "message": err.Error(),
111
+ }); err != nil {
112
+ return err
113
+ }
114
+ continue
115
+ }
116
+ structures = append(structures, structure)
117
+ }
118
+ return response.Encode(map[string]any{
119
+ "kind": "product", "contract": structuresContract, "value": structures,
120
+ })
121
+ }
122
+
123
+ func inspectFile(path string, duplication duplicationSettings) (codeStructure, error) {
124
+ source, err := os.ReadFile(filepath.FromSlash(path))
125
+ if err != nil {
126
+ return codeStructure{}, fmt.Errorf("Unable to read Go source %q", path)
127
+ }
128
+ positions := token.NewFileSet()
129
+ file, err := parser.ParseFile(positions, path, source, parser.ParseComments|parser.SkipObjectResolution)
130
+ if err != nil {
131
+ return codeStructure{}, fmt.Errorf("Unable to parse Go source %q", path)
132
+ }
133
+
134
+ layout := sourceLayout{tokens: positions.File(file.Pos()), offsets: lineOffsets(source), source: source}
135
+ layout.fixRawStringEnds(file)
136
+ code, comments := classifyLines(source, layout.offsets, commentSpans(file, layout.tokens, source))
137
+ metrics := measureStructure(file, layout)
138
+ return codeStructure{
139
+ Path: path, Lines: len(layout.offsets) - 1, Functions: len(metrics.cyclomatic),
140
+ CyclomaticFunctions: metrics.cyclomatic, CognitiveComplexity: metrics.cognitiveTotal,
141
+ CognitiveFunctions: metrics.cognitive, Observations: metrics.observations,
142
+ CommentLines: comments, CodeLines: code, Clones: measureClones(path, file, layout, code, duplication),
143
+ }, nil
144
+ }
145
+
146
+ // Repometry recognizes these line breaks in every source inventory.
147
+ func lineOffsets(source []byte) []int {
148
+ offsets := []int{0}
149
+ for offset, char := range string(source) {
150
+ switch char {
151
+ case '\r':
152
+ if offset+1 == len(source) || source[offset+1] != '\n' {
153
+ offsets = append(offsets, offset+1)
154
+ }
155
+ case '\n':
156
+ offsets = append(offsets, offset+1)
157
+ case '\u2028', '\u2029':
158
+ offsets = append(offsets, offset+len(string(char)))
159
+ }
160
+ }
161
+ if offsets[len(offsets)-1] != len(source) {
162
+ offsets = append(offsets, len(source))
163
+ }
164
+ return offsets
165
+ }
166
+
167
+ func commentSpans(file *ast.File, tokens *token.File, source []byte) []span {
168
+ var spans []span
169
+ for _, group := range file.Comments {
170
+ for _, comment := range group.List {
171
+ start := tokens.Offset(comment.Slash)
172
+ // The AST comment text omits carriage returns, so find its end in the original source.
173
+ end := len(source)
174
+ if source[start+1] == '/' {
175
+ if newline := bytes.IndexByte(source[start:], '\n'); newline >= 0 {
176
+ end = start + newline
177
+ }
178
+ } else {
179
+ end = start + 4 + bytes.Index(source[start+2:], []byte("*/"))
180
+ }
181
+ spans = append(spans, span{start, end})
182
+ }
183
+ }
184
+ return spans
185
+ }
186
+
187
+ func classifyLines(source []byte, offsets []int, comments []span) ([]int, int) {
188
+ code := []int{}
189
+ commentLines := 0
190
+ start := 0
191
+ if bytes.HasPrefix(source, []byte("\ufeff")) {
192
+ start = len("\ufeff")
193
+ }
194
+ for line, end := range offsets[1:] {
195
+ cursor := start
196
+ hasCode, hasComment := false, false
197
+ for len(comments) > 0 && comments[0].start < end {
198
+ comment := comments[0]
199
+ hasComment = true
200
+ if cursor < comment.start {
201
+ hasCode = hasCode || len(bytes.TrimSpace(source[cursor:comment.start])) > 0
202
+ }
203
+ cursor = comment.end
204
+ if cursor > end {
205
+ break
206
+ }
207
+ comments = comments[1:]
208
+ }
209
+ if hasCode || (cursor < end && len(bytes.TrimSpace(source[cursor:end])) > 0) {
210
+ code = append(code, line+1)
211
+ } else if hasComment {
212
+ commentLines++
213
+ }
214
+ start = end
215
+ }
216
+ return code, commentLines
217
+ }
218
+
219
+ type sourceLayout struct {
220
+ tokens *token.File
221
+ offsets []int
222
+ source []byte
223
+ rawEnds map[token.Pos]int
224
+ }
225
+
226
+ func (s *sourceLayout) fixRawStringEnds(file *ast.File) {
227
+ if bytes.IndexByte(s.source, '\r') < 0 {
228
+ return
229
+ }
230
+ ast.Inspect(file, func(node ast.Node) bool {
231
+ literal, ok := node.(*ast.BasicLit)
232
+ if !ok || !rawString(literal) {
233
+ return true
234
+ }
235
+ position := literal.End()
236
+ end := s.tokens.Offset(position)
237
+ if s.source[end-1] != '`' {
238
+ if s.rawEnds == nil {
239
+ s.rawEnds = make(map[token.Pos]int)
240
+ }
241
+ // Go discards carriage returns from a raw string's AST value.
242
+ s.rawEnds[position] = end + bytes.IndexByte(s.source[end:], '`') + 1
243
+ }
244
+ return true
245
+ })
246
+ }
247
+
248
+ func (s sourceLayout) end(position token.Pos) int {
249
+ if offset, found := s.rawEnds[position]; found {
250
+ return offset
251
+ }
252
+ return s.tokens.Offset(position)
253
+ }
254
+
255
+ func rawString(literal *ast.BasicLit) bool {
256
+ return literal.Kind == token.STRING && literal.Value[0] == '`'
257
+ }
258
+
259
+ func (s sourceLayout) line(offset int) int {
260
+ return sort.SearchInts(s.offsets, offset+1)
261
+ }
262
+
263
+ type structureMetrics struct {
264
+ layout sourceLayout
265
+ cyclomatic []functionComplexity
266
+ cognitive []functionComplexity
267
+ observations []observation
268
+ cognitiveTotal int
269
+ }
270
+
271
+ type flow struct {
272
+ cognitive, cyclomatic, returns, maxDepth int
273
+ deepest ast.Node
274
+ }
275
+
276
+ func measureStructure(file *ast.File, layout sourceLayout) structureMetrics {
277
+ metrics := structureMetrics{layout: layout, cyclomatic: []functionComplexity{},
278
+ cognitive: []functionComplexity{}, observations: []observation{}}
279
+ module := flow{}
280
+ metrics.visit(file, &module, 0, token.ILLEGAL, false)
281
+ if module.deepest != nil {
282
+ metrics.observe("nested-control-flow", module.maxDepth, "Module control-flow depth", module.deepest)
283
+ }
284
+ metrics.cognitiveTotal += module.cognitive
285
+ metrics.observations = append(metrics.observations, observation{
286
+ Rule: "file-complexity", Value: metrics.cognitiveTotal, Label: "File cognitive complexity",
287
+ Line: 1, EndLine: len(layout.offsets) - 1,
288
+ })
289
+ return metrics
290
+ }
291
+
292
+ func (m *structureMetrics) observe(rule string, value int, label string, node ast.Node) {
293
+ start, end := m.layout.tokens.Offset(node.Pos()), m.layout.end(node.End())
294
+ m.observations = append(m.observations, observation{
295
+ Rule: rule, Value: value, Label: label, Line: m.layout.line(start), EndLine: m.layout.line(end - 1),
296
+ })
297
+ }
298
+
299
+ func (m *structureMetrics) visit(node ast.Node, frame *flow, depth int, logicalParent token.Token, chained bool) {
300
+ switch node := node.(type) {
301
+ case *ast.FuncDecl:
302
+ m.measureFunction(node, node.Body, node.Type, methodName(node), frame, depth)
303
+ return
304
+ case *ast.FuncLit:
305
+ m.measureFunction(node, node.Body, node.Type, "", frame, depth)
306
+ return
307
+ case *ast.ParenExpr:
308
+ m.visit(node.X, frame, depth, logicalParent, false)
309
+ return
310
+ case *ast.CommentGroup:
311
+ return
312
+ }
313
+
314
+ var logical token.Token
315
+ block := false
316
+ switch node := node.(type) {
317
+ case *ast.IfStmt, *ast.ForStmt, *ast.RangeStmt:
318
+ frame.cyclomatic++
319
+ block = true
320
+ case *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt:
321
+ block = true
322
+ case *ast.CaseClause:
323
+ if node.List != nil {
324
+ frame.cyclomatic++
325
+ }
326
+ case *ast.CommClause:
327
+ if node.Comm != nil {
328
+ frame.cyclomatic++
329
+ }
330
+ case *ast.ReturnStmt:
331
+ frame.returns++
332
+ case *ast.BranchStmt:
333
+ if node.Label != nil {
334
+ frame.cognitive++
335
+ }
336
+ case *ast.BinaryExpr:
337
+ if isLogical(node.Op) {
338
+ logical = node.Op
339
+ frame.cyclomatic++
340
+ if logicalParent != logical {
341
+ frame.cognitive++
342
+ }
343
+ if !isLogical(logicalParent) {
344
+ m.observe("boolean-logic", countLogicalOperators(node), "Logical operators in one expression", node)
345
+ }
346
+ }
347
+ }
348
+
349
+ childDepth := depth
350
+ if block {
351
+ frame.cognitive++
352
+ if !chained {
353
+ frame.cognitive += depth
354
+ }
355
+ childDepth++
356
+ if childDepth > frame.maxDepth {
357
+ frame.maxDepth, frame.deepest = childDepth, node
358
+ }
359
+ }
360
+ forChildren(node, func(child ast.Node) {
361
+ if conditional, ok := node.(*ast.IfStmt); ok && child == conditional.Else {
362
+ if _, nextIf := child.(*ast.IfStmt); nextIf {
363
+ m.visit(child, frame, depth, token.ILLEGAL, true)
364
+ } else {
365
+ frame.cognitive++
366
+ m.visit(child, frame, childDepth, token.ILLEGAL, false)
367
+ }
368
+ return
369
+ }
370
+ m.visit(child, frame, childDepth, logical, false)
371
+ })
372
+ }
373
+
374
+ func forChildren(node ast.Node, visit func(ast.Node)) {
375
+ ast.Inspect(node, func(child ast.Node) bool {
376
+ if child == node {
377
+ return true
378
+ }
379
+ if child != nil {
380
+ visit(child)
381
+ }
382
+ return false
383
+ })
384
+ }
385
+
386
+ func isLogical(operator token.Token) bool {
387
+ return operator == token.LAND || operator == token.LOR
388
+ }
389
+
390
+ func countLogicalOperators(node ast.Expr) int {
391
+ switch node := node.(type) {
392
+ case *ast.ParenExpr:
393
+ return countLogicalOperators(node.X)
394
+ case *ast.BinaryExpr:
395
+ if isLogical(node.Op) {
396
+ return 1 + countLogicalOperators(node.X) + countLogicalOperators(node.Y)
397
+ }
398
+ }
399
+ return 0
400
+ }
401
+
402
+ func (m *structureMetrics) measureFunction(node ast.Node, body *ast.BlockStmt, signature *ast.FuncType, name string, outer *flow, depth int) {
403
+ number := len(m.cyclomatic)
404
+ offset := m.layout.tokens.Offset(node.Pos())
405
+ line := m.layout.line(offset)
406
+ position := functionComplexity{Name: name, Line: line, Column: offset - m.layout.offsets[line-1] + 1}
407
+ m.cyclomatic = append(m.cyclomatic, position)
408
+ m.cognitive = append(m.cognitive, position)
409
+
410
+ own := flow{cyclomatic: 1}
411
+ forChildren(node, func(child ast.Node) {
412
+ if child == body {
413
+ m.visit(child, &own, 0, token.ILLEGAL, false)
414
+ } else {
415
+ m.visit(child, outer, depth, token.ILLEGAL, false)
416
+ }
417
+ })
418
+ m.cyclomatic[number].Value = own.cyclomatic
419
+ m.cognitive[number].Value = own.cognitive
420
+ m.cognitiveTotal += own.cognitive
421
+
422
+ label := name
423
+ if label == "" {
424
+ label = "(anonymous)"
425
+ }
426
+ params := 0
427
+ for _, field := range signature.Params.List {
428
+ if len(field.Names) == 0 {
429
+ params++
430
+ } else {
431
+ params += len(field.Names)
432
+ }
433
+ }
434
+ m.observe("function-parameters", params, label+" · Parameters", node)
435
+ m.observe("return-statements", own.returns, label+" · Return statements", node)
436
+ m.observe("function-complexity", own.cognitive, label+" · Cognitive complexity", node)
437
+ if own.deepest != nil {
438
+ m.observe("nested-control-flow", own.maxDepth, label+" · Control-flow depth", own.deepest)
439
+ }
440
+ }
441
+
442
+ func methodName(declaration *ast.FuncDecl) string {
443
+ if declaration.Recv != nil && len(declaration.Recv.List) > 0 {
444
+ if receiver := receiverName(declaration.Recv.List[0].Type); receiver != "" {
445
+ return receiver + "." + declaration.Name.Name
446
+ }
447
+ }
448
+ return declaration.Name.Name
449
+ }
450
+
451
+ func receiverName(expression ast.Expr) string {
452
+ switch expression := expression.(type) {
453
+ case *ast.Ident:
454
+ return expression.Name
455
+ case *ast.StarExpr:
456
+ if name := receiverName(expression.X); name != "" {
457
+ return "(*" + name + ")"
458
+ }
459
+ case *ast.IndexExpr:
460
+ return receiverName(expression.X)
461
+ case *ast.IndexListExpr:
462
+ return receiverName(expression.X)
463
+ case *ast.ParenExpr:
464
+ return receiverName(expression.X)
465
+ }
466
+ return ""
467
+ }
468
+
469
+ type fingerprints struct {
470
+ exact, similar [sha256.Size]byte
471
+ nodes int
472
+ }
473
+
474
+ var (
475
+ nodeType = reflect.TypeOf((*ast.Node)(nil)).Elem()
476
+ positionType = reflect.TypeOf(token.NoPos)
477
+ )
478
+
479
+ func measureClones(path string, file *ast.File, layout sourceLayout, code []int, settings duplicationSettings) cloneSource {
480
+ result := cloneSource{Path: path, Scheme: "repometry.go-ast/v1", CodeLines: code, Candidates: []candidate{}}
481
+ if len(code) < settings.MinCodeLines {
482
+ return result
483
+ }
484
+
485
+ var walk func(ast.Node) fingerprints
486
+ walk = func(node ast.Node) fingerprints {
487
+ nodes := 1
488
+ syntax := reflect.ValueOf(node).Elem()
489
+ exact := []byte(syntax.Type().Name())
490
+ similar := []byte(syntax.Type().Name())
491
+
492
+ addChild := func(field reflect.Value) {
493
+ if field.IsNil() {
494
+ exact = append(exact, 0)
495
+ similar = append(similar, 0)
496
+ return
497
+ }
498
+ hashes := walk(field.Interface().(ast.Node))
499
+ nodes += hashes.nodes
500
+ exact = append(append(exact, 1), hashes.exact[:]...)
501
+ similar = append(append(similar, 1), hashes.similar[:]...)
502
+ }
503
+
504
+ for i := 0; i < syntax.NumField(); i++ {
505
+ field, definition := syntax.Field(i), syntax.Type().Field(i)
506
+ if !fingerprintField(definition) {
507
+ continue
508
+ }
509
+ exact = append(append(exact, '|'), definition.Name...)
510
+ similar = append(append(similar, '|'), definition.Name...)
511
+ exact, similar = append(exact, ':'), append(similar, ':')
512
+
513
+ switch {
514
+ case definition.Type.Implements(nodeType):
515
+ addChild(field)
516
+ case field.Kind() == reflect.Slice:
517
+ for j := 0; j < field.Len(); j++ {
518
+ addChild(field.Index(j))
519
+ }
520
+ default:
521
+ value := fingerprintValue(field, definition)
522
+ if literal, ok := node.(*ast.BasicLit); definition.Name == "Value" && ok && rawString(literal) {
523
+ value = string(layout.source[layout.tokens.Offset(literal.Pos()):layout.end(literal.End())])
524
+ }
525
+ exact = strconv.AppendQuote(exact, value)
526
+ if normalizedField(node, definition.Name) {
527
+ value = ""
528
+ }
529
+ similar = strconv.AppendQuote(similar, value)
530
+ }
531
+ }
532
+ hashes := fingerprints{sha256.Sum256(exact), sha256.Sum256(similar), nodes}
533
+ if nodes >= settings.MinNodes && cloneEligible(node) {
534
+ start, end := layout.tokens.Offset(node.Pos()), layout.end(node.End())
535
+ if end > start {
536
+ line, endLine := layout.line(start), layout.line(end-1)
537
+ count := sort.SearchInts(code, endLine+1) - sort.SearchInts(code, line)
538
+ if count >= settings.MinCodeLines {
539
+ result.Candidates = append(result.Candidates, candidate{
540
+ Start: start, End: end, Line: line, EndLine: endLine, CodeLines: count, Nodes: nodes,
541
+ Exact: base64.RawURLEncoding.EncodeToString(hashes.exact[:]), Similar: base64.RawURLEncoding.EncodeToString(hashes.similar[:]),
542
+ })
543
+ }
544
+ }
545
+ }
546
+ return hashes
547
+ }
548
+ forChildren(file, func(child ast.Node) {
549
+ if _, comment := child.(*ast.CommentGroup); !comment {
550
+ walk(child)
551
+ }
552
+ })
553
+ return result
554
+ }
555
+
556
+ func fingerprintField(field reflect.StructField) bool {
557
+ switch field.Name {
558
+ case "Doc", "Comment", "Comments", "Obj", "Scope", "Imports", "Unresolved", "GoVersion":
559
+ return false
560
+ }
561
+ if field.Type == positionType {
562
+ // These positions encode syntax not otherwise represented by an AST child or scalar.
563
+ return field.Name == "Assign" || field.Name == "Ellipsis"
564
+ }
565
+ return true
566
+ }
567
+
568
+ func fingerprintValue(field reflect.Value, definition reflect.StructField) string {
569
+ if definition.Type == positionType {
570
+ return strconv.FormatBool(field.Interface().(token.Pos).IsValid())
571
+ }
572
+ switch field.Kind() {
573
+ case reflect.String:
574
+ return field.String()
575
+ case reflect.Bool:
576
+ return strconv.FormatBool(field.Bool())
577
+ default:
578
+ return strconv.FormatInt(field.Int(), 10)
579
+ }
580
+ }
581
+
582
+ func normalizedField(node ast.Node, field string) bool {
583
+ switch node.(type) {
584
+ case *ast.Ident:
585
+ return field == "Name"
586
+ case *ast.BasicLit:
587
+ return field == "Value"
588
+ }
589
+ return false
590
+ }
591
+
592
+ func cloneEligible(node ast.Node) bool {
593
+ switch node := node.(type) {
594
+ case *ast.EmptyStmt:
595
+ return false
596
+ case *ast.GenDecl:
597
+ return node.Tok != token.IMPORT
598
+ case ast.Stmt, *ast.FuncDecl, *ast.FuncLit:
599
+ return true
600
+ }
601
+ return false
602
+ }