Browse Source

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

The language tool only logged problems, so an empty YAML file generated an
empty JSON file, an unparseable file was skipped, and keys not present in
en.yaml were only warned about. These now stop generation with an error,
so the generated-check catches them. Missing keys remain warnings so new
English strings can be merged before every language is translated.

schemaVersion was never parsed because the struct only had json tags; it
now has yaml tags and must be 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jamesread 21 hours ago
parent
commit
d495d90051
2 changed files with 148 additions and 39 deletions
  1. 69 39
      lang/main.go
  2. 79 0
      lang/main_test.go

+ 69 - 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 int               `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,48 @@ 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
+	}
+
+	return output, validateTranslations(output)
+}
 
-		err = yaml.Unmarshal(content, &yamlData)
+func loadLanguageFile(fullPath string) (map[string]string, error) {
+	log.Infof("Loading language file: %s", fullPath)
 
-		if err != nil {
-			log.Errorf("Error reading language file %s: %v", fullPath, err)
-			continue
-		}
+	content, err := os.ReadFile(fullPath)
+	if err != nil {
+		return nil, fmt.Errorf("reading language file %s: %w", fullPath, err)
+	}
+
+	var yamlData LanguageFilev1
 
-		output.Messages[languageName] = yamlData.Translations
+	err = yaml.Unmarshal(content, &yamlData)
+	if err != nil {
+		return nil, fmt.Errorf("parsing language file %s: %w", fullPath, err)
+	}
+
+	if yamlData.SchemaVersion != 1 {
+		return nil, fmt.Errorf("language file %s has schemaVersion %d, expected 1", fullPath, yamlData.SchemaVersion)
 	}
 
-	validateTranslations(output)
+	if len(yamlData.Translations) == 0 {
+		return nil, fmt.Errorf("language file %s has no translations", fullPath)
+	}
 
-	return output
+	return yamlData.Translations, nil
 }
 
 // getReferenceKeys returns the keys from the "en" translation as the reference set.
@@ -196,29 +210,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 {

+ 79 - 0
lang/main_test.go

@@ -0,0 +1,79 @@
+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 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")
+	}
+}