|
| 1 | +package jsonschema |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + "os" |
| 9 | + "strings" |
| 10 | + |
| 11 | + "github.com/iancoleman/orderedmap" |
| 12 | + "github.com/jesseduffield/lazycore/pkg/utils" |
| 13 | + "github.com/samber/lo" |
| 14 | + |
| 15 | + "gopkg.in/yaml.v3" |
| 16 | +) |
| 17 | + |
| 18 | +type Node struct { |
| 19 | + Name string |
| 20 | + Description string |
| 21 | + Default any |
| 22 | + Children []*Node |
| 23 | +} |
| 24 | + |
| 25 | +const ( |
| 26 | + IndentLevel = 2 |
| 27 | + DocumentationCommentStart = "<!-- START CONFIG YAML: AUTOMATICALLY GENERATED with `go generate ./..., DO NOT UPDATE MANUALLY -->\n" |
| 28 | + DocumentationCommentEnd = "<!-- END CONFIG YAML -->" |
| 29 | + DocumentationCommentStartLen = len(DocumentationCommentStart) |
| 30 | +) |
| 31 | + |
| 32 | +func insertBlankLines(buffer bytes.Buffer) bytes.Buffer { |
| 33 | + lines := strings.Split(strings.TrimRight(buffer.String(), "\n"), "\n") |
| 34 | + |
| 35 | + var newBuffer bytes.Buffer |
| 36 | + |
| 37 | + previousIndent := -1 |
| 38 | + wasComment := false |
| 39 | + |
| 40 | + for _, line := range lines { |
| 41 | + trimmedLine := strings.TrimLeft(line, " ") |
| 42 | + indent := len(line) - len(trimmedLine) |
| 43 | + isComment := strings.HasPrefix(trimmedLine, "#") |
| 44 | + if isComment && !wasComment && indent <= previousIndent { |
| 45 | + newBuffer.WriteString("\n") |
| 46 | + } |
| 47 | + newBuffer.WriteString(line) |
| 48 | + newBuffer.WriteString("\n") |
| 49 | + previousIndent = indent |
| 50 | + wasComment = isComment |
| 51 | + } |
| 52 | + |
| 53 | + return newBuffer |
| 54 | +} |
| 55 | + |
| 56 | +func prepareMarshalledConfig(buffer bytes.Buffer) []byte { |
| 57 | + buffer = insertBlankLines(buffer) |
| 58 | + |
| 59 | + // Remove all `---` lines |
| 60 | + lines := strings.Split(strings.TrimRight(buffer.String(), "\n"), "\n") |
| 61 | + |
| 62 | + var newBuffer bytes.Buffer |
| 63 | + |
| 64 | + for _, line := range lines { |
| 65 | + if strings.TrimSpace(line) != "---" { |
| 66 | + newBuffer.WriteString(line) |
| 67 | + newBuffer.WriteString("\n") |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + config := newBuffer.Bytes() |
| 72 | + |
| 73 | + // Add markdown yaml block tag |
| 74 | + config = append([]byte("```yaml\n"), config...) |
| 75 | + config = append(config, []byte("```\n")...) |
| 76 | + |
| 77 | + return config |
| 78 | +} |
| 79 | + |
| 80 | +func setComment(yamlNode *yaml.Node, description string) { |
| 81 | + // Workaround for the way yaml formats the HeadComment if it contains |
| 82 | + // blank lines: it renders these without a leading "#", but we want a |
| 83 | + // leading "#" even on blank lines. However, yaml respects it if the |
| 84 | + // HeadComment already contains a leading "#", so we prefix all lines |
| 85 | + // (including blank ones) with "#". |
| 86 | + yamlNode.HeadComment = strings.Join( |
| 87 | + lo.Map(strings.Split(description, "\n"), func(s string, _ int) string { |
| 88 | + if s == "" { |
| 89 | + return "#" // avoid trailing space on blank lines |
| 90 | + } |
| 91 | + return "# " + s |
| 92 | + }), |
| 93 | + "\n") |
| 94 | +} |
| 95 | + |
| 96 | +func (n *Node) MarshalYAML() (interface{}, error) { |
| 97 | + node := yaml.Node{ |
| 98 | + Kind: yaml.MappingNode, |
| 99 | + } |
| 100 | + |
| 101 | + keyNode := yaml.Node{ |
| 102 | + Kind: yaml.ScalarNode, |
| 103 | + Value: n.Name, |
| 104 | + } |
| 105 | + if n.Description != "" { |
| 106 | + setComment(&keyNode, n.Description) |
| 107 | + } |
| 108 | + |
| 109 | + if n.Default != nil { |
| 110 | + valueNode := yaml.Node{ |
| 111 | + Kind: yaml.ScalarNode, |
| 112 | + } |
| 113 | + err := valueNode.Encode(n.Default) |
| 114 | + if err != nil { |
| 115 | + return nil, err |
| 116 | + } |
| 117 | + node.Content = append(node.Content, &keyNode, &valueNode) |
| 118 | + } else if len(n.Children) > 0 { |
| 119 | + childrenNode := yaml.Node{ |
| 120 | + Kind: yaml.MappingNode, |
| 121 | + } |
| 122 | + for _, child := range n.Children { |
| 123 | + childYaml, err := child.MarshalYAML() |
| 124 | + if err != nil { |
| 125 | + return nil, err |
| 126 | + } |
| 127 | + |
| 128 | + childKey := yaml.Node{ |
| 129 | + Kind: yaml.ScalarNode, |
| 130 | + Value: child.Name, |
| 131 | + } |
| 132 | + if child.Description != "" { |
| 133 | + setComment(&childKey, child.Description) |
| 134 | + } |
| 135 | + childYaml = childYaml.(*yaml.Node) |
| 136 | + childrenNode.Content = append(childrenNode.Content, childYaml.(*yaml.Node).Content...) |
| 137 | + } |
| 138 | + node.Content = append(node.Content, &keyNode, &childrenNode) |
| 139 | + } |
| 140 | + |
| 141 | + return &node, nil |
| 142 | +} |
| 143 | + |
| 144 | +func getDescription(v *orderedmap.OrderedMap) string { |
| 145 | + description, ok := v.Get("description") |
| 146 | + if !ok { |
| 147 | + description = "" |
| 148 | + } |
| 149 | + return description.(string) |
| 150 | +} |
| 151 | + |
| 152 | +func getDefault(v *orderedmap.OrderedMap) (error, any) { |
| 153 | + defaultValue, ok := v.Get("default") |
| 154 | + if ok { |
| 155 | + return nil, defaultValue |
| 156 | + } |
| 157 | + |
| 158 | + dataType, ok := v.Get("type") |
| 159 | + if ok { |
| 160 | + dataTypeString := dataType.(string) |
| 161 | + if dataTypeString == "string" { |
| 162 | + return nil, "" |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + return errors.New("Failed to get default value"), nil |
| 167 | +} |
| 168 | + |
| 169 | +func parseNode(parent *Node, name string, value *orderedmap.OrderedMap) { |
| 170 | + description := getDescription(value) |
| 171 | + err, defaultValue := getDefault(value) |
| 172 | + if err == nil { |
| 173 | + leaf := &Node{Name: name, Description: description, Default: defaultValue} |
| 174 | + parent.Children = append(parent.Children, leaf) |
| 175 | + } |
| 176 | + |
| 177 | + properties, ok := value.Get("properties") |
| 178 | + if !ok { |
| 179 | + return |
| 180 | + } |
| 181 | + |
| 182 | + orderedProperties := properties.(orderedmap.OrderedMap) |
| 183 | + |
| 184 | + node := &Node{Name: name, Description: description} |
| 185 | + parent.Children = append(parent.Children, node) |
| 186 | + |
| 187 | + keys := orderedProperties.Keys() |
| 188 | + for _, name := range keys { |
| 189 | + value, _ := orderedProperties.Get(name) |
| 190 | + typedValue := value.(orderedmap.OrderedMap) |
| 191 | + parseNode(node, name, &typedValue) |
| 192 | + } |
| 193 | +} |
| 194 | + |
| 195 | +func writeToConfigDocs(config []byte) error { |
| 196 | + configPath := utils.GetLazyRootDirectory() + "/docs/Config.md" |
| 197 | + markdown, err := os.ReadFile(configPath) |
| 198 | + if err != nil { |
| 199 | + return fmt.Errorf("Error reading Config.md file %w", err) |
| 200 | + } |
| 201 | + |
| 202 | + startConfigSectionIndex := bytes.Index(markdown, []byte(DocumentationCommentStart)) |
| 203 | + if startConfigSectionIndex == -1 { |
| 204 | + return errors.New("Default config starting comment not found") |
| 205 | + } |
| 206 | + |
| 207 | + endConfigSectionIndex := bytes.Index(markdown[startConfigSectionIndex+DocumentationCommentStartLen:], []byte(DocumentationCommentEnd)) |
| 208 | + if endConfigSectionIndex == -1 { |
| 209 | + return errors.New("Default config closing comment not found") |
| 210 | + } |
| 211 | + |
| 212 | + endConfigSectionIndex = endConfigSectionIndex + startConfigSectionIndex + DocumentationCommentStartLen |
| 213 | + |
| 214 | + newMarkdown := make([]byte, 0, len(markdown)-endConfigSectionIndex+startConfigSectionIndex+len(config)) |
| 215 | + newMarkdown = append(newMarkdown, markdown[:startConfigSectionIndex+DocumentationCommentStartLen]...) |
| 216 | + newMarkdown = append(newMarkdown, config...) |
| 217 | + newMarkdown = append(newMarkdown, markdown[endConfigSectionIndex:]...) |
| 218 | + |
| 219 | + if err := os.WriteFile(configPath, newMarkdown, 0o644); err != nil { |
| 220 | + return fmt.Errorf("Error writing to file %w", err) |
| 221 | + } |
| 222 | + return nil |
| 223 | +} |
| 224 | + |
| 225 | +func GenerateConfigDocs() { |
| 226 | + content, err := os.ReadFile(GetSchemaDir() + "/config.json") |
| 227 | + if err != nil { |
| 228 | + panic("Error reading config.json") |
| 229 | + } |
| 230 | + |
| 231 | + schema := orderedmap.New() |
| 232 | + |
| 233 | + err = json.Unmarshal(content, &schema) |
| 234 | + if err != nil { |
| 235 | + panic("Failed to unmarshal config.json") |
| 236 | + } |
| 237 | + |
| 238 | + root, ok := schema.Get("properties") |
| 239 | + if !ok { |
| 240 | + panic("properties key not found in schema") |
| 241 | + } |
| 242 | + orderedRoot := root.(orderedmap.OrderedMap) |
| 243 | + |
| 244 | + rootNode := Node{} |
| 245 | + for _, name := range orderedRoot.Keys() { |
| 246 | + value, _ := orderedRoot.Get(name) |
| 247 | + typedValue := value.(orderedmap.OrderedMap) |
| 248 | + parseNode(&rootNode, name, &typedValue) |
| 249 | + } |
| 250 | + |
| 251 | + var buffer bytes.Buffer |
| 252 | + encoder := yaml.NewEncoder(&buffer) |
| 253 | + encoder.SetIndent(IndentLevel) |
| 254 | + |
| 255 | + for _, child := range rootNode.Children { |
| 256 | + err := encoder.Encode(child) |
| 257 | + if err != nil { |
| 258 | + panic("Failed to Marshal document") |
| 259 | + } |
| 260 | + } |
| 261 | + encoder.Close() |
| 262 | + |
| 263 | + config := prepareMarshalledConfig(buffer) |
| 264 | + |
| 265 | + err = writeToConfigDocs(config) |
| 266 | + if err != nil { |
| 267 | + panic(err) |
| 268 | + } |
| 269 | +} |
0 commit comments