package modules import ( "bytes" "encoding/json" "html/template" "regexp" "strconv" "strings" "gopkg.in/yaml.v3" ) // ParseNote reports why a JSON/YAML blob failed to parse, so the blob view // can point at the offending line instead of leaving a reader to guess. // Line is 0 when the underlying error can't be pinned to one. type ParseNote struct { Line int Msg string } // Anchor is a YAML anchor declared on a line, along with how many alias // sites in the file point back at it. type Anchor struct { Name string Uses int } // StructRef is a resolved YAML alias: which anchor it names, the line that // anchor is declared on, and the value it stands for rendered back to YAML. // One per line -- a flow sequence like [*a, *b] resolves only its first. type StructRef struct { Name string Line int Preview string } // maxStructuredSize bounds the work one file may cost the structured view: // a full parse on the server, and a pass over every row in the browser at // load. It matches maxHighlightSize on purpose -- past that point the file // is already served as plain, unhighlighted text with no indent guides, and // folding a file that has neither would be a strange half-feature. Half a // megabyte is far above any hand-written config and below the size where a // modest laptop notices the per-row work. const maxStructuredSize = maxHighlightSize // structuredLang returns "json" or "yaml" for a recognised config // extension, "" otherwise. The blob view only spends the extra parse and // indent-guide pass on formats where nesting depth is the whole point. func structuredLang(path string) string { p := strings.ToLower(path) switch { case strings.HasSuffix(p, ".json"): return "json" case strings.HasSuffix(p, ".yaml"), strings.HasSuffix(p, ".yml"): return "yaml" default: return "" } } func validateStructured(lang string, raw []byte) *ParseNote { var err error switch lang { case "json": err = json.Unmarshal(raw, new(any)) case "yaml": err = yaml.Unmarshal(raw, new(any)) default: return nil } if err == nil { return nil } return &ParseNote{Line: parseErrorLine(lang, raw, err), Msg: err.Error()} } var yamlLineRe = regexp.MustCompile(`line (\d+)`) func parseErrorLine(lang string, raw []byte, err error) int { if lang == "json" { switch e := err.(type) { case *json.SyntaxError: return bytes.Count(raw[:e.Offset], []byte("\n")) + 1 case *json.UnmarshalTypeError: return bytes.Count(raw[:e.Offset], []byte("\n")) + 1 } return 0 } // yaml.v3 errors are plain strings of the form "yaml: line N: ...", or // for TypeError one such string per bad field -- take the first. if m := yamlLineRe.FindStringSubmatch(err.Error()); m != nil { n, _ := strconv.Atoi(m[1]) return n } return 0 } // indentUnit finds the smallest non-zero run of leading spaces across // non-blank lines, so a 4-space file gets one guide per level and a // 2-space file doesn't get a spurious extra one. func indentUnit(raw []byte) int { unit := 0 for _, line := range bytes.Split(raw, []byte("\n")) { n := 0 for n < len(line) && line[n] == ' ' { n++ } if n == 0 || n == len(line) { continue // blank or all-whitespace } if unit == 0 || n < unit { unit = n } } if unit == 0 { return 2 } return unit } // annotateStructure fills in the per-line structure the blob view needs to // fold, filter and cross-reference a config file: nesting depth, the extent // of the block each line opens, the mapping key it declares, and (YAML only) // the anchors and aliases tying parts of the file together. // // It works off raw rather than the highlighted HTML: indentation is the one // signal that means the same thing in both languages, and it survives // minified or oddly-formatted input by simply finding nothing to fold. func annotateStructure(lines []Line, raw []byte, lang string) { src := bytes.Split(raw, []byte("\n")) unit := indentUnit(raw) ind := make([]int, len(src)) for i, l := range src { ind[i] = lineIndent(l) } ends := foldEnds(ind) keyRe := jsonKeyRe if lang == "yaml" { keyRe = yamlKeyRe } for i := range src { if i >= len(lines) { break } if ind[i] >= 0 { lines[i].Depth = ind[i] / unit if e := ends[i]; e > 0 && e <= len(lines) { lines[i].FoldTo = e } } if m := keyRe.FindSubmatch(src[i]); m != nil { for _, g := range m[1:] { if len(g) > 0 { lines[i].Key = string(g) break } } } } if lang != "yaml" { return } anchors, refs := yamlAnchors(src) for n, a := range anchors { if n >= 1 && n <= len(lines) { lines[n-1].Anchor = a } } for n, r := range refs { if n >= 1 && n <= len(lines) { lines[n-1].Ref = r } } } // lineIndent counts leading spaces, or returns -1 for a line that carries no // structure (blank or whitespace-only) so folding steps over it rather than // treating column 0 as a dedent. func lineIndent(line []byte) int { n := 0 for n < len(line) && line[n] == ' ' { n++ } if n == len(bytes.TrimRight(line, " \t\r")) { return -1 } return n } // foldEnds returns, per line, the 1-based number of the last line belonging // to the block that line opens -- 0 when it opens nothing. A line opens a // block when the next line carrying structure is indented further, and the // block runs until indentation returns to that line's own level or less. // Blank lines between siblings are absorbed; blank lines trailing a block // are not. func foldEnds(ind []int) []int { ends := make([]int, len(ind)) type frame struct { ind, idx int child bool } var stack []frame prev := -1 // last line carrying structure for i, in := range ind { if in < 0 { continue } for len(stack) > 0 && stack[len(stack)-1].ind >= in { if t := stack[len(stack)-1]; t.child { ends[t.idx] = prev + 1 } stack = stack[:len(stack)-1] } if len(stack) > 0 { stack[len(stack)-1].child = true } stack = append(stack, frame{ind: in, idx: i}) prev = i } for _, t := range stack { if t.child { ends[t.idx] = prev + 1 } } return ends } var ( // The key a line declares, used to scope search to keys rather than // whole lines. Both are deliberately shallow: a miss costs a narrower // search, not a wrong render. yamlKeyRe = regexp.MustCompile(`^\s*(?:-\s+)?(?:"([^"]*)"|'([^']*)'|([^\s#"'][^:#]*?))\s*:(?:\s|$)`) jsonKeyRe = regexp.MustCompile(`^\s*"((?:[^"\\]|\\.)*)"\s*:`) ) // yamlAnchors resolves every alias in the file to the line its anchor is // declared on, keyed by 1-based line number. Anchors are per-document, so // the whole stream is decoded document by document -- a k8s manifest that // defines its anchors in the second document would otherwise come back // empty. A malformed document ends the walk with whatever was found first; // the parse-error banner already reports the failure itself. func yamlAnchors(src [][]byte) (map[int]*Anchor, map[int]*StructRef) { anchors := map[int]*Anchor{} refs := map[int]*StructRef{} dec := yaml.NewDecoder(bytes.NewReader(bytes.Join(src, []byte("\n")))) for { var doc yaml.Node if err := dec.Decode(&doc); err != nil { break } walkYAML(&doc, src, anchors, refs) } return anchors, refs } func walkYAML(n *yaml.Node, src [][]byte, anchors map[int]*Anchor, refs map[int]*StructRef) { if n.Anchor != "" { if line := anchorLine(src, n.Anchor, n.Line); line > 0 { if _, ok := anchors[line]; !ok { anchors[line] = &Anchor{Name: n.Anchor} } } } if n.Kind == yaml.AliasNode && n.Alias != nil { target := anchorLine(src, n.Value, n.Alias.Line) if target > 0 { if _, ok := refs[n.Line]; !ok { refs[n.Line] = &StructRef{Name: n.Value, Line: target, Preview: nodePreview(n.Alias)} } if a, ok := anchors[target]; ok { a.Uses++ } } } for _, c := range n.Content { walkYAML(c, src, anchors, refs) } } // anchorLine locates the line the "&name" token sits on. A node's own Line // is where its *value* begins, which for a block mapping is the line after // the key the anchor was written on -- so scan back from there for the // token itself and point at that instead. func anchorLine(src [][]byte, name string, at int) int { tok := []byte("&" + name) if at > len(src) { at = len(src) } for i := at - 1; i >= 0 && i > at-64; i-- { j := bytes.Index(src[i], tok) if j < 0 { continue } if k := j + len(tok); k < len(src[i]) && isAnchorChar(src[i][k]) { continue // &namelonger } return i + 1 } return 0 } func isAnchorChar(b byte) bool { return b == '-' || b == '_' || b == '.' || (b >= '0' && b <= '9') || (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') } // nodePreview renders what an alias actually stands for, short enough to sit // in a tooltip. The anchor name is stripped from the copy so the preview // reads as the value, not as its declaration. func nodePreview(n *yaml.Node) string { c := *n c.Anchor = "" var buf bytes.Buffer enc := yaml.NewEncoder(&buf) enc.SetIndent(2) // yaml.Marshal's default of 4 doesn't match most files if err := enc.Encode(&c); err != nil { return "" } enc.Close() s := strings.TrimRight(buf.String(), "\n") if ls := strings.Split(s, "\n"); len(ls) > 12 { s = strings.Join(append(ls[:12], "…"), "\n") } if len(s) > 480 { s = strings.ToValidUTF8(s[:480], "") + "…" } return s } // withIndentGuides prefixes each line's leading spaces with one guide span // per nesting level, so deeply nested JSON/YAML reads like a tree instead // of a wall of spaces. Leading whitespace is always plain, unwrapped text // at this point (see highlightLines' Text/TextWhitespace handling), so // trimming it back off the rendered HTML here is safe. func withIndentGuides(lines []template.HTML, unit int) []template.HTML { out := make([]template.HTML, len(lines)) for i, l := range lines { s := string(l) n := 0 for n < len(s) && s[n] == ' ' { n++ } if n < unit { out[i] = l continue } var b strings.Builder levels, rem := n/unit, n%unit for j := 0; j < levels; j++ { b.WriteString(``) } if rem > 0 { b.WriteString(strings.Repeat(" ", rem)) } b.WriteString(s[n:]) out[i] = template.HTML(b.String()) } return out }