Просмотр исходного кода

fix(lang): fail generation on empty, invalid or mistyped language files (#1194)

James Read 21 часов назад
Родитель
Сommit
0cbbc4522d
3 измененных файлов с 180 добавлено и 39 удалено
  1. 5 0
      .github/workflows/generated.yml
  2. 80 39
      lang/main.go
  3. 95 0
      lang/main_test.go

+ 5 - 0
.github/workflows/generated.yml

@@ -18,6 +18,7 @@ on:
       - 'service/Makefile'
       - 'service/tools.go'
   pull_request:
+    types: [opened, synchronize, reopened, edited]
     branches:
       - next
     paths:
@@ -54,5 +55,9 @@ jobs:
             service/go.sum
             lang/go.sum
 
+      - name: Test language tool
+        run: go test ./...
+        working-directory: lang
+
       - name: Check generated sources
         run: make generated-check

+ 80 - 39
lang/main.go

@@ -2,6 +2,8 @@ package main
 
 import (
 	"encoding/json"
+	"errors"
+	"fmt"
 	"os"
 	"path/filepath"
 	"sort"
@@ -14,8 +16,8 @@ import (
 )
 
 type LanguageFilev1 struct {
-	SchemaVersion int               `json:"schemaVersion"`
-	Translations  map[string]string `json:"translations"`
+	SchemaVersion yaml.Node         `json:"schemaVersion" yaml:"schemaVersion"`
+	Translations  map[string]string `json:"translations" yaml:"translations"`
 }
 
 type CombinedTranslationsOutput struct {
@@ -24,10 +26,14 @@ type CombinedTranslationsOutput struct {
 }
 
 func main() {
-	combinedContent := getCombinedLanguageContent()
+	combinedContent, err := getCombinedLanguageContent()
+	if err != nil {
+		log.Fatalf("Error loading language files: %v", err)
+	}
+
 	sortedContent := sortTranslations(combinedContent)
 
-	err := writeTranslationFiles(sortedContent.Messages)
+	err = writeTranslationFiles(sortedContent.Messages)
 	if err != nil {
 		log.Fatalf("Error writing language content: %v", err)
 	}
@@ -115,7 +121,7 @@ func getLanguageDir() string {
 	return dir
 }
 
-func getCombinedLanguageContent() *CombinedTranslationsOutput {
+func getCombinedLanguageContent() (*CombinedTranslationsOutput, error) {
 	output := &CombinedTranslationsOutput{
 		Comment:  "This file is generated. Please re-generate this file using 'make' when you update a translation.",
 		Messages: make(map[string]map[string]string),
@@ -124,40 +130,59 @@ func getCombinedLanguageContent() *CombinedTranslationsOutput {
 	languageDir := getLanguageDir()
 
 	files, err := os.ReadDir(languageDir)
-
 	if err != nil {
-		log.Errorf("Error reading language directory %s: %v", languageDir, err)
-		return output
+		return nil, fmt.Errorf("reading language directory %s: %w", languageDir, err)
 	}
 
 	for _, file := range filterLanguageFiles(files) {
-		languageName := strings.Replace(file.Name(), ".yaml", "", 1)
-
-		fullPath := filepath.Join(languageDir, file.Name())
-		log.Infof("Loading language file: %s", fullPath)
-
-		content, err := os.ReadFile(fullPath)
+		languageName := strings.TrimSuffix(file.Name(), ".yaml")
 
+		translations, err := loadLanguageFile(filepath.Join(languageDir, file.Name()))
 		if err != nil {
-			log.Errorf("Error reading language file %s: %v", fullPath, err)
-			continue
+			return nil, err
 		}
 
-		var yamlData LanguageFilev1
+		output.Messages[languageName] = translations
+	}
 
-		err = yaml.Unmarshal(content, &yamlData)
+	return output, validateTranslations(output)
+}
 
-		if err != nil {
-			log.Errorf("Error reading language file %s: %v", fullPath, err)
-			continue
-		}
+func loadLanguageFile(fullPath string) (map[string]string, error) {
+	log.Infof("Loading language file: %s", fullPath)
+
+	content, err := os.ReadFile(fullPath)
+	if err != nil {
+		return nil, fmt.Errorf("reading language file %s: %w", fullPath, err)
+	}
+
+	var yamlData LanguageFilev1
+
+	err = yaml.Unmarshal(content, &yamlData)
+	if err != nil {
+		return nil, fmt.Errorf("parsing language file %s: %w", fullPath, err)
+	}
 
-		output.Messages[languageName] = yamlData.Translations
+	err = validateSchemaVersion(&yamlData.SchemaVersion)
+	if err != nil {
+		return nil, fmt.Errorf("language file %s: %w", fullPath, err)
+	}
+
+	if len(yamlData.Translations) == 0 {
+		return nil, fmt.Errorf("language file %s has no translations", fullPath)
 	}
 
-	validateTranslations(output)
+	return yamlData.Translations, nil
+}
+
+// validateSchemaVersion checks the raw YAML scalar, because decoding straight
+// into an int silently truncates values such as 1.5 to 1.
+func validateSchemaVersion(node *yaml.Node) error {
+	if node.Kind != yaml.ScalarNode || node.ShortTag() != "!!int" || node.Value != "1" {
+		return fmt.Errorf("schemaVersion is %q, expected 1", node.Value)
+	}
 
-	return output
+	return nil
 }
 
 // getReferenceKeys returns the keys from the "en" translation as the reference set.
@@ -196,29 +221,45 @@ func findExtraKeys(referenceKeys map[string]bool, translations map[string]string
 	return extra
 }
 
-// validateTranslations checks all translations against the "en" reference and prints warnings for missing and extra keys.
-func validateTranslations(output *CombinedTranslationsOutput) {
+// validateTranslations checks all translations against the "en" reference.
+// Missing keys are only warnings, so that new English strings can be merged
+// before every language has been translated. Extra keys are errors, as they
+// are usually typos and are never displayed.
+func validateTranslations(output *CombinedTranslationsOutput) error {
 	referenceKeys := getReferenceKeys(output.Messages)
 	if referenceKeys == nil {
-		log.Warnf("No 'en' translation found, skipping validation")
-		return
+		return errors.New("no 'en' translation found to validate against")
 	}
 
+	invalidLanguages := make([]string, 0)
+
 	for langName, translations := range output.Messages {
-		if langName == "en" {
-			continue
+		if !checkLanguageKeys(langName, referenceKeys, translations) {
+			invalidLanguages = append(invalidLanguages, langName)
 		}
+	}
 
-		missing := findMissingKeys(referenceKeys, translations)
-		if len(missing) > 0 {
-			log.Warnf("Translation '%s' is missing %d key(s): %v", langName, len(missing), missing)
-		}
+	if len(invalidLanguages) > 0 {
+		sort.Strings(invalidLanguages)
+		return fmt.Errorf("translations with keys that are not in 'en': %v", invalidLanguages)
+	}
 
-		extra := findExtraKeys(referenceKeys, translations)
-		if len(extra) > 0 {
-			log.Warnf("Translation '%s' has %d extra key(s) not in 'en': %v", langName, len(extra), extra)
-		}
+	return nil
+}
+
+func checkLanguageKeys(langName string, referenceKeys map[string]bool, translations map[string]string) bool {
+	missing := findMissingKeys(referenceKeys, translations)
+	if len(missing) > 0 {
+		log.Warnf("Translation '%s' is missing %d key(s): %v", langName, len(missing), missing)
+	}
+
+	extra := findExtraKeys(referenceKeys, translations)
+	if len(extra) > 0 {
+		log.Errorf("Translation '%s' has %d extra key(s) not in 'en': %v", langName, len(extra), extra)
+		return false
 	}
+
+	return true
 }
 
 func filterLanguageFiles(files []os.DirEntry) []os.DirEntry {

+ 95 - 0
lang/main_test.go

@@ -0,0 +1,95 @@
+package main
+
+import (
+	"os"
+	"path/filepath"
+	"testing"
+)
+
+func writeLanguageFile(t *testing.T, content string) string {
+	t.Helper()
+
+	path := filepath.Join(t.TempDir(), "xx-XX.yaml")
+	if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
+		t.Fatal(err)
+	}
+
+	return path
+}
+
+func TestLoadLanguageFileRejectsEmptyFile(t *testing.T) {
+	if _, err := loadLanguageFile(writeLanguageFile(t, "")); err == nil {
+		t.Error("expected an error for an empty language file")
+	}
+}
+
+func TestLoadLanguageFileRejectsWrongSchemaVersion(t *testing.T) {
+	if _, err := loadLanguageFile(writeLanguageFile(t, "schemaVersion: 2\ntranslations:\n  welcome: Hi\n")); err == nil {
+		t.Error("expected an error for an unsupported schemaVersion")
+	}
+}
+
+func TestLoadLanguageFileRejectsNonIntegerSchemaVersion(t *testing.T) {
+	for _, schemaVersion := range []string{"1.5", "1.0", "\"1\"", "0x1", "[1]"} {
+		content := "schemaVersion: " + schemaVersion + "\ntranslations:\n  welcome: Hi\n"
+
+		if _, err := loadLanguageFile(writeLanguageFile(t, content)); err == nil {
+			t.Errorf("expected an error for schemaVersion %s", schemaVersion)
+		}
+	}
+}
+
+func TestLoadLanguageFileRejectsMissingSchemaVersion(t *testing.T) {
+	if _, err := loadLanguageFile(writeLanguageFile(t, "translations:\n  welcome: Hi\n")); err == nil {
+		t.Error("expected an error for a missing schemaVersion")
+	}
+}
+
+func TestLoadLanguageFileRejectsInvalidYaml(t *testing.T) {
+	if _, err := loadLanguageFile(writeLanguageFile(t, "schemaVersion: 1\ntranslations: [\n")); err == nil {
+		t.Error("expected an error for invalid YAML")
+	}
+}
+
+func TestLoadLanguageFileAcceptsValidFile(t *testing.T) {
+	translations, err := loadLanguageFile(writeLanguageFile(t, "schemaVersion: 1\ntranslations:\n  welcome: Hi\n"))
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	if translations["welcome"] != "Hi" {
+		t.Errorf("unexpected translations: %v", translations)
+	}
+}
+
+func TestValidateTranslationsAllowsMissingKeys(t *testing.T) {
+	output := &CombinedTranslationsOutput{Messages: map[string]map[string]string{
+		"en":    {"welcome": "Hi", "docs": "Docs"},
+		"xx-XX": {"welcome": "Salut"},
+	}}
+
+	if err := validateTranslations(output); err != nil {
+		t.Errorf("missing keys should only warn, got %v", err)
+	}
+}
+
+func TestValidateTranslationsRejectsExtraKeys(t *testing.T) {
+	output := &CombinedTranslationsOutput{Messages: map[string]map[string]string{
+		"en":    {"welcome": "Hi"},
+		"xx-XX": {"welcome": "Salut", "welcom": "Typo"},
+	}}
+
+	if err := validateTranslations(output); err == nil {
+		t.Error("expected an error for keys not in 'en'")
+	}
+}
+
+func TestValidateTranslationsRequiresEnglish(t *testing.T) {
+	output := &CombinedTranslationsOutput{Messages: map[string]map[string]string{
+		"xx-XX": {"welcome": "Salut"},
+	}}
+
+	if err := validateTranslations(output); err == nil {
+		t.Error("expected an error when 'en' is missing")
+	}
+}