sourceref

package
v0.50.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

README

pkg/sourceref

specscore: annotation parsing and source-to-spec linking. Detects and parses references from source code comments.

Outstanding Questions

  1. sourceref.go hardcodes "github.com", "specscore" as the "current" repo defaults used by parseExpandedURL to determine whether a cross-repo suffix is needed. Should these be configurable via a parameter or context struct so the library works for any project? For now, these match the original behavior.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (

	// DetectionRegex is rebuilt when prefixes change.
	DetectionRegex *regexp.Regexp
)

Functions

func DetectReference

func DetectReference(line string) bool

DetectReference checks if a line contains a source reference.

func ExpandGlobPattern

func ExpandGlobPattern(pattern string) ([]string, error)

ExpandGlobPattern expands a glob pattern to a list of file paths. Returns sorted file paths.

Supported patterns:

  • "**/*" or "**" — matches all files recursively (special-cased)
  • "**" as a path segment — matches any number of directory segments (including zero), so "pkg/**/*.go" matches "pkg/a.go", "pkg/sub/b.go", and "pkg/sub/deep/c.go" (cli/code/deps#req:path-glob).
  • Standard filepath.Match patterns (e.g. "*.go", "src/*.txt"); a single "*" or "?" never crosses a "/" separator.

func ExtractReference

func ExtractReference(line string) string

ExtractReference extracts the reference string from a line.

func FormatOutput

func FormatOutput(result *ScanResult, singleFile bool, typeFilter string) string

FormatOutput formats the scan results for output. If singleFile is true, returns a flat list. Otherwise, groups by file with headers.

func RegisterPrefix

func RegisterPrefix(prefix string)

RegisterPrefix adds a short-notation prefix (e.g. "mytool") so that "mytool:feature/foo" is recognized as a source reference. Also registers "mytool.io" as an expanded URL domain.

func ValidateDirective added in v0.40.0

func ValidateDirective(d *Directive) error

ValidateDirective validates a parsed directive's relation and target.

func ValidateRelationTarget added in v0.40.0

func ValidateRelationTarget(relation Relation, target *Reference) error

ValidateRelationTarget applies the relation-to-resource rules owned by SpecScore. It does not inspect the source symbol kind; executable-test attachment is a provider concern.

func ValidateRelationTargetString added in v0.40.0

func ValidateRelationTargetString(relation Relation, raw string) error

ValidateRelationTargetString parses and validates an authoring-form target in one step. It is a convenience for linter and provider adapters that keep directives as text until validation.

Types

type Directive added in v0.40.0

type Directive struct {
	Relation Relation   `json:"relation"`
	Target   *Reference `json:"target"`
	Line     int        `json:"line,omitempty"`
}

Directive is a typed source annotation. Source-line information is retained for callers that scan files themselves; symbol attachment is deliberately left to language-aware providers such as CodeGrapher.

func ParseDirective added in v0.40.0

func ParseDirective(line string) (*Directive, error)

ParseDirective parses one typed source directive. An unqualified source reference is also accepted and gets references semantics. The target may be a short reference, a specscore authority reference, or a canonical https://specscore.org URL.

func ScanDirective added in v0.40.0

func ScanDirective(line string) *Directive

ScanDirective scans one source line and returns nil when it has no SpecScore annotation. It is intentionally syntax-agnostic: providers may later attach the directive to the nearest parsed symbol.

func (Directive) Canonical added in v0.40.0

func (d Directive) Canonical() string

Canonical returns the directive with its target in canonical URL form. REQ and AC fragment prefixes are normalized to lowercase; other fragments stay opaque to this package.

type LegacySuffixError added in v0.16.0

type LegacySuffixError struct {
	Rewrite string
}

LegacySuffixError is returned by ParseReference when a reference uses the removed `specscore:{reference}@{host}/{org}/{repo}` suffix form (decision 0010). Rewrite carries the exact authority-form replacement that `--fix` applies.

func (*LegacySuffixError) Error added in v0.16.0

func (e *LegacySuffixError) Error() string

type LocalResolver added in v0.33.0

type LocalResolver struct {
	// contains filtered or unexported fields
}

LocalResolver resolves source references only from the current project and explicitly configured local projects. It never fetches from a network.

func NewLocalResolver added in v0.33.0

func NewLocalResolver(specRoot string) *LocalResolver

NewLocalResolver builds an offline resolver for a project's spec directory.

func (*LocalResolver) ValidateFeatureCitation added in v0.41.0

func (r *LocalResolver) ValidateFeatureCitation(ref *Reference) ([]byte, error)

ValidateFeatureCitation proves a Feature, REQ, or AC citation resolves from the current project or an explicitly configured local mirror. Typed source directives use lowercase #req: and #ac: fragments; legacy uppercase #REQ: and #AC: spellings remain accepted. specscore:implements https://specscore.org/github.com/specscore/specscore-cli/spec/features/cli/code/deps#req:offline-typed-source-link-check

func (*LocalResolver) ValidateRequirementCitation added in v0.33.0

func (r *LocalResolver) ValidateRequirementCitation(ref *Reference) ([]byte, error)

ValidateRequirementCitation proves a feature #REQ:<id> citation resolves to one real Markdown H4 outside fenced code. A feature without a fragment is a resource citation and is checked for existence only. Other non-empty fragments are rejected rather than being silently treated as live.

type ParseError added in v0.33.0

type ParseError struct {
	Line  int
	Token string
	Err   error
}

type Reference

type Reference struct {
	ResolvedPath    string `json:"resolved_path"`
	CrossRepoSuffix string `json:"cross_repo_suffix,omitempty"`
	Type            string `json:"type,omitempty"`
	// Fragment is the decoded address fragment, without its leading '#'. It is
	// deliberately opaque to this package: consumers such as spec lint decide
	// which resource-specific fragments they can resolve.
	Fragment string `json:"fragment,omitempty"`
	// Ref preserves a ?ref=<git-ref> pin (branch, tag, or commit) through
	// parsing and canonicalization. Parsers do not fetch it; an explicit local
	// resolver may require an exact checked-out revision before validating it.
	Ref string `json:"ref,omitempty"`
	// contains filtered or unexported fields
}

Reference represents a parsed source reference found in source code.

func GetUniqueReferences

func GetUniqueReferences(result *ScanResult, typeFilter string) []*Reference

GetUniqueReferences extracts unique references from a ScanResult, optionally filtered by type. Returns references sorted by (resolved_path, cross_repo_suffix).

func ParseReference

func ParseReference(extracted string) (*Reference, error)

ParseReference parses an extracted reference string and returns a Reference.

func ScanLine

func ScanLine(line string) *Reference

ScanLine scans a single line for references. Returns nil if none found.

func (Reference) Canonical added in v0.33.0

func (r Reference) Canonical() string

Canonical returns a parseable, authority-form source reference. It preserves both the optional revision pin and the resource fragment so consumers can round-trip a parsed citation without dropping its addressing semantics.

func (Reference) CanonicalTyped added in v0.40.0

func (r Reference) CanonicalTyped() string

CanonicalTyped returns the parseable canonical reference with the resource-specific fragment prefix normalized for typed traceability.

type Relation added in v0.40.0

type Relation string

Relation is the semantic relationship between a source location and a SpecScore target.

const (
	RelationImplements Relation = "implements"
	RelationVerifies   Relation = "verifies"
	RelationReferences Relation = "references"
)

type ScanResult

type ScanResult struct {
	// FileRefs maps file path to list of references found in that file
	FileRefs map[string][]*Reference
	// ParseErrors records syntactically detected annotations that could not be
	// parsed. Listing mode remains backward-compatible; validation mode reports
	// these deterministic file/line diagnostics instead of silently dropping them.
	ParseErrors map[string][]ParseError
}

ScanResult represents the references found in a set of files.

func ScanFiles

func ScanFiles(filePaths []string) (*ScanResult, error)

ScanFiles scans a list of files for source references. Returns a ScanResult with all references grouped by file. The result may be partial if some files fail; errors are accumulated and returned alongside whatever refs were successfully scanned.

type SourceRef

type SourceRef struct {
	FilePath    string
	LineNumber  int
	LineContent string
}

SourceRef represents a source file reference (file + line number).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL