first commit

This commit is contained in:
aitzol76 2022-10-16 16:26:42 +02:00
commit 6cb67a6f35
3 changed files with 95 additions and 0 deletions

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module po2json
go 1.19

27
main.go Normal file
View File

@ -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))
}

65
po2json/po2json.go Normal file
View File

@ -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)
}