Last active
September 25, 2024 09:04
-
-
Save hawx/b1c4453df87f1ad9f600a28191eaba65 to your computer and use it in GitHub Desktop.
Replace values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Replace values takes two JSON files as inputs, it will replace the values of | |
// the keys of the first file using the values from the second. This is built | |
// for the first file to be a download of untranslated keys from Weblate, and | |
// the second file to be our language file. | |
// | |
// Given files keys.json: | |
// | |
// { "a": 1 } | |
// | |
// and values.json: | |
// | |
// { "a": 2, "b": 3 } | |
// | |
// Running: | |
// | |
// replace-values keys.json values.json | |
// | |
// Would print: | |
// | |
// "a",2 | |
package main | |
import ( | |
"encoding/csv" | |
"encoding/json" | |
"flag" | |
"log" | |
"os" | |
"strings" | |
) | |
func main() { | |
flag.Parse() | |
if err := run(); err != nil { | |
log.Println(err) | |
} | |
} | |
func run() error { | |
keysFile, err := os.Open(flag.Arg(0)) | |
if err != nil { | |
return err | |
} | |
valuesFile, err := os.Open(flag.Arg(1)) | |
if err != nil { | |
return err | |
} | |
var keys map[string]string | |
if err := json.NewDecoder(keysFile).Decode(&keys); err != nil { | |
return err | |
} | |
var values map[string]any | |
if err := json.NewDecoder(valuesFile).Decode(&values); err != nil { | |
return err | |
} | |
for k := range keys { | |
if before, after, ok := strings.Cut(k, "."); ok { | |
keys[k] = values[before].(map[string]any)[after].(string) | |
} else { | |
keys[k] = values[k].(string) | |
} | |
} | |
writer := csv.NewWriter(os.Stdout) | |
for k, v := range keys { | |
writer.Write([]string{k, v}) | |
} | |
writer.Flush() | |
if err := writer.Error(); err != nil { | |
return err | |
} | |
return err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment