Skip to content

Instantly share code, notes, and snippets.

@eumel8
Created June 11, 2024 15:52
Show Gist options
  • Save eumel8/ead695d37d6bffe728cab1f5098d96d8 to your computer and use it in GitHub Desktop.
Save eumel8/ead695d37d6bffe728cab1f5098d96d8 to your computer and use it in GitHub Desktop.
sort-yaml
// a program to sort keys in a given directory with yaml files
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"sort"
"strings"
"gopkg.in/yaml.v2"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Work dir is required.")
return
}
// work dir as program argument
dir := os.Args[1]
fmt.Printf("Work dirs: %s\n", dir)
// read list of files
files, err := ioutil.ReadDir(dir)
if err != nil {
fmt.Printf("Error read directory: %v\n", err)
return
}
// work on each file
for _, filename := range files {
if strings.HasSuffix(filename.Name(), ".yaml") {
fmt.Println(filename.Name())
// Read the YAML file
content, err := ioutil.ReadFile(filename.Name())
if err != nil {
log.Fatalf("Error reading file: %v", err)
}
// Unmarshal YAML data into a map
var data map[interface{}]interface{}
if err := yaml.Unmarshal(content, &data); err != nil {
log.Fatalf("Error unmarshaling YAML: %v", err)
}
// Sort keys alphabetically
keys := make([]string, 0, len(data))
for key := range data {
keys = append(keys, key.(string))
}
sort.Strings(keys)
// Create an ordered map
orderedData := make(map[interface{}]interface{})
for _, key := range keys {
orderedData[key] = data[key]
}
// Marshal the ordered data back to YAML
output, err := yaml.Marshal(orderedData)
if err != nil {
log.Fatalf("Error marshaling YAML: %v", err)
}
if err := ioutil.WriteFile(filename.Name(), output, 0644); err != nil {
log.Fatalf("Error writing file: %v", err)
}
fmt.Printf("Sorted YAML data written to %s\n", filename.Name())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment