Browse Source

Update Import & Export

- Added ImportByReader(...) for those that already have the file open or are using embedded assets.
- Made concrete errors for Import & Export.
joeybloggs 8 năm trước cách đây
mục cha
commit
8c4ba43db1
6 tập tin đã thay đổi với 94 bổ sung40 xóa
  1. 1 1
      .gitignore
  2. 24 0
      errors.go
  3. 52 39
      import_export.go
  4. 12 0
      import_export_test.go
  5. 3 0
      testdata/.gitignore
  6. 2 0
      translator_test.go

+ 1 - 1
.gitignore

@@ -21,4 +21,4 @@ _testmain.go
 
 *.exe
 *.test
-*.prof
+*.prof

+ 24 - 0
errors.go

@@ -93,3 +93,27 @@ func (e *ErrMissingPluralTranslation) Error() string {
 
 	return fmt.Sprintf("error: missing '%s' plural rule '%s' for translation with key '%s'", e.translationType, e.rule, e.key)
 }
+
+// import/export errors
+
+// ErrMissingLocale is the error representing an expected locale that could
+// not be found aka locale not registered with the UniversalTranslator Instance
+type ErrMissingLocale struct {
+	locale string
+}
+
+// Error returns ErrMissingLocale's internal error text
+func (e *ErrMissingLocale) Error() string {
+	return fmt.Sprintf("error: locale '%s' not registered.", e.locale)
+}
+
+// ErrBadPluralDefinition is the error representing an incorrect plural definition
+// usually found within translations defined within files during the import process.
+type ErrBadPluralDefinition struct {
+	tl translation
+}
+
+// Error returns ErrBadPluralDefinition's internal error text
+func (e *ErrBadPluralDefinition) Error() string {
+	return fmt.Sprintf("error: bad plural definition '%#v'", e.tl)
+}

+ 52 - 39
import_export.go

@@ -2,17 +2,18 @@ package ut
 
 import (
 	"encoding/json"
-	"fmt"
 	"io/ioutil"
 	"os"
 	"path/filepath"
 
+	"io"
+
 	"github.com/go-playground/locales"
 )
 
 type translation struct {
 	Locale           string      `json:"locale"`
-	Key              interface{} `json:"key"`
+	Key              interface{} `json:"key"` // either string or integer
 	Translation      string      `json:"trans"`
 	PluralType       string      `json:"type,omitempty"`
 	PluralRule       string      `json:"rule,omitempty"`
@@ -139,66 +140,78 @@ func (t *UniversalTranslator) Import(format ExportFormat, dirnameOrFilename stri
 
 	processFn := func(filename string) error {
 
-		b, err := ioutil.ReadFile(filename)
+		f, err := os.Open(filename)
 		if err != nil {
 			return err
 		}
+		defer f.Close()
 
-		var trans []translation
+		return t.ImportByReader(format, f)
+	}
 
-		switch format {
-		case JSON:
-			err = json.Unmarshal(b, &trans)
-		}
+	if !fi.IsDir() {
+		return processFn(dirnameOrFilename)
+	}
 
-		if err != nil {
-			return err
+	// recursively go through directory
+
+	walker := func(path string, info os.FileInfo, err error) error {
+
+		if info.IsDir() {
+			return nil
 		}
 
-		for _, tl := range trans {
+		return processFn(dirnameOrFilename)
+	}
 
-			locale, found := t.FindTranslator(tl.Locale)
-			if !found {
-				return fmt.Errorf("locale '%s' not registered for translation in file '%s'", tl.Locale, filename)
-			}
+	return filepath.Walk(dirnameOrFilename, walker)
+}
 
-			pr := stringToPR(tl.PluralRule)
+// ImportByReader imports a files contexts
+func (t *UniversalTranslator) ImportByReader(format ExportFormat, reader io.Reader) error {
 
-			if pr == locales.PluralRuleUnknown {
-				return locale.Add(tl.Key, tl.Translation, tl.OverrideExisting)
-			}
+	b, err := ioutil.ReadAll(reader)
+	if err != nil {
+		return err
+	}
 
-			switch tl.PluralType {
-			case cardinalType:
-				return locale.AddCardinal(tl.Key, tl.Translation, pr, tl.OverrideExisting)
-			case ordinalType:
-				return locale.AddOrdinal(tl.Key, tl.Translation, pr, tl.OverrideExisting)
-			case rangeType:
-				return locale.AddRange(tl.Key, tl.Translation, pr, tl.OverrideExisting)
-			default:
-				return fmt.Errorf("bad plural rule '%#v', incorrect plural information found for translation in file '%s'", tl, filename)
-			}
-		}
+	var trans []translation
 
-		return nil
+	switch format {
+	case JSON:
+		err = json.Unmarshal(b, &trans)
 	}
 
-	if !fi.IsDir() {
-		return processFn(dirnameOrFilename)
+	if err != nil {
+		return err
 	}
 
-	// recursively go through directory
+	for _, tl := range trans {
 
-	walker := func(path string, info os.FileInfo, err error) error {
+		locale, found := t.FindTranslator(tl.Locale)
+		if !found {
+			return &ErrMissingLocale{locale: tl.Locale}
+		}
 
-		if info.IsDir() {
-			return nil
+		pr := stringToPR(tl.PluralRule)
+
+		if pr == locales.PluralRuleUnknown {
+			return locale.Add(tl.Key, tl.Translation, tl.OverrideExisting)
 		}
 
-		return processFn(dirnameOrFilename)
+		switch tl.PluralType {
+		case cardinalType:
+			return locale.AddCardinal(tl.Key, tl.Translation, pr, tl.OverrideExisting)
+		case ordinalType:
+			return locale.AddOrdinal(tl.Key, tl.Translation, pr, tl.OverrideExisting)
+		case rangeType:
+			return locale.AddRange(tl.Key, tl.Translation, pr, tl.OverrideExisting)
+		default:
+			return &ErrBadPluralDefinition{tl: tl}
+		}
 	}
 
-	return filepath.Walk(dirnameOrFilename, walker)
+	return nil
 }
 
 func stringToPR(s string) locales.PluralRule {

+ 12 - 0
import_export_test.go

@@ -0,0 +1,12 @@
+package ut
+
+// NOTES:
+// - Run "go test" to run tests
+// - Run "gocov test | gocov report" to report on test converage by file
+// - Run "gocov test | gocov annotate -" to report on all code and functions, those ,marked with "MISS" were never called
+//
+// or
+//
+// -- may be a good idea to change to output path to somewherelike /tmp
+// go test -coverprofile cover.out && go tool cover -html=cover.out -o cover.html
+//

+ 3 - 0
testdata/.gitignore

@@ -0,0 +1,3 @@
+*
+
+!.gitignore

+ 2 - 0
translator_test.go

@@ -243,6 +243,8 @@ func TestCardinalTranslation(t *testing.T) {
 			t.Errorf("Expected '%s' Got '%s'", tt.expected, s)
 		}
 	}
+
+	uni.Export(JSON, "test.json")
 }
 
 func TestOrdinalTranslation(t *testing.T) {