-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert_yaml_to_json.go
More file actions
98 lines (89 loc) · 3.01 KB
/
Copy pathconvert_yaml_to_json.go
File metadata and controls
98 lines (89 loc) · 3.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
)
// convertYamlToJSON converts assignment.yml or assignment.yaml files to JSON format.
// It does this by simply wrapping the YAML content with { } and validating the result is valid JSON.
// If successful, it writes the content to assignment.json and deletes the original YAML file.
func convertYamlToJSON(args []string) {
yamlFiles, err := findAssignmentYamlFiles(gitRoot)
if err != nil {
exitErr(err, "Error finding YAML files")
}
if len(yamlFiles) == 0 {
fmt.Println("No assignment.yml or assignment.yaml files found.")
return
}
for _, yamlFile := range yamlFiles {
if err := convertSingleFile(yamlFile); err != nil {
fmt.Printf("Error converting %s: %s\n", yamlFile, err)
continue
}
fmt.Printf("Successfully converted %s to assignment.json\n", yamlFile)
}
}
// findAssignmentYamlFiles finds all assignment.yml and assignment.yaml files in the given directory and its subdirectories
func findAssignmentYamlFiles(path string) ([]string, error) {
var yamlFiles []string
err := filepath.WalkDir(path, func(filePath string, dirEntry os.DirEntry, err error) error {
if err != nil {
return err
}
if dirEntry.IsDir() {
return nil
}
filename := dirEntry.Name()
if filename == "assignment.yml" || filename == "assignment.yaml" {
yamlFiles = append(yamlFiles, filePath)
}
return nil
})
return yamlFiles, err
}
// convertSingleFile converts a YAML file to JSON.
func convertSingleFile(yamlFilePath string) error {
content, err := os.ReadFile(yamlFilePath)
if err != nil {
return fmt.Errorf("failed to read YAML file: %w", err)
}
contentStr := strings.TrimSpace(string(content))
if contentStr == "" {
return fmt.Errorf("empty YAML file")
}
jsonContent := convertYamlKeysToJSON(contentStr)
// Validate that the result is valid JSON without reordering
var jsonObj json.RawMessage
if err := json.Unmarshal([]byte(jsonContent), &jsonObj); err != nil {
return fmt.Errorf("resulting content is not valid JSON: %w", err)
}
jsonContentBytes := []byte(jsonContent)
dir := filepath.Dir(yamlFilePath)
jsonFilePath := filepath.Join(dir, "assignment.json")
if err := os.WriteFile(jsonFilePath, jsonContentBytes, 0o644); err != nil {
return fmt.Errorf("failed to write JSON file: %w", err)
}
if err := os.Remove(yamlFilePath); err != nil {
return fmt.Errorf("failed to delete original YAML file: %w", err)
}
return nil
}
// convertYamlKeysToJSON converts YAML key-value pairs to JSON format by adding quotes around keys
func convertYamlKeysToJSON(yamlContent string) string {
var jsonLines []string
for line := range strings.Lines(yamlContent) {
key, val, found := strings.Cut(line, ":")
if found {
jsonLines = append(jsonLines, fmt.Sprintf(` "%s": %s`, key, strings.TrimSpace(val)))
} else {
// skip lines that do not match key-value pairs
fmt.Printf("Skipping line: %s\n", line)
continue
}
}
// Join with commas and newlines for proper JSON format
return "{\n" + strings.Join(jsonLines, ",\n") + "\n}"
}