Files
skillshare/internal/utils/frontmatter.go
T
Willie 620141af2b feat(analyze): add context analysis command
Analyze context window usage per target, showing always-loaded
(description) vs on-demand (body) token costs.

- Single-pass discovery with frontmatter-aware char/token counting
- Per-target filtering (include/exclude/symlink mode)
- Unified output when all targets have identical skills
- Verbose mode shows top 10 largest descriptions
- Project mode (-p) support
- JSON output (--json)
- Integration tests
2026-03-26 19:20:52 +08:00

353 lines
7.7 KiB
Go

package utils
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
"gopkg.in/yaml.v3"
)
// ParseSkillName reads the SKILL.md and extracts the "name" from frontmatter.
func ParseSkillName(skillPath string) (string, error) {
skillFile := filepath.Join(skillPath, "SKILL.md")
file, err := os.Open(skillFile)
if err != nil {
return "", err
}
defer file.Close()
scanner := bufio.NewScanner(file)
inFrontmatter := false
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
// Detect frontmatter delimiters
if line == "---" {
if inFrontmatter {
break // End of frontmatter
}
inFrontmatter = true
continue
}
if inFrontmatter {
if strings.HasPrefix(line, "name:") {
// Extract value: "name: my-skill" -> "my-skill"
parts := strings.SplitN(line, ":", 2)
if len(parts) == 2 {
name := strings.TrimSpace(parts[1])
// Remove quotes if present
name = strings.Trim(name, `"'`)
return name, nil
}
}
}
}
return "", nil // Name not found
}
// isYAMLBlockIndicator returns true for YAML block scalar indicators (>, >-, >+, |, |-, |+).
func isYAMLBlockIndicator(s string) bool {
switch s {
case ">", ">-", ">+", "|", "|-", "|+":
return true
}
return false
}
// resolveField looks up a field in the frontmatter map.
// Priority: metadata.<field> > top-level <field>.
// Returns nil when the field is absent in both locations.
func resolveField(fm map[string]any, field string) any {
if md, ok := fm["metadata"]; ok {
if mdMap, ok := md.(map[string]any); ok {
if val, ok := mdMap[field]; ok {
return val
}
}
}
val, ok := fm[field]
if !ok {
return nil
}
return val
}
// ParseFrontmatterList reads a SKILL.md file and extracts a YAML list field from frontmatter.
// Supports both inline [a, b] and block (- a\n- b) formats.
// Returns nil when the field is absent or the file cannot be read.
func ParseFrontmatterList(filePath, field string) []string {
raw := extractFrontmatterRaw(filePath)
if raw == "" {
return nil
}
var fm map[string]any
if err := yaml.Unmarshal([]byte(raw), &fm); err != nil {
return nil
}
val := resolveField(fm, field)
if val == nil {
return nil
}
switch v := val.(type) {
case []any:
result := make([]string, 0, len(v))
for _, item := range v {
if s, ok := item.(string); ok {
result = append(result, s)
}
}
if len(result) == 0 {
return nil
}
return result
default:
return nil
}
}
// ParseFrontmatterListFromBytes parses a YAML list field from pre-read content.
// Same as ParseFrontmatterList but avoids re-reading the file.
func ParseFrontmatterListFromBytes(content []byte, field string) []string {
raw := extractFrontmatterRawFromBytes(content)
if raw == "" {
return nil
}
var fm map[string]any
if err := yaml.Unmarshal([]byte(raw), &fm); err != nil {
return nil
}
val := resolveField(fm, field)
if val == nil {
return nil
}
switch v := val.(type) {
case []any:
result := make([]string, 0, len(v))
for _, item := range v {
if s, ok := item.(string); ok {
result = append(result, s)
}
}
if len(result) == 0 {
return nil
}
return result
default:
return nil
}
}
// extractFrontmatterRawFromBytes extracts raw frontmatter YAML from pre-read content.
func extractFrontmatterRawFromBytes(content []byte) string {
s := string(content)
lines := strings.Split(s, "\n")
inFrontmatter := false
var fmLines []string
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if trimmed == "---" {
if inFrontmatter {
break
}
inFrontmatter = true
continue
}
if inFrontmatter {
fmLines = append(fmLines, line)
}
}
if len(fmLines) == 0 {
return ""
}
return strings.Join(fmLines, "\n")
}
// extractFrontmatterRaw reads the raw frontmatter text between --- delimiters.
func extractFrontmatterRaw(filePath string) string {
file, err := os.Open(filePath)
if err != nil {
return ""
}
defer file.Close()
scanner := bufio.NewScanner(file)
inFrontmatter := false
var lines []string
for scanner.Scan() {
line := scanner.Text()
trimmed := strings.TrimSpace(line)
if trimmed == "---" {
if inFrontmatter {
break
}
inFrontmatter = true
continue
}
if inFrontmatter {
lines = append(lines, line)
}
}
if len(lines) == 0 {
return ""
}
return strings.Join(lines, "\n")
}
// ParseFrontmatterFields reads a SKILL.md file once and returns the values of
// multiple frontmatter fields. This avoids opening the same file repeatedly
// when multiple fields are needed (e.g. description + license).
// Note: does not resolve metadata.<field> — only reads top-level fields.
func ParseFrontmatterFields(filePath string, fields []string) map[string]string {
result := make(map[string]string, len(fields))
if len(fields) == 0 {
return result
}
raw := extractFrontmatterRaw(filePath)
if raw == "" {
return result
}
var fm map[string]any
if err := yaml.Unmarshal([]byte(raw), &fm); err != nil {
return result
}
for _, field := range fields {
val, ok := fm[field]
if !ok || val == nil {
continue
}
switch v := val.(type) {
case string:
result[field] = v
case int:
result[field] = fmt.Sprintf("%d", v)
case float64:
result[field] = fmt.Sprintf("%g", v)
case bool:
result[field] = fmt.Sprintf("%t", v)
}
}
return result
}
// ReadSkillBody reads a file and returns everything after the YAML frontmatter.
// If no frontmatter is present, the entire content is returned.
// Returns "" on read error.
func ReadSkillBody(filePath string) string {
data, err := os.ReadFile(filePath)
if err != nil {
return ""
}
content := string(data)
// Check for frontmatter opening delimiter
if !strings.HasPrefix(strings.TrimSpace(content), "---") {
return strings.TrimSpace(content)
}
// Skip leading whitespace + first "---" line
scanner := bufio.NewScanner(strings.NewReader(content))
foundOpen := false
for scanner.Scan() {
if strings.TrimSpace(scanner.Text()) == "---" {
foundOpen = true
break
}
}
if !foundOpen {
return strings.TrimSpace(content)
}
// Skip until closing "---"
for scanner.Scan() {
if strings.TrimSpace(scanner.Text()) == "---" {
// Collect remaining lines
var lines []string
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
result := strings.Join(lines, "\n")
return strings.TrimSpace(result)
}
}
// No closing delimiter found — return everything after opening "---"
return ""
}
// ParseFrontmatterField reads a SKILL.md file and extracts the value of a given frontmatter field.
// It supports both inline values and YAML block scalars (>, >-, |, |-).
func ParseFrontmatterField(filePath, field string) string {
file, err := os.Open(filePath)
if err != nil {
return ""
}
defer file.Close()
scanner := bufio.NewScanner(file)
inFrontmatter := false
prefix := field + ":"
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "---" {
if inFrontmatter {
break
}
inFrontmatter = true
continue
}
if inFrontmatter && strings.HasPrefix(line, prefix) {
parts := strings.SplitN(line, ":", 2)
if len(parts) == 2 {
val := strings.TrimSpace(parts[1])
// Handle YAML block scalar indicators — read indented continuation lines
if isYAMLBlockIndicator(val) {
var blockParts []string
for scanner.Scan() {
next := scanner.Text()
trimmed := strings.TrimSpace(next)
if trimmed == "---" {
break
}
// Block continues while lines are indented
if len(next) > 0 && (next[0] == ' ' || next[0] == '\t') {
blockParts = append(blockParts, trimmed)
} else {
break
}
}
return strings.Join(blockParts, " ")
}
val = strings.Trim(val, `"'`)
return val
}
}
}
return ""
}