package modules import ( "bytes" "encoding/json" "html/template" "regexp" "sort" "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" { annotateJSONPaths(lines, raw) return } anchors, refs, paths := yamlAnnotations(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 } } for n, p := range paths { if n >= 1 && n <= len(lines) { lines[n-1].Path = p } } } // 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*:`) ) // yamlAnnotations resolves every alias in the file to the line its anchor is // declared on, keyed by 1-based line number, and records each line's // canonical value path. 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 yamlAnnotations(src [][]byte) (map[int]*Anchor, map[int]*StructRef, map[int]string) { anchors := map[int]*Anchor{} refs := map[int]*StructRef{} paths := map[int]string{} 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, paths, "") } return anchors, refs, paths } func walkYAML(n *yaml.Node, src [][]byte, anchors map[int]*Anchor, refs map[int]*StructRef, paths map[int]string, path string) { 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++ } } // An alias displays only *name here; the aliased value's lines are // wherever the anchor was declared. Recursing into n.Alias would // emit paths pointing at those other lines, so record this line's // path and stop. recordPath(paths, n.Line, path) return } switch n.Kind { case yaml.DocumentNode: for _, c := range n.Content { walkYAML(c, src, anchors, refs, paths, path) } case yaml.MappingNode: for i := 0; i+1 < len(n.Content); i += 2 { k, v := n.Content[i], n.Content[i+1] child := joinPath(path, k.Value) if k.Value == "<<" { // A merge key is not a property of the mapping, and the // rendered text never expands it, so a `<<` segment would // name something the reader cannot see. Keep the parent. child = path } // Walk the key too (anchors may be declared on one), but record // the value's path last so it wins for the shared line. walkYAML(k, src, anchors, refs, paths, path) recordPath(paths, k.Line, child) walkYAML(v, src, anchors, refs, paths, child) } case yaml.SequenceNode: for i, c := range n.Content { child := joinIndex(path, i) recordPath(paths, c.Line, child) walkYAML(c, src, anchors, refs, paths, child) } default: recordPath(paths, n.Line, path) } } // 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 } // --------------------------------------------------------------- paths // A path query names a value the way obj1.property3.items[4].val does. // Both the server (here) and static/js/structured.js write the same // canonical form so a query can be compared as a string: simple keys are // dotted, indices attach directly, and anything else is bracket-quoted. var ( simplePathKey = regexp.MustCompile(`^[A-Za-z0-9_$-]+$`) pathEscaper = strings.NewReplacer(`\`, `\\`, `"`, `\"`) ) func joinPath(parent, key string) string { if simplePathKey.MatchString(key) { if parent == "" { return key } return parent + "." + key } return parent + `["` + pathEscaper.Replace(key) + `"]` } func joinIndex(parent string, i int) string { return parent + "[" + strconv.Itoa(i) + "]" } // recordPath keeps the last path recorded for a line. A line can carry more // than one path (JSON/YAML flow style puts several values on one row), and // the last one parsed is the deepest -- the one a reader naming a full path // is most likely to mean. A container query still reaches its children by // the boundary-aware prefix match in structured.js, so dropping the shallow // path costs nothing there. func recordPath(paths map[int]string, line int, path string) { if path == "" || line <= 0 { return } paths[line] = path } // annotateJSONPaths records each line's canonical value path. It reuses // encoding/json's own decoder rather than a second parser, so the offsets it // sees are exactly the ones the format defines. func annotateJSONPaths(lines []Line, raw []byte) { paths := jsonPaths(raw) for i := range lines { if p, ok := paths[lines[i].N]; ok { lines[i].Path = p } } } func jsonPaths(raw []byte) map[int]string { paths := map[int]string{} lineOf := newLineIndex(raw) dec := json.NewDecoder(bytes.NewReader(raw)) // walk consumes one JSON value at path. Objects record the path on the // key's line and recurse into the value; arrays record it on each // element's line. A malformed document simply stops -- the parse-error // banner owns reporting that. var walk func(path string) walk = func(path string) { tok, err := dec.Token() if err != nil { return } recordPath(paths, lineOf(dec.InputOffset()), path) d, ok := tok.(json.Delim) if !ok { return } switch d { case '{': for dec.More() { kt, err := dec.Token() if err != nil { return } key, _ := kt.(string) child := joinPath(path, key) recordPath(paths, lineOf(dec.InputOffset()), child) walk(child) } dec.Token() // consume '}' case '[': for i := 0; dec.More(); i++ { walk(joinIndex(path, i)) } dec.Token() // consume ']' } } walk("") return paths } // newLineIndex maps a byte offset to a 1-based line number. Newline // positions are found once and binary-searched per token, so indexing a // whole file stays O(n log n) rather than counting from zero each time. func newLineIndex(raw []byte) func(int64) int { var newlines []int64 for i, b := range raw { if b == '\n' { newlines = append(newlines, int64(i)) } } return func(off int64) int { return sort.Search(len(newlines), func(i int) bool { return newlines[i] >= off }) + 1 } }