Skip to content

Instantly share code, notes, and snippets.

@ANPez
Created August 29, 2017 11:06
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ANPez/57deba50a926ed897aeed38c5aa745c5 to your computer and use it in GitHub Desktop.
Script to reorder a strings.xml according to another ordered file. Useful if you want your translations to be ordered in the same order.
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)
type resources struct {
XMLName xml.Name `xml:"resources"`
Resources []resource `xml:"string"`
}
type resource struct {
XMLName xml.Name `xml:"string"`
Name string `xml:"name,attr"`
Value string `xml:",innerxml"`
}
func readResourcesFrom(file string) (*resources, error) {
xmlFile, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
res := new(resources)
err = xml.Unmarshal(xmlFile, res)
if err != nil {
return nil, err
}
return res, nil
}
func main() {
if len(os.Args) != 3 {
fmt.Fprintf(os.Stderr, "Usage: %s file.xml ordered.xml\n", os.Args[0])
os.Exit(1)
}
file, err := readResourcesFrom(os.Args[1])
if err != nil {
fmt.Fprintln(os.Stderr, "Error parsing file:", err)
return
}
ordered, err := readResourcesFrom(os.Args[2])
if err != nil {
fmt.Fprintln(os.Stderr, "Error parsing ordered file:", err)
return
}
var result resources
for _, orderedString := range ordered.Resources {
found := false
for i, fileString := range file.Resources {
if fileString.Name == orderedString.Name {
result.Resources = append(result.Resources, fileString)
file.Resources = append(file.Resources[:i], file.Resources[i+1:]...)
found = true
break
}
}
if !found {
fmt.Fprintln(os.Stderr, "No matching element found for ordered element: ", orderedString.Name)
return
}
}
if len(file.Resources) > 0 {
fmt.Fprintf(os.Stderr, "%d resources left after processing.\n", len(file.Resources))
for _, fileString := range file.Resources {
fmt.Fprintln(os.Stderr, "-", fileString.Name)
}
}
res, err := xml.MarshalIndent(result, "", " ")
if err != nil {
fmt.Fprintln(os.Stderr, "Error marshaling result:", err)
return
}
fmt.Println(string(res))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment