Skip to content

Commit

Permalink
Merge pull request #68 from kobergj/AddFSToLocale
Browse files Browse the repository at this point in the history
Allow locale to use a `fs.FS`
  • Loading branch information
leonelquinteros authored Mar 17, 2023
2 parents 6f9bcaa + 8ebc12b commit 71a59c0
Show file tree
Hide file tree
Showing 7 changed files with 391 additions and 254 deletions.
37 changes: 31 additions & 6 deletions locale.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package gotext
import (
"bytes"
"encoding/gob"
"io/fs"
"os"
"path"
"sync"
Expand Down Expand Up @@ -60,6 +61,9 @@ type Locale struct {

// Sync Mutex
sync.RWMutex

// optional fs to use
fs fs.FS
}

// NewLocale creates and initializes a new Locale object for a given language.
Expand All @@ -72,48 +76,69 @@ func NewLocale(p, l string) *Locale {
}
}

// NewLocaleFS returns a Locale working with a fs.FS
func NewLocaleFS(l string, filesystem fs.FS) *Locale {
loc := NewLocale("", l)
loc.fs = filesystem
return loc
}

func (l *Locale) findExt(dom, ext string) string {
filename := path.Join(l.path, l.lang, "LC_MESSAGES", dom+"."+ext)
if _, err := os.Stat(filename); err == nil {
if l.fileExists(filename) {
return filename
}

if len(l.lang) > 2 {
filename = path.Join(l.path, l.lang[:2], "LC_MESSAGES", dom+"."+ext)
if _, err := os.Stat(filename); err == nil {
if l.fileExists(filename) {
return filename
}
}

filename = path.Join(l.path, l.lang, dom+"."+ext)
if _, err := os.Stat(filename); err == nil {
if l.fileExists(filename) {
return filename
}

if len(l.lang) > 2 {
filename = path.Join(l.path, l.lang[:2], dom+"."+ext)
if _, err := os.Stat(filename); err == nil {
if l.fileExists(filename) {
return filename
}
}

return ""
}

func (l *Locale) fileExists(filename string) bool {
if l.fs != nil {
f, err := l.fs.Open(filename)
if err != nil {
return false
}
_, err = f.Stat()
return err == nil

}
_, err := os.Stat(filename)
return err == nil
}

// AddDomain creates a new domain for a given locale object and initializes the Po object.
// If the domain exists, it gets reloaded.
func (l *Locale) AddDomain(dom string) {
var poObj Translator

file := l.findExt(dom, "po")
if file != "" {
poObj = NewPo()
poObj = NewPoFS(l.fs)
// Parse file.
poObj.ParseFile(file)
} else {
file = l.findExt(dom, "mo")
if file != "" {
poObj = NewMo()
poObj = NewMoFS(l.fs)
// Parse file.
poObj.ParseFile(file)
} else {
Expand Down
Loading

0 comments on commit 71a59c0

Please sign in to comment.