Repository navigation
Expand file tree
/
Copy pathtags.go
More file actions
268 lines (250 loc) · 11.1 KB
/
Copy pathtags.go
File metadata and controls
268 lines (250 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package codegraph
import (
"cmp"
"fmt"
"path"
"regexp"
"slices"
"strings"
"github.com/compforge/codegraph/internal/language"
"github.com/compforge/codegraph/pkg"
)
type Tag = pkg.Tag
const (
SymlinkTag = pkg.SymlinkTag
GitlinkTag = pkg.GitlinkTag
UnknownTag = pkg.UnknownTag
SourceTag = pkg.SourceTag
DocumentationTag = pkg.DocumentationTag
VersionTag = pkg.VersionTag
ResourceTag = pkg.ResourceTag
ToolingTag = pkg.ToolingTag
ConfigTag = pkg.ConfigTag
ManifestTag = pkg.ManifestTag
LockfileTag = pkg.LockfileTag
GeneratedTag = pkg.GeneratedTag
TestTag = pkg.TestTag
TestFixtureTag = pkg.TestFixtureTag
DependencyTag = pkg.DependencyTag
BuildOutputTag = pkg.BuildOutputTag
CacheTag = pkg.CacheTag
MinifiedTag = pkg.MinifiedTag
)
// TagRule assigns Name to each Document or Directory whose snapshot-relative
// slash-separated path matches Pattern. Directory paths have no trailing slash;
// the root is ".". Patterns use Go regular expressions (unanchored unless specified).
// Languages optionally restricts matches to grammar names recognized from the path;
// an empty list adds no language restriction. It never loads parsers or source bytes.
// +spec=Plain path matches confirm their tag. Contextual rules resolve evidence per material and tag.
type TagRule struct {
Name Tag
Pattern string
Languages []string
// Kind optionally restricts this rule to DocumentNodeKind or DirectoryNodeKind.
Kind NodeKind `json:",omitempty"`
// Observe returns evidence when the path filter matches. Nil confirms a matching pattern.
// Callbacks must be deterministic, concurrency safe and treat the input as read-only.
Observe func(TagMaterial) []TagEvidence `json:",omitempty"`
// Resolve optionally combines soft evidence for Name. At most one rule may set it per tag.
Resolve func([]TagEvidence) TagDecision `json:",omitempty"`
}
// BuiltinTagRules returns a fresh rule set for common repository material.
// Callers may append custom rules or supply a replacement through Options.TagRules.
// Tags describe path conventions; consumers decide whether to exclude material.
// +spec=Test tags use naming conventions and shared language recognition, not a separate extension list or proof of execution.
// +why=Consumers extend shared classification instead of replacing tags to express admission or review policy.
// +spec=Generated tags recognize explicit output naming conventions without reading content or requiring parser support.
// +link=component://docs/document.md
// +case=generated_document_tags
func BuiltinTagRules() []TagRule {
return []TagRule{
{Name: ManifestTag, Pattern: `(^|/)(go\.mod|go\.work|pyproject\.toml|package\.json)$`},
{Name: VersionTag, Pattern: `(^|/)VERSION$`},
{Name: LockfileTag, Pattern: `(^|/)(go\.sum|go\.work\.sum|uv\.lock|poetry\.lock|Pipfile\.lock|pdm\.lock|pylock(\.[^/]+)?\.toml|package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?|Cargo\.lock|Gemfile\.lock|composer\.lock)$`},
{Name: GeneratedTag, Pattern: `(?i)\.generated\.[^/]+$`},
{Name: GeneratedTag, Pattern: `(?i)\.(gen\.go|pb(\.gw)?\.go)$`},
{Name: GeneratedTag, Pattern: `(?i)_pb2(_grpc)?\.pyi?$`},
{Name: GeneratedTag, Pattern: `(?i)\.(pb\.(cc|h)|pb-c\.(c|h))$`},
{Name: GeneratedTag, Pattern: `(?i)(\.capnp\.(h|c\+\+|go|ts)|_capnp\.(rs|py))$`},
// Source maps need no grammar; a bare .map or declaration file is ambiguous.
{Name: GeneratedTag, Pattern: `(?i)\.(js|jsx|mjs|cjs|css|d\.(ts|mts|cts))\.map$`},
{Name: GeneratedTag, Pattern: `(?i)(^|/)kitex_gen(/|$)`},
{Name: TestTag, Pattern: `(?i)(^|/)[^/]*_test\.(go|rs)$`},
{Name: TestTag, Pattern: `(?i)(^|/)(test_[^/]*|[^/]*_test)\.py$`},
{Name: TestTag, Pattern: `(^|/)[^/]*\.(test|spec)\.[^/]+$`, Languages: []string{"javascript", "typescript", "tsx"}},
{Name: TestTag, Pattern: `(^|/)__tests__/`, Languages: []string{"javascript", "typescript", "tsx"}},
{Name: TestTag, Pattern: `(?i)(^|/)[^/]*_spec\.rb$`},
{Name: TestTag, Pattern: `(^|/)[^/]*Tests?\.java$|(^|/)src/test/.*\.(java|kt)$`},
{Name: TestTag, Pattern: `(?i)\.test\.ets$`},
{Name: TestFixtureTag, Pattern: `(^|/)(testdata|fixtures|snapshots|__snapshots__)(/|$)`},
{Name: DependencyTag, Pattern: `(?i)(^|/)(vendor|node_modules|oh_modules|bower_components|\.pnpm-store|\.bundle|\.venv|venv|site-packages|pods|carthage)(/|$)`},
{Name: DependencyTag, Pattern: `(?i)(^|/)\.yarn/(cache|unplugged|releases|sdks)(/|$)|(^|/)\.pnp\.(cjs|loader\.mjs)$|(^|/)[^/]*\.egg-info(/|$)`},
{Name: BuildOutputTag, Pattern: `(?i)(^|/)(dist|\.next|\.nuxt|\.svelte-kit|\.astro|\.docusaurus|\.build|obj)(/|$)|(^|/)coverage/lcov-report(/|$)`},
{Name: BuildOutputTag, Kind: DirectoryNodeKind, Pattern: `(?i)(^|/)target$`, Observe: targetEvidence, Resolve: resolveTarget},
{Name: CacheTag, Pattern: `(?i)(^|/)(\.cache|__pycache__|\.pytest_cache|\.mypy_cache|\.ruff_cache|\.happypack|\.turbo|\.angular|\.parcel-cache|\.gradle|\.tox|\.dart_tool|\.terraform|\.stack-work)(/|$)`},
{Name: MinifiedTag, Pattern: `(?i)\.min\.(js|css)$`},
{Name: ToolingTag, Pattern: `(^|/)(\.git|\.svn|\.idea|\.vscode|\.codebase|\.devloop|\.codex|\.claude|\.agents|\.cursor)(/|$)`},
{Name: ConfigTag, Pattern: `(^|/)(\.dockerignore|\.gitignore|\.ignore|\.gitattributes|\.editorconfig|\.env(\.[^/]+)?)$`},
{Name: ToolingTag, Pattern: `(^|/)(AGENTS|CLAUDE|GEMINI)\.md$`},
}
}
type compiledTagRule struct {
name Tag
pattern *regexp.Regexp
languages []string
kind NodeKind
observe func(TagMaterial) []TagEvidence
}
// TagMatcher applies compiled path rules without reading files or constructing a graph.
// It is immutable after construction and safe for concurrent Match calls.
// The zero value has no path rules; DocumentTags still classifies formats.
type TagMatcher struct {
rules []compiledTagRule
resolvers map[Tag]func([]TagEvidence) TagDecision
lookup TagLookup
}
// NewTagMatcher validates and compiles rules. Nil selects BuiltinTagRules;
// an explicit empty slice disables path tags. Later changes to rules do not affect
// the matcher. Invalid regular expressions and blank names return an error.
// +why=Graph construction and consumers share one path classification implementation.
func NewTagMatcher(rules []TagRule) (*TagMatcher, error) {
if rules == nil {
rules = BuiltinTagRules()
}
resolvers := map[Tag]func([]TagEvidence) TagDecision{}
out := make([]compiledTagRule, 0, len(rules))
for i, rule := range rules {
if strings.TrimSpace(string(rule.Name)) == "" {
return nil, fmt.Errorf("tag rule %d: name is required", i)
}
pattern, err := regexp.Compile(rule.Pattern)
if err != nil {
return nil, fmt.Errorf("tag rule %d (%q): %w", i, rule.Name, err)
}
if rule.Kind != "" && rule.Kind != DirectoryNodeKind && rule.Kind != DocumentNodeKind {
return nil, fmt.Errorf("tag rule %d: unsupported material kind %q", i, rule.Kind)
}
if rule.Resolve != nil {
if resolvers[rule.Name] != nil {
return nil, fmt.Errorf("tag rule %d: duplicate resolver for %q", i, rule.Name)
}
resolvers[rule.Name] = rule.Resolve
}
out = append(out, compiledTagRule{kind: rule.Kind, observe: rule.Observe, name: rule.Name, pattern: pattern, languages: slices.Clone(rule.Languages)})
}
return &TagMatcher{rules: out, resolvers: resolvers}, nil
}
// Match returns all matching tags, deduplicated and sorted by name, or nil if none match.
// Path must be a normalized snapshot-relative, slash-separated path; directory
// paths have no trailing slash and the root is ".". Match does not normalize paths.
// The returned slice belongs to the caller. Tags are not inherited from ancestors.
func (m *TagMatcher) Match(path string) []Tag {
return m.tags(TagMaterial{Path: path}, false)
}
// DirectoryTags classifies a directory with the same evidence protocol as DocumentTags.
func (m *TagMatcher) DirectoryTags(name string) []Tag {
return m.tags(TagMaterial{Kind: DirectoryNodeKind, Path: name}, false)
}
func (m *TagMatcher) DocumentTags(d Document) []Tag {
return m.tags(TagMaterial{Kind: DocumentNodeKind, Path: d.Path, Content: d.Content, Gitlink: d.Gitlink, Symlink: d.Symlink}, true)
}
func (m *TagMatcher) tags(subject TagMaterial, fallback bool) []Tag {
observations := m.observe(subject, "")
var tags []Tag
for tag, evidence := range observations {
if m.resolve(tag, evidence) == TagYes {
tags = append(tags, tag)
}
}
if fallback && len(tags) == 0 {
return []Tag{UnknownTag}
}
slices.Sort(tags)
return tags
}
// Decision explains the direct classification of one tag, before the unknown document fallback.
func (m *TagMatcher) Decision(subject TagMaterial, tag Tag) (TagDecision, []TagEvidence) {
evidence := m.observe(subject, tag)[tag]
return m.resolve(tag, evidence), evidence
}
func (m *TagMatcher) observe(subject TagMaterial, only Tag) map[Tag][]TagEvidence {
subject.Lookup = m.lookup
evidence := map[Tag][]TagEvidence{}
for _, rule := range m.rules {
if (only != "" && rule.name != only) || (rule.kind != "" && subject.Kind != rule.kind) || !rule.pattern.MatchString(subject.Path) {
continue
}
if len(rule.languages) > 0 && !slices.Contains(rule.languages, Language(subject.Path)) {
continue
}
if rule.observe == nil {
evidence[rule.name] = append(evidence[rule.name], TagEvidence{Confirm, rule.pattern.String()})
} else if seen := rule.observe(subject); len(seen) > 0 {
evidence[rule.name] = append(evidence[rule.name], seen...)
}
}
if subject.Kind == DocumentNodeKind {
var tag Tag
switch {
case subject.Symlink != "":
tag = SymlinkTag
case subject.Gitlink != "":
tag = GitlinkTag
default:
tag = Tag(language.MaterialTag(subject.Path))
}
if tag != "" && (only == "" || only == tag) {
evidence[tag] = append(evidence[tag], TagEvidence{Confirm, "document format or link"})
}
}
return evidence
}
func (m *TagMatcher) resolve(tag Tag, evidence []TagEvidence) TagDecision {
slices.SortFunc(evidence, func(a, b TagEvidence) int {
if c := cmp.Compare(a.Signal, b.Signal); c != 0 {
return c
}
return cmp.Compare(a.Reason, b.Reason)
})
var confirmed, vetoed bool
for _, e := range evidence {
confirmed = confirmed || e.Signal == Confirm
vetoed = vetoed || e.Signal == Veto
}
switch {
case confirmed && vetoed:
return TagUndecided
case confirmed:
return TagYes
case vetoed:
return TagNo
}
if resolve := m.resolvers[tag]; len(evidence) > 0 && resolve != nil {
return resolve(slices.Compact(slices.Clone(evidence)))
}
return TagUndecided
}
// ExcludedBy returns the first matching exclusion tag on the document or an
// ancestor directory, or empty when admitted. It does not inherit directory tags
// into DocumentTags. Document paths must be normalized snapshot-relative paths.
// +spec=Consumers and Builder apply the same material exclusions before parsing and document budgets.
func (m *TagMatcher) ExcludedBy(d Document, excluded []Tag) Tag {
if len(excluded) == 0 {
return ""
}
for _, tag := range m.DocumentTags(d) {
if slices.Contains(excluded, tag) {
return tag
}
}
for current := path.Dir(d.Path); ; current = path.Dir(current) {
for _, tag := range m.DirectoryTags(current) {
if slices.Contains(excluded, tag) {
return tag
}
}
if current == "." {
return ""
}
}
}