repometry 0.6.2 → 0.8.0

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 (153) hide show
  1. package/README.md +3 -0
  2. package/package.json +1 -1
  3. package/target/main/resources/config/process-plugins-v1.schema.json +79 -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/report-v2.schema.json +21 -1
  7. package/target/main/resources/report/json/repository-summary-v1.schema.json +9 -0
  8. package/target/main/resources/report/json/viewer-inspection-v1.schema.json +12 -3
  9. package/target/main/resources/viewer/files.css +7 -0
  10. package/target/main/resources/viewer/index.html +1 -1
  11. package/target/main/resources/viewer/styles.css +1 -0
  12. package/target/main/ts/api/git/git-reader.d.ts +10 -2
  13. package/target/main/ts/api/git/git-reader.js +74 -35
  14. package/target/main/ts/api/git/git.d.ts +19 -1
  15. package/target/main/ts/api/git/git.js +97 -7
  16. package/target/main/ts/api/import/go-cover.d.ts +13 -0
  17. package/target/main/ts/api/import/go-cover.js +150 -0
  18. package/target/main/ts/api/import/lcov-files.d.ts +6 -1
  19. package/target/main/ts/api/import/lcov-files.js +27 -7
  20. package/target/main/ts/api/process/docker-tool-runner.js +5 -21
  21. package/target/main/ts/api/process/host-language-runner.d.ts +13 -0
  22. package/target/main/ts/api/process/host-language-runner.js +176 -0
  23. package/target/main/ts/api/process/plugin.d.ts +4 -1
  24. package/target/main/ts/api/process/plugin.js +7 -3
  25. package/target/main/ts/api/process/tool-snapshot.d.ts +3 -0
  26. package/target/main/ts/api/process/tool-snapshot.js +26 -0
  27. package/target/main/ts/cli/config.d.ts +1 -0
  28. package/target/main/ts/cli/config.js +3 -2
  29. package/target/main/ts/cli/imports.d.ts +1 -0
  30. package/target/main/ts/cli/imports.js +5 -2
  31. package/target/main/ts/cli/main.js +76 -27
  32. package/target/main/ts/cli/reporting.js +3 -3
  33. package/target/main/ts/compose/analysis-files.d.ts +3 -1
  34. package/target/main/ts/compose/analysis-files.js +46 -12
  35. package/target/main/ts/compose/analysis-imports.js +4 -2
  36. package/target/main/ts/compose/analysis-report.d.ts +1 -0
  37. package/target/main/ts/compose/analysis-report.js +20 -15
  38. package/target/main/ts/compose/analysis-repository.d.ts +2 -1
  39. package/target/main/ts/compose/analysis-repository.js +42 -4
  40. package/target/main/ts/compose/analysis-results.d.ts +4 -1
  41. package/target/main/ts/compose/analysis-results.js +3 -0
  42. package/target/main/ts/compose/analysis-sources.d.ts +5 -0
  43. package/target/main/ts/compose/analysis-sources.js +11 -3
  44. package/target/main/ts/compose/analyze-snapshot.d.ts +2 -1
  45. package/target/main/ts/compose/analyze-snapshot.js +5 -3
  46. package/target/main/ts/compose/diff-coverage.d.ts +2 -1
  47. package/target/main/ts/compose/diff-coverage.js +8 -6
  48. package/target/main/ts/compose/history-cache.d.ts +29 -0
  49. package/target/main/ts/compose/history-cache.js +57 -0
  50. package/target/main/ts/compose/inspect.d.ts +6 -1
  51. package/target/main/ts/compose/inspect.js +10 -10
  52. package/target/main/ts/compose/inspection-coverage.d.ts +9 -0
  53. package/target/main/ts/compose/inspection-coverage.js +9 -0
  54. package/target/main/ts/compose/languages.d.ts +6 -1
  55. package/target/main/ts/compose/languages.js +23 -7
  56. package/target/main/ts/compose/native-language-plugins.d.ts +6 -0
  57. package/target/main/ts/compose/native-language-plugins.js +40 -0
  58. package/target/main/ts/compose/plugin-list.d.ts +7 -3
  59. package/target/main/ts/compose/plugin-list.js +13 -3
  60. package/target/main/ts/compose/prepare-metabranch.js +1 -1
  61. package/target/main/ts/compose/process-plugins.d.ts +2 -0
  62. package/target/main/ts/compose/process-plugins.js +64 -0
  63. package/target/main/ts/compose/review.d.ts +1 -2
  64. package/target/main/ts/compose/review.js +2 -2
  65. package/target/main/ts/compose/structure-measures.d.ts +5 -0
  66. package/target/main/ts/compose/structure-measures.js +57 -0
  67. package/target/main/ts/core/engine/manifest.js +5 -1
  68. package/target/main/ts/core/engine/plan.js +5 -6
  69. package/target/main/ts/core/engine/plugin.d.ts +2 -0
  70. package/target/main/ts/core/model/clone-source.js +0 -1
  71. package/target/main/ts/core/model/code-structure.d.ts +14 -9
  72. package/target/main/ts/core/model/code-structure.js +23 -10
  73. package/target/main/ts/core/model/file-types.d.ts +1 -0
  74. package/target/main/ts/core/model/file-types.js +14 -3
  75. package/target/main/ts/core/model/language.d.ts +2 -0
  76. package/target/main/ts/core/model/plugin-data.d.ts +2 -0
  77. package/target/main/ts/core/model/quality-summary.d.ts +4 -0
  78. package/target/main/ts/core/model/quality-summary.js +55 -29
  79. package/target/main/ts/core/model/report.d.ts +6 -0
  80. package/target/main/ts/core/model/source.d.ts +2 -0
  81. package/target/main/ts/core/usecases/inspect.d.ts +1 -1
  82. package/target/main/ts/core/usecases/inspect.js +1 -1
  83. package/target/main/ts/plugin.d.ts +1 -1
  84. package/target/main/ts/plugins/coverage/coverage.d.ts +2 -1
  85. package/target/main/ts/plugins/coverage/coverage.js +40 -30
  86. package/target/main/ts/plugins/language-js/function-facts.d.ts +1 -1
  87. package/target/main/ts/plugins/language-js/function-facts.js +0 -1
  88. package/target/main/ts/plugins/language-js/js-security.js +25 -37
  89. package/target/main/ts/plugins/language-js/structural-observations.js +5 -4
  90. package/target/main/ts/plugins/maintainability/maintainability.d.ts +1 -1
  91. package/target/main/ts/plugins/maintainability/maintainability.js +9 -8
  92. package/target/main/ts/plugins/security/dockerfile.js +51 -52
  93. package/target/main/ts/plugins/structure/structure.js +2 -2
  94. package/target/main/ts/report/html/app/viewer-code-map.js +6 -5
  95. package/target/main/ts/report/html/app/viewer-columns.d.ts +2 -0
  96. package/target/main/ts/report/html/app/viewer-columns.js +9 -4
  97. package/target/main/ts/report/html/app/viewer-data.d.ts +2 -1
  98. package/target/main/ts/report/html/app/viewer-data.js +1 -1
  99. package/target/main/ts/report/html/app/viewer-file-aside.d.ts +5 -9
  100. package/target/main/ts/report/html/app/viewer-file-aside.js +18 -8
  101. package/target/main/ts/report/html/app/viewer-file-figures.d.ts +2 -0
  102. package/target/main/ts/report/html/app/viewer-file-figures.js +6 -1
  103. package/target/main/ts/report/html/app/viewer-hotspots.js +7 -5
  104. package/target/main/ts/report/html/app/viewer-inspection.js +1 -1
  105. package/target/main/ts/report/html/app/viewer-issue-group.js +2 -2
  106. package/target/main/ts/report/html/app/viewer-language-bar.d.ts +2 -0
  107. package/target/main/ts/report/html/app/viewer-language-bar.js +5 -1
  108. package/target/main/ts/report/html/app/viewer-languages.d.ts +3 -2
  109. package/target/main/ts/report/html/app/viewer-languages.js +14 -7
  110. package/target/main/ts/report/html/app/viewer-line-coverage.d.ts +4 -4
  111. package/target/main/ts/report/html/app/viewer-line-coverage.js +11 -24
  112. package/target/main/ts/report/html/app/viewer-map-scale.d.ts +1 -1
  113. package/target/main/ts/report/html/app/viewer-map-scale.js +1 -1
  114. package/target/main/ts/report/html/app/viewer-map-shape.d.ts +2 -2
  115. package/target/main/ts/report/html/app/viewer-metric-registry.d.ts +0 -3
  116. package/target/main/ts/report/html/app/viewer-metric-registry.js +0 -9
  117. package/target/main/ts/report/html/app/viewer-metrics-view.js +1 -4
  118. package/target/main/ts/report/html/app/viewer-metrics.d.ts +2 -0
  119. package/target/main/ts/report/html/app/viewer-metrics.js +5 -0
  120. package/target/main/ts/report/html/app/viewer-overview-cards.js +4 -1
  121. package/target/main/ts/report/html/app/viewer-overview-hotspots.js +2 -2
  122. package/target/main/ts/report/html/app/viewer-profile.js +22 -1
  123. package/target/main/ts/report/html/app/viewer-source-view.js +7 -6
  124. package/target/main/ts/report/html/app/viewer-table-cells.js +8 -2
  125. package/target/main/ts/report/html/app/viewer-table-rows.d.ts +2 -0
  126. package/target/main/ts/report/html/app/viewer-table-rows.js +7 -5
  127. package/target/main/ts/report/html/app/viewer-tokenizer.d.ts +2 -5
  128. package/target/main/ts/report/html/app/viewer-tokenizer.js +9 -12
  129. package/target/main/ts/report/html/app/viewer-totals.d.ts +6 -0
  130. package/target/main/ts/report/html/app/viewer-totals.js +11 -0
  131. package/target/main/ts/report/html/app/viewer-trend-data.d.ts +1 -1
  132. package/target/main/ts/report/html/app/viewer-trend-data.js +1 -1
  133. package/target/main/ts/report/html/app/viewer-trend-nav.js +3 -2
  134. package/target/main/ts/report/html/app/viewer.js +1 -7
  135. package/target/main/ts/report/json/projections/commit-summary.d.ts +1 -0
  136. package/target/main/ts/report/json/projections/commit-summary.js +10 -0
  137. package/target/main/ts/report/json/projections/file-metrics.js +56 -45
  138. package/target/main/ts/report/json/projections/inspection-details.js +33 -14
  139. package/target/main/ts/report/json/projections/metric-values.d.ts +1 -0
  140. package/target/main/ts/report/json/projections/metric-values.js +36 -3
  141. package/target/main/ts/report/json/store/directory.d.ts +3 -0
  142. package/target/main/ts/report/json/store/directory.js +19 -0
  143. package/target/main/ts/report/json/store/local-store.d.ts +14 -2
  144. package/target/main/ts/report/json/store/local-store.js +74 -60
  145. package/target/main/ts/report/json/store/object-store.d.ts +14 -0
  146. package/target/main/ts/report/json/store/object-store.js +73 -0
  147. package/target/main/ts/report/json/store/report-tree.d.ts +46 -0
  148. package/target/main/ts/report/json/store/report-tree.js +290 -0
  149. package/target/main/ts/report/json/store/store-check.d.ts +32 -0
  150. package/target/main/ts/report/json/store/store-check.js +144 -0
  151. package/target/main/ts/report/json/validation/report.d.ts +6 -1
  152. package/target/main/ts/report/json/validation/report.js +10 -4
  153. package/target/main/ts/report/json/wire/inspection-details-model.d.ts +9 -1
package/README.md CHANGED
@@ -39,6 +39,9 @@ npx repometry view
39
39
  # Export a static report to .repometry/report/html. Use -o DIR for another folder.
40
40
  npx repometry report html
41
41
 
42
+ # Check saved inspections. --repair restores missing data from a copy.
43
+ npx repometry store check --repair --from git:repometry
44
+
42
45
  # List supported formats and get help for a command.
43
46
  npx repometry plugins
44
47
  npx repometry help analyze
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "repometry",
3
- "version": "0.6.2",
3
+ "version": "0.8.0",
4
4
  "description": "Track repository metrics without SaaS",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -0,0 +1,79 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "urn:repometry:schema:process-plugins:1",
4
+ "title": "Repometry process plugins",
5
+ "type": "array",
6
+ "items": {
7
+ "type": "object",
8
+ "additionalProperties": false,
9
+ "required": ["id", "version", "image", "command", "scope", "tools", "providesLanguages"],
10
+ "properties": {
11
+ "id": { "$ref": "#/$defs/id" },
12
+ "version": { "$ref": "#/$defs/text" },
13
+ "image": {
14
+ "type": "string",
15
+ "pattern": "^(?:[a-z0-9][a-z0-9.:/_-]*@)?sha256:[a-f0-9]{64}$",
16
+ "description": "The full ID or distribution digest of a locally available Docker image."
17
+ },
18
+ "command": {
19
+ "type": "array",
20
+ "minItems": 1,
21
+ "items": { "type": "string", "pattern": "^[^\\u0000]*$" }
22
+ },
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
+ },
28
+ "claims": {
29
+ "type": "object",
30
+ "additionalProperties": false,
31
+ "properties": {
32
+ "extensions": { "$ref": "#/$defs/extensions" },
33
+ "globs": { "$ref": "#/$defs/globs" }
34
+ }
35
+ },
36
+ "limits": {
37
+ "type": "object",
38
+ "additionalProperties": false,
39
+ "properties": {
40
+ "timeoutMs": { "type": "integer", "minimum": 1, "maximum": 2147483647 },
41
+ "maxOutputBytes": { "$ref": "#/$defs/positiveInteger" },
42
+ "memoryBytes": { "$ref": "#/$defs/positiveInteger" },
43
+ "pidsLimit": { "$ref": "#/$defs/positiveInteger" }
44
+ }
45
+ },
46
+ "tools": { "type": "object", "minProperties": 1, "additionalProperties": { "$ref": "#/$defs/text" } },
47
+ "settings": true,
48
+ "providesLanguages": {
49
+ "type": "array",
50
+ "minItems": 1,
51
+ "items": {
52
+ "type": "object",
53
+ "additionalProperties": false,
54
+ "required": ["id", "label"],
55
+ "properties": {
56
+ "id": { "$ref": "#/$defs/id" },
57
+ "label": { "$ref": "#/$defs/text" },
58
+ "color": { "type": "string", "pattern": "^#[0-9A-Fa-f]{6}$" },
59
+ "extensions": { "$ref": "#/$defs/extensions" },
60
+ "globs": { "$ref": "#/$defs/globs" },
61
+ "measures": {
62
+ "type": "array",
63
+ "uniqueItems": true,
64
+ "items": { "enum": ["functions", "cyclomaticComplexity", "cognitiveComplexity", "classes",
65
+ "commentLines", "codeLines", "duplication", "structuralRules"] }
66
+ }
67
+ }
68
+ }
69
+ }
70
+ }
71
+ },
72
+ "$defs": {
73
+ "id": { "type": "string", "pattern": "^[a-z][a-z0-9-]*$" },
74
+ "text": { "type": "string", "pattern": "\\S" },
75
+ "positiveInteger": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 },
76
+ "extensions": { "type": "array", "uniqueItems": true, "items": { "type": "string", "pattern": "^\\.[\\w-]+$" } },
77
+ "globs": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/text" } }
78
+ }
79
+ }
@@ -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
+ }