Created
April 20, 2018 19:01
-
-
Save filipeandre/516220f6906fb7c35fda14fb490d4f12 to your computer and use it in GitHub Desktop.
Simple script used to translate laravel lang file
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
package main | |
import ( | |
"fmt" | |
"io" | |
"log" | |
"os" | |
"regexp" | |
"bufio" | |
"bytes" | |
"github.com/jinzhongmin/gtra" | |
"time" | |
"strings" | |
) | |
//Settings | |
const ( | |
langFile = "source/lang/file" | |
destLangFile = "dest/lang/file" | |
) | |
//Regex | |
var ( | |
matchTranslation = regexp.MustCompile(`=> '(.*)',`) | |
) | |
// If has error then break the app | |
func check(e error) { | |
if e != nil { | |
log.Fatal(e) | |
} | |
} | |
// Read a whole file into the memory and store it as array of lines | |
func readLines(path string) (lines []string, err error) { | |
var ( | |
file *os.File | |
part []byte | |
prefix bool | |
) | |
if file, err = os.Open(path); err != nil { | |
return | |
} | |
defer file.Close() | |
reader := bufio.NewReader(file) | |
buffer := bytes.NewBuffer(make([]byte, 0)) | |
for { | |
if part, prefix, err = reader.ReadLine(); | |
err != nil { | |
break | |
} | |
buffer.Write(part) | |
if !prefix { | |
lines = append(lines, buffer.String()) | |
buffer.Reset() | |
} | |
} | |
if err == io.EOF { | |
err = nil | |
} | |
return | |
} | |
// Write all file lines back into file | |
func writeLines(lines []string, path string) (err error) { | |
var ( | |
file *os.File | |
) | |
if file, err = os.Create(path); err != nil { | |
return | |
} | |
defer file.Close() | |
lastI := len(lines) -1 | |
for i,item := range lines { | |
tmp := item | |
if lastI != i { | |
tmp = tmp + "\n" | |
} | |
_, err = file.WriteString(tmp) | |
check(err) | |
} | |
return | |
} | |
func main() { | |
start := time.Now() | |
fmt.Println("Working...") | |
lines, err := readLines(langFile) | |
check(err) | |
t := gtra.New() | |
l := gtra.NewConstLang() | |
for i, line := range lines { | |
lines[i] = matchTranslation.ReplaceAllStringFunc(line, func(m string) string{ | |
parts := matchTranslation.FindStringSubmatch(m) | |
tmp := parts[1] | |
tmp = t.Translate(tmp).To(l.PT, func(e error) string { | |
check(e) | |
return "?" | |
}) | |
return strings.Replace(m, parts[1], tmp, -1) | |
}) | |
} | |
err = writeLines(lines, destLangFile) | |
check(err) | |
time := time.Now() | |
elapsed := time.Sub(start) | |
fmt.Printf("Finished in %vms", elapsed.Nanoseconds()/1e6 ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment