From 6cb67a6f35cf4a740ba6ca4a9d21e440ff3e07be Mon Sep 17 00:00:00 2001 From: aitzol76 Date: Sun, 16 Oct 2022 16:26:42 +0200 Subject: [PATCH] first commit --- go.mod | 3 +++ main.go | 27 +++++++++++++++++++ po2json/po2json.go | 65 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 95 insertions(+) create mode 100644 go.mod create mode 100644 main.go create mode 100644 po2json/po2json.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..c08e72b --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module po2json + +go 1.19 diff --git a/main.go b/main.go new file mode 100644 index 0000000..95c1e3d --- /dev/null +++ b/main.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "po2json/po2json" + "io/ioutil" +) + +func main(){ + + //locales := []string{"en_UK", "eu_ES"} + locales := []string {} + domain := "base" + localedir := "locales" + files,_ := ioutil.ReadDir(localedir) + for _, f := range files { + if f.IsDir() { + fmt.Println(f.Name()) + locales = append(locales, f.Name(),) + } + } + + //fmt.Println(po2json.PO2JSON([]string{locales[0], locales[1]}, domain, localedir)) + fmt.Println(po2json.PO2JSON(locales, domain, localedir)) + +} + diff --git a/po2json/po2json.go b/po2json/po2json.go new file mode 100644 index 0000000..5ad339f --- /dev/null +++ b/po2json/po2json.go @@ -0,0 +1,65 @@ +package po2json + +import "regexp" +import "io/ioutil" +import "encoding/json" +import "strings" + +type msgIdStrPairs map[string]string +type localesMsg map[string]msgIdStrPairs + +//const pattern = `msgid "(.+)"\nmsgstr "(.+)"` +//const patternP = `msgid "(.+)"\nmsgid_plural "(.+)"\nmsgstr\[.\] "(.+)"\nmsgstr\[.\] "(.+)"` +var pattern = [2] string {`msgid "(.+)"\nmsgstr "(.+)"`,`msgid "(.+)"\nmsgid_plural "(.+)"\nmsgstr\[.\] "(.+)"\nmsgstr\[.\] "(.+)"`} + +func getPOPath(locale, domain, localedir string) string { + return localedir + "/" + locale + "/LC_MESSAGES/" + domain + ".po" +} + +func extractFromPOFile(popath string) msgIdStrPairs { + buf, err := ioutil.ReadFile(popath) + if err != nil { + panic(err) + } + + pairs := msgIdStrPairs{} + + for j:= 0; j < 2; j++{ + re := regexp.MustCompile(pattern[j]) + matches := re.FindAllStringSubmatch(string(buf), -1) + + if(strings.Count(pattern[j], "msg") == 4 ){ + for _, array := range matches { + pairs[array[1]] = array[3] + pairs[array[2]] = array[4] + } + }else{ + for _, array := range matches { + pairs[array[1]] = array[2] + } + } + + } + + return pairs +} + +func PO2JSON(locales []string, domain, localedir string) string { + // create PO-like json data for i18n + obj := localesMsg{} + for _, locale := range locales { + // English is default language + if locale == "en_US" { + continue + } + + obj[locale] = extractFromPOFile(getPOPath(locale, domain, localedir)) + } + + b, err := json.Marshal(obj) + if err != nil { + panic(err) + } + + return string(b) +} \ No newline at end of file