parser

package
v0.32.1 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2025 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ImportCacheDir is the directory where cached imports are stored
	ImportCacheDir = ".github/aw/imports"
)

Variables

View Source
var IncludeDirectivePattern = regexp.MustCompile(`^(?:@(?:include|import)(\?)?\s+(.+)|{{#import(\?)?\s*:?\s*(.+?)\s*}})$`)

IncludeDirectivePattern matches @include, @import (deprecated), or {{#import (new) directives The colon after #import is optional and ignored if present

View Source
var LegacyIncludeDirectivePattern = regexp.MustCompile(`^@(?:include|import)(\?)?\s+(.+)$`)

LegacyIncludeDirectivePattern matches only the deprecated @include and @import directives

View Source
var ValidMCPTypes = []string{"stdio", "http", "local"}

ValidMCPTypes defines all supported MCP server types. "local" is an alias for "stdio" and gets normalized during parsing.

Functions

func EnsureLocalhostDomains added in v0.8.3

func EnsureLocalhostDomains(domains []string) []string

EnsureLocalhostDomains ensures that localhost and 127.0.0.1 are always included in the allowed domains list for Playwright, even when custom domains are specified Includes port variations to allow all ports on localhost and 127.0.0.1

func EnsureToolsSection added in v0.8.3

func EnsureToolsSection(frontmatter map[string]any) map[string]any

EnsureToolsSection ensures the tools section exists in frontmatter and returns it

func ExpandIncludes

func ExpandIncludes(content, baseDir string, extractTools bool) (string, error)

ExpandIncludes recursively expands @include and @import directives until no more remain This matches the bash expand_includes function behavior

func ExpandIncludesForEngines added in v0.5.1

func ExpandIncludesForEngines(content, baseDir string) ([]string, error)

ExpandIncludesForEngines recursively expands @include and @import directives to extract engine configurations

func ExpandIncludesForSafeOutputs added in v0.14.1

func ExpandIncludesForSafeOutputs(content, baseDir string) ([]string, error)

ExpandIncludesForSafeOutputs recursively expands @include and @import directives to extract safe-outputs configurations

func ExpandIncludesWithManifest added in v0.14.1

func ExpandIncludesWithManifest(content, baseDir string, extractTools bool) (string, []string, error)

ExpandIncludesWithManifest recursively expands @include and @import directives and returns list of included files

func ExtractFrontmatterString

func ExtractFrontmatterString(content string) (string, error)

ExtractFrontmatterString extracts only the YAML frontmatter as a string This matches the bash extract_frontmatter function

func ExtractMarkdown

func ExtractMarkdown(filePath string) (string, error)

ExtractMarkdown extracts markdown content from a file (excluding frontmatter) This matches the bash extract_markdown function

func ExtractMarkdownContent

func ExtractMarkdownContent(content string) (string, error)

ExtractMarkdownContent extracts only the markdown content (excluding frontmatter) This matches the bash extract_markdown function

func ExtractMarkdownSection

func ExtractMarkdownSection(content, sectionName string) (string, error)

ExtractMarkdownSection extracts a specific section from markdown content Supports H1-H3 headers and proper nesting (matches bash implementation)

func ExtractPermissionsFromContent added in v0.27.0

func ExtractPermissionsFromContent(content string) (string, error)

ExtractPermissionsFromContent extracts permissions section from frontmatter as JSON string

func ExtractWorkflowNameFromMarkdown

func ExtractWorkflowNameFromMarkdown(filePath string) (string, error)

ExtractWorkflowNameFromMarkdown extracts workflow name from first H1 header This matches the bash extract_workflow_name_from_markdown function exactly

func ExtractYAMLError

func ExtractYAMLError(err error, frontmatterLineOffset int) (line int, column int, message string)

ExtractYAMLError extracts line and column information from YAML parsing errors frontmatterLineOffset is the line number where the frontmatter content begins in the document (1-based) This allows proper line number reporting when frontmatter is not at the beginning of the document

func ExtractYamlChunk

func ExtractYamlChunk(yamlContent, key string) (string, error)

ExtractYamlChunk extracts a specific YAML section with proper indentation handling This matches the bash extract_yaml_chunk function exactly

func FindClosestMatches added in v0.31.4

func FindClosestMatches(target string, candidates []string, maxResults int) []string

FindClosestMatches finds the closest matching strings using Levenshtein distance. It returns up to maxResults matches that have a Levenshtein distance of 3 or less. Results are sorted by distance (closest first), then alphabetically for ties.

func FormatImportError added in v0.31.4

func FormatImportError(err *ImportError, yamlContent string) error

FormatImportError formats an import error as a compilation error with source location

func GetGitHubToken

func GetGitHubToken() (string, error)

GetGitHubToken attempts to get GitHub token from environment or gh CLI

func GetSafeOutputTypeKeys added in v0.31.3

func GetSafeOutputTypeKeys() ([]string, error)

GetSafeOutputTypeKeys returns the list of safe output type keys from the embedded main workflow schema. These are the keys under safe-outputs that define actual safe output operations (like create-issue, add-comment, etc.) Meta-configuration fields (like allowed-domains, staged, env, etc.) are excluded.

func IsLabelOnlyEvent added in v0.30.5

func IsLabelOnlyEvent(eventValue any) bool

IsLabelOnlyEvent checks if an event configuration only contains labeled/unlabeled types This is exported for use in the compiler to validate command trigger combinations

func IsMCPType added in v0.32.0

func IsMCPType(typeStr string) bool

IsMCPType checks if a type string is a valid MCP server type. Returns true for "stdio", "http", and "local" (which is an alias for "stdio").

func IsValidGitHubIdentifier added in v0.28.3

func IsValidGitHubIdentifier(s string) bool

IsValidGitHubIdentifier checks if a string is a valid GitHub username or repository name

func LevenshteinDistance added in v0.31.4

func LevenshteinDistance(a, b string) int

LevenshteinDistance computes the Levenshtein distance between two strings. This is the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into the other.

func MergeTools

func MergeTools(base, additional map[string]any) (map[string]any, error)

MergeTools merges two neutral tool configurations. Only supports merging arrays and maps for neutral tools (bash, web-fetch, web-search, edit, mcp-*). Removes all legacy Claude tool merging logic.

func ParsePRURL added in v0.28.3

func ParsePRURL(prURL string) (owner, repo string, prNumber int, err error)

ParsePRURL is a convenience function that parses a GitHub PR URL and extracts PR information. Expected format: https://github.com/owner/repo/pull/123

func ParseRepoFileURL added in v0.28.3

func ParseRepoFileURL(fileURL string) (owner, repo, ref, filePath string, err error)

ParseRepoFileURL is a convenience function that parses a GitHub repository file URL. It accepts URLs like:

func ParseRunURL added in v0.28.3

func ParseRunURL(input string) (runID int64, owner, repo, hostname string, err error)

ParseRunURL is a convenience function that parses a run ID or URL and extracts run information. It accepts:

func ProcessImportsFromFrontmatter added in v0.14.1

func ProcessImportsFromFrontmatter(frontmatter map[string]any, baseDir string) (mergedTools string, mergedEngines []string, err error)

ProcessImportsFromFrontmatter processes imports field from frontmatter Returns merged tools and engines from imported files

func ProcessIncludes

func ProcessIncludes(content, baseDir string, extractTools bool) (string, error)

ProcessIncludes processes @include, @import (deprecated), and {{#import: directives in markdown content This matches the bash process_includes function behavior

func ProcessIncludesForEngines added in v0.5.1

func ProcessIncludesForEngines(content, baseDir string) ([]string, string, error)

ProcessIncludesForEngines processes import directives to extract engine configurations

func ProcessIncludesForSafeOutputs added in v0.14.1

func ProcessIncludesForSafeOutputs(content, baseDir string) ([]string, string, error)

ProcessIncludesForSafeOutputs processes import directives to extract safe-outputs configurations

func QuoteCronExpressions added in v0.28.7

func QuoteCronExpressions(yamlContent string) string

QuoteCronExpressions ensures cron expressions in schedule sections are properly quoted. The YAML library may drop quotes from cron expressions like "0 14 * * 1-5" which causes validation errors since they start with numbers but contain spaces and special chars.

func ResolveIncludePath added in v0.32.0

func ResolveIncludePath(filePath, baseDir string, cache *ImportCache) (string, error)

ResolveIncludePath resolves include path based on workflowspec format or relative path

func StripANSI

func StripANSI(s string) string

StripANSI removes ANSI escape codes from a string

func UpdateWorkflowFrontmatter added in v0.8.3

func UpdateWorkflowFrontmatter(workflowPath string, updateFunc func(frontmatter map[string]any) error, verbose bool) error

UpdateWorkflowFrontmatter updates the frontmatter of a workflow file using a callback function

func ValidateIncludedFileFrontmatterWithSchema

func ValidateIncludedFileFrontmatterWithSchema(frontmatter map[string]any) error

ValidateIncludedFileFrontmatterWithSchema validates included file frontmatter using JSON schema

func ValidateIncludedFileFrontmatterWithSchemaAndLocation

func ValidateIncludedFileFrontmatterWithSchemaAndLocation(frontmatter map[string]any, filePath string) error

ValidateIncludedFileFrontmatterWithSchemaAndLocation validates included file frontmatter with file location info

func ValidateMCPConfigWithSchema

func ValidateMCPConfigWithSchema(mcpConfig map[string]any, toolName string) error

ValidateMCPConfigWithSchema validates MCP configuration using JSON schema

func ValidateMainWorkflowFrontmatterWithSchema

func ValidateMainWorkflowFrontmatterWithSchema(frontmatter map[string]any) error

ValidateMainWorkflowFrontmatterWithSchema validates main workflow frontmatter using JSON schema

func ValidateMainWorkflowFrontmatterWithSchemaAndLocation

func ValidateMainWorkflowFrontmatterWithSchemaAndLocation(frontmatter map[string]any, filePath string) error

ValidateMainWorkflowFrontmatterWithSchemaAndLocation validates main workflow frontmatter with file location info

Types

type DeprecatedField added in v0.30.0

type DeprecatedField struct {
	Name        string // The deprecated field name
	Replacement string // The recommended replacement field name
	Description string // Description from the schema
}

DeprecatedField represents a deprecated field with its replacement information

func FindDeprecatedFieldsInFrontmatter added in v0.30.0

func FindDeprecatedFieldsInFrontmatter(frontmatter map[string]any, deprecatedFields []DeprecatedField) []DeprecatedField

FindDeprecatedFieldsInFrontmatter checks frontmatter for deprecated fields Returns a list of deprecated fields that were found

func GetMainWorkflowDeprecatedFields added in v0.30.0

func GetMainWorkflowDeprecatedFields() ([]DeprecatedField, error)

GetMainWorkflowDeprecatedFields returns a list of deprecated fields from the main workflow schema

type FrontmatterResult

type FrontmatterResult struct {
	Frontmatter map[string]any
	Markdown    string
	// Additional fields for error context
	FrontmatterLines []string // Original frontmatter lines for error context
	FrontmatterStart int      // Line number where frontmatter starts (1-based)
}

FrontmatterResult holds parsed frontmatter and markdown content

func ExtractFrontmatterFromContent

func ExtractFrontmatterFromContent(content string) (*FrontmatterResult, error)

ExtractFrontmatterFromContent parses YAML frontmatter from markdown content string

type GitHubURLComponents added in v0.28.3

type GitHubURLComponents struct {
	Host   string        // Hostname (e.g., "github.com", "github.example.com", "raw.githubusercontent.com")
	Owner  string        // Repository owner
	Repo   string        // Repository name
	Type   GitHubURLType // Type of URL (run, pull, issue, blob, tree, raw, rawcontent)
	Number int64         // Number for runs, PRs, issues, jobs
	Path   string        // File path for blob/tree/raw URLs
	Ref    string        // Git reference (branch, tag, SHA) for file URLs
}

GitHubURLComponents represents the parsed components of a GitHub URL

func (*GitHubURLComponents) GetRepoSlug added in v0.28.3

func (c *GitHubURLComponents) GetRepoSlug() string

GetRepoSlug returns the repository slug in "owner/repo" format

func (*GitHubURLComponents) GetWorkflowName added in v0.28.3

func (c *GitHubURLComponents) GetWorkflowName() string

GetWorkflowName returns the workflow name from a file path (without .md extension)

type GitHubURLType added in v0.28.3

type GitHubURLType string

GitHubURLType represents the type of GitHub URL

const (
	URLTypeRun         GitHubURLType = "run"        // GitHub Actions run
	URLTypePullRequest GitHubURLType = "pull"       // Pull request
	URLTypeIssue       GitHubURLType = "issue"      // Issue
	URLTypeBlob        GitHubURLType = "blob"       // File blob view
	URLTypeTree        GitHubURLType = "tree"       // Directory tree view
	URLTypeRaw         GitHubURLType = "raw"        // Raw file view
	URLTypeRawContent  GitHubURLType = "rawcontent" // raw.githubusercontent.com
	URLTypeUnknown     GitHubURLType = "unknown"    // Unknown type
)

type ImportCache added in v0.29.1

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

ImportCache manages cached imported workflow files

func NewImportCache added in v0.29.1

func NewImportCache(repoRoot string) *ImportCache

NewImportCache creates a new import cache instance

func (*ImportCache) Get added in v0.29.1

func (c *ImportCache) Get(owner, repo, path, sha string) (string, bool)

Get retrieves a cached file path if it exists sha parameter should be the resolved commit SHA

func (*ImportCache) GetCacheDir added in v0.29.1

func (c *ImportCache) GetCacheDir() string

GetCacheDir returns the base cache directory path

func (*ImportCache) Set added in v0.29.1

func (c *ImportCache) Set(owner, repo, path, sha string, content []byte) (string, error)

Set stores a new cache entry by saving the content to the cache directory sha parameter should be the resolved commit SHA

type ImportDirectiveMatch added in v0.14.1

type ImportDirectiveMatch struct {
	IsOptional bool
	Path       string
	IsLegacy   bool
	Original   string
}

ImportDirectiveMatch holds the parsed components of an import directive

func ParseImportDirective added in v0.14.1

func ParseImportDirective(line string) *ImportDirectiveMatch

ParseImportDirective parses an import directive and returns its components

type ImportError added in v0.31.4

type ImportError struct {
	ImportPath string // The import path that failed (e.g., "nonexistent.md")
	FilePath   string // The workflow file containing the import
	Line       int    // Line number where the import is defined
	Column     int    // Column number where the import is defined
	Cause      error  // The underlying error
}

ImportError represents an error that occurred during import resolution

func (*ImportError) Error added in v0.31.4

func (e *ImportError) Error() string

Error returns the error message

func (*ImportError) Unwrap added in v0.31.4

func (e *ImportError) Unwrap() error

Unwrap returns the underlying error

type ImportInputDefinition added in v0.31.4

type ImportInputDefinition struct {
	Description string   `yaml:"description,omitempty" json:"description,omitempty"`
	Required    bool     `yaml:"required,omitempty" json:"required,omitempty"`
	Default     any      `yaml:"default,omitempty" json:"default,omitempty"` // Can be string, number, or boolean
	Type        string   `yaml:"type,omitempty" json:"type,omitempty"`       // "string", "choice", "boolean", "number"
	Options     []string `yaml:"options,omitempty" json:"options,omitempty"` // Options for choice type
}

ImportInputDefinition defines an input parameter for a shared workflow import. Uses the same schema as workflow_dispatch inputs. NOTE: This type matches workflow.InputDefinition which is the canonical type for input parameters. The parser package uses map[string]any for actual parsing to avoid circular dependencies.

type ImportSpec added in v0.31.4

type ImportSpec struct {
	Path   string         // Import path (required)
	Inputs map[string]any // Optional input values to pass to the imported workflow (values are string, number, or boolean)
}

ImportSpec represents a single import specification (either a string path or an object with path and inputs)

type ImportsResult added in v0.14.1

type ImportsResult struct {
	MergedTools         string         // Merged tools configuration from all imports
	MergedMCPServers    string         // Merged mcp-servers configuration from all imports
	MergedEngines       []string       // Merged engine configurations from all imports
	MergedSafeOutputs   []string       // Merged safe-outputs configurations from all imports
	MergedSafeInputs    []string       // Merged safe-inputs configurations from all imports
	MergedMarkdown      string         // Merged markdown content from all imports
	MergedSteps         string         // Merged steps configuration from all imports
	MergedRuntimes      string         // Merged runtimes configuration from all imports
	MergedServices      string         // Merged services configuration from all imports
	MergedNetwork       string         // Merged network configuration from all imports
	MergedPermissions   string         // Merged permissions configuration from all imports
	MergedSecretMasking string         // Merged secret-masking steps from all imports
	ImportedFiles       []string       // List of imported file paths (for manifest)
	AgentFile           string         // Path to custom agent file (if imported)
	ImportInputs        map[string]any // Aggregated input values from all imports (key = input name, value = input value)
}

ImportsResult holds the result of processing imports from frontmatter

func ProcessImportsFromFrontmatterWithManifest added in v0.14.1

func ProcessImportsFromFrontmatterWithManifest(frontmatter map[string]any, baseDir string, cache *ImportCache) (*ImportsResult, error)

ProcessImportsFromFrontmatterWithManifest processes imports field from frontmatter Returns result containing merged tools, engines, markdown content, and list of imported files Uses BFS traversal with queues for deterministic ordering and cycle detection

func ProcessImportsFromFrontmatterWithSource added in v0.31.4

func ProcessImportsFromFrontmatterWithSource(frontmatter map[string]any, baseDir string, cache *ImportCache, workflowFilePath string, yamlContent string) (*ImportsResult, error)

ProcessImportsFromFrontmatterWithSource processes imports field from frontmatter with source tracking This version includes the workflow file path and YAML content for better error reporting

type JSONPathInfo added in v0.4.0

type JSONPathInfo struct {
	Path     string   // JSON path like "/tools/1" or "/age"
	Message  string   // Error message
	Location []string // Instance location from jsonschema (e.g., ["tools", "1"])
}

JSONPathInfo holds information about a validation error and its path

func ExtractJSONPathFromValidationError added in v0.4.0

func ExtractJSONPathFromValidationError(err error) []JSONPathInfo

ExtractJSONPathFromValidationError extracts JSON path information from jsonschema validation errors

type JSONPathLocation added in v0.4.0

type JSONPathLocation struct {
	Line   int
	Column int
	Found  bool
}

JSONPathLocation represents a location in YAML source corresponding to a JSON path

func LocateJSONPathInYAML added in v0.4.0

func LocateJSONPathInYAML(yamlContent string, jsonPath string) JSONPathLocation

LocateJSONPathInYAML finds the line/column position of a JSON path in YAML source

func LocateJSONPathInYAMLWithAdditionalProperties added in v0.4.0

func LocateJSONPathInYAMLWithAdditionalProperties(yamlContent string, jsonPath string, errorMessage string) JSONPathLocation

LocateJSONPathInYAMLWithAdditionalProperties finds the line/column position of a JSON path in YAML source with special handling for additional properties errors

type MCPServerConfig

type MCPServerConfig struct {
	Name           string            `json:"name"`
	Type           string            `json:"type"`           // stdio, http, docker
	Registry       string            `json:"registry"`       // URI to installation location from registry
	Command        string            `json:"command"`        // for stdio
	Args           []string          `json:"args"`           // for stdio
	Container      string            `json:"container"`      // for docker
	Version        string            `json:"version"`        // optional version/tag for container
	EntrypointArgs []string          `json:"entrypointArgs"` // arguments to add after container image
	URL            string            `json:"url"`            // for http
	Headers        map[string]string `json:"headers"`        // for http
	Env            map[string]string `json:"env"`            // environment variables
	ProxyArgs      []string          `json:"proxy-args"`     // custom proxy arguments for container-based tools
	Allowed        []string          `json:"allowed"`        // allowed tools
}

MCPServerConfig represents a parsed MCP server configuration

func ExtractMCPConfigurations

func ExtractMCPConfigurations(frontmatter map[string]any, serverFilter string) ([]MCPServerConfig, error)

ExtractMCPConfigurations extracts MCP server configurations from workflow frontmatter

func ParseMCPConfig

func ParseMCPConfig(toolName string, mcpSection any, toolConfig map[string]any) (MCPServerConfig, error)

ParseMCPConfig parses MCP configuration from various formats (map or JSON string)

type MCPServerInfo

type MCPServerInfo struct {
	Config    MCPServerConfig
	Connected bool
	Error     error
	Tools     []*mcp.Tool
	Resources []*mcp.Resource
	Roots     []*mcp.Root
}

MCPServerInfo contains the inspection results for an MCP server

type NestedSection added in v0.4.0

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

NestedSection represents a section of YAML content that corresponds to a nested object

type PathSegment added in v0.4.0

type PathSegment struct {
	Type  string // "key" or "index"
	Value string // The raw value
	Index int    // Parsed index for array elements
}

PathSegment represents a segment in a JSON path

Jump to

Keyboard shortcuts

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