diff --git a/clients/cli/cmd/internal/placeholders/placeholders.go b/clients/cli/cmd/internal/placeholders/placeholders.go index 94d47c8ca..0d93e9ff6 100644 --- a/clients/cli/cmd/internal/placeholders/placeholders.go +++ b/clients/cli/cmd/internal/placeholders/placeholders.go @@ -30,6 +30,7 @@ func ContainsTagPlaceholder(s string) bool { } func ToGlobbingPattern(s string) string { + s = replaceSlotsWithGlob(s) path := anyPlaceholderRegexp.ReplaceAllString(s, "*") baseName := filepath.Base(s) extension := filepath.Ext(s) @@ -113,3 +114,212 @@ func ResolveTranslationKeyPrefix(translationKeyPrefix optional.String, filePath return translationKeyPrefix, nil } + +const tagSeparator = "__" + +var ( + slotRegexp = regexp.MustCompile(`\{([A-Za-z_][A-Za-z0-9_]*)\}`) + patternTokenRegexp = regexp.MustCompile(`|||\{[A-Za-z_][A-Za-z0-9_]*\}|\*\*|\*`) +) + +// A slot is a named part of a file pattern, written {name}. On push the values +// of all slots of a file are joined with "__" into one tag; on pull the tag is +// split again and the values are filled into the same pattern. A slot that is a +// whole path segment ({module} in ./Modules/{module}/en.lproj/…) spans one or +// more folders; any other slot ({name} in {name}.strings) stays within a segment. +type slot struct { + name string + start, end int + spansPath bool +} + +func ContainsSlots(s string) bool { + return slotRegexp.MatchString(s) +} + +func slotsOf(pattern string) []slot { + slots := []slot{} + for _, match := range slotRegexp.FindAllStringSubmatchIndex(pattern, -1) { + start, end := match[0], match[1] + slots = append(slots, slot{ + name: pattern[match[2]:match[3]], + start: start, + end: end, + spansPath: (start == 0 || pattern[start-1] == '/') && (end == len(pattern) || pattern[end] == '/'), + }) + } + return slots +} + +// ValidateSlots checks that the slots of a pattern can be turned into a tag and back. +func ValidateSlots(pattern string) error { + slots := slotsOf(pattern) + if len(slots) == 0 { + return nil + } + if ContainsTagPlaceholder(pattern) { + return fmt.Errorf(" cannot be combined with {slot} placeholders in %q", pattern) + } + if strings.Contains(pattern, "**") { + return fmt.Errorf("** cannot be combined with {slot} placeholders in %q", pattern) + } + + names := map[string]bool{} + spanning := 0 + for i, current := range slots { + if names[current.name] { + return fmt.Errorf("{%s} can only occur once in a file pattern!", current.name) + } + names[current.name] = true + if current.spansPath { + spanning++ + } + if i > 0 && slots[i-1].end == current.start { + return fmt.Errorf("{%s}{%s} are ambiguous, separate slots by other characters", slots[i-1].name, current.name) + } + } + if spanning > 1 { + return fmt.Errorf("only one {slot} per pattern may be a whole folder segment (spanning folders): %q", pattern) + } + return nil +} + +// replaceSlots swaps every slot for "**" (spanning folders) or "*". +func replaceSlotsWithGlob(pattern string) string { + slots := slotsOf(pattern) + for i := len(slots) - 1; i >= 0; i-- { + replacement := "*" + if slots[i].spansPath { + replacement = "**" + } + pattern = pattern[:slots[i].start] + replacement + pattern[slots[i].end:] + } + return pattern +} + +// SlotMatch is the result of matching a path against a pattern with slots. +type SlotMatch struct { + // Placeholders holds locale_name, locale_code and tag values found in the path. + Placeholders map[string]string + // Slots holds the slot values in the order of the pattern. + Slots []string +} + +// Tag joins the slot values into a tag: Auth/Login + Widget becomes Auth__Login__Widget. +func (match SlotMatch) Tag() (string, error) { + parts := []string{} + for _, value := range match.Slots { + for _, folder := range strings.Split(value, "/") { + if strings.Contains(folder, tagSeparator) { + return "", fmt.Errorf("%q contains %q, which separates the parts of a tag", folder, tagSeparator) + } + parts = append(parts, folder) + } + } + return strings.Join(parts, tagSeparator), nil +} + +// MatchSlots matches path against pattern, which may contain slots, +// , , and the * and ** globs. +func MatchSlots(path, pattern string) (SlotMatch, error) { + path = filepath.ToSlash(filepath.Clean(path)) + pattern = filepath.ToSlash(filepath.Clean(pattern)) + slots := slotsOf(pattern) + + var expression strings.Builder + expression.WriteString("^") + last := 0 + for _, token := range patternTokenRegexp.FindAllStringIndex(pattern, -1) { + expression.WriteString(regexp.QuoteMeta(pattern[last:token[0]])) + text := pattern[token[0]:token[1]] + switch { + case text == "" || text == "" || text == "": + fmt.Fprintf(&expression, "(?P<%s>[^/]+)", text[1:len(text)-1]) + case text == "**": + expression.WriteString(".*") + case text == "*": + expression.WriteString("[^/]*") + default: + for _, current := range slots { + if current.start == token[0] { + if current.spansPath { + fmt.Fprintf(&expression, "(?P[^/]+(?:/[^/]+)*?)", current.name) + } else { + fmt.Fprintf(&expression, "(?P[^/]+?)", current.name) + } + } + } + } + last = token[1] + } + expression.WriteString(regexp.QuoteMeta(pattern[last:]) + "$") + + compiled, err := regexp.Compile(expression.String()) + if err != nil { + return SlotMatch{}, err + } + submatches := compiled.FindStringSubmatch(path) + if submatches == nil { + return SlotMatch{}, fmt.Errorf("string %q does not match pattern %q", path, pattern) + } + + match := SlotMatch{Placeholders: map[string]string{}} + values := map[string]string{} + for i, name := range compiled.SubexpNames() { + switch { + case strings.HasPrefix(name, "slot_"): + values[strings.TrimPrefix(name, "slot_")] = submatches[i] + case name != "": + match.Placeholders[name] = submatches[i] + } + } + for _, current := range slots { + match.Slots = append(match.Slots, values[current.name]) + } + return match, nil +} + +// SlotsFromTag splits a tag into slot values for pattern, the inverse of SlotMatch.Tag. +func SlotsFromTag(tag, pattern string) ([]string, error) { + pattern = filepath.ToSlash(filepath.Clean(pattern)) + slots := slotsOf(pattern) + parts := strings.Split(tag, tagSeparator) + for _, part := range parts { + if part == "" { + return nil, fmt.Errorf("tag %q does not fit pattern %q", tag, pattern) + } + } + + spanningIndex := -1 + for i, current := range slots { + if current.spansPath { + spanningIndex = i + } + } + if len(parts) < len(slots) || (spanningIndex < 0 && len(parts) != len(slots)) { + return nil, fmt.Errorf("tag %q does not fit pattern %q", tag, pattern) + } + + values := make([]string, len(slots)) + for i := range slots { + switch { + case spanningIndex < 0 || i < spanningIndex: + values[i] = parts[i] + case i == spanningIndex: + values[i] = strings.Join(parts[i:len(parts)-(len(slots)-1-i)], "/") + default: + values[i] = parts[len(parts)-(len(slots)-i)] + } + } + return values, nil +} + +// FillSlots replaces the slots of pattern by values, in order. +func FillSlots(pattern string, values []string) string { + index := 0 + return slotRegexp.ReplaceAllStringFunc(pattern, func(string) string { + value := values[index] + index++ + return value + }) +} diff --git a/clients/cli/cmd/internal/placeholders/placeholders_test.go b/clients/cli/cmd/internal/placeholders/placeholders_test.go index 0aae0bd58..e98eb86a4 100644 --- a/clients/cli/cmd/internal/placeholders/placeholders_test.go +++ b/clients/cli/cmd/internal/placeholders/placeholders_test.go @@ -1,6 +1,9 @@ package placeholders -import "testing" +import ( + "reflect" + "testing" +) func TestResolve(t *testing.T) { tests := map[struct { @@ -138,3 +141,118 @@ func areEqual(got, want map[string]string) bool { return true } + +func TestSlotsRoundTrip(t *testing.T) { + tests := []struct { + path, pattern, tag string + slots []string + }{ + { + "Modules/Auth/Passkey/Resources/Strings/en.lproj/Passkey.strings", + "./Modules/{module}/Resources/Strings/.lproj/{name}.strings", + "Auth__Passkey__Passkey", []string{"Auth/Passkey", "Passkey"}, + }, + { + "locales/something/a/en.lang/data.json", + "./locales/{path}/.lang/data.json", + "something__a", []string{"something/a"}, + }, + { + "locales/another/structure/de.lang/data.json", + "./locales/{path}/.lang/data.json", + "another__structure", []string{"another/structure"}, + }, + { + "app/values-fr/Widget_Item.xml", + "app/values-/{name}.xml", + "Widget_Item", []string{"Widget_Item"}, + }, + } + for _, test := range tests { + match, err := MatchSlots(test.path, test.pattern) + if err != nil { + t.Fatalf("%s: %v", test.path, err) + } + if !reflect.DeepEqual(match.Slots, test.slots) { + t.Errorf("%s: slots = %v, want %v", test.path, match.Slots, test.slots) + } + tag, err := match.Tag() + if err != nil || tag != test.tag { + t.Errorf("%s: tag = %q (%v), want %q", test.path, tag, err, test.tag) + } + values, err := SlotsFromTag(tag, test.pattern) + if err != nil || !reflect.DeepEqual(values, test.slots) { + t.Errorf("%s: SlotsFromTag = %v (%v), want %v", test.path, values, err, test.slots) + } + } +} + +func TestMatchSlotsLocalePlaceholders(t *testing.T) { + match, err := MatchSlots("Modules/Auth/Strings/de.lproj/X.strings", "./Modules/{module}/Strings/.lproj/{name}.strings") + if err != nil { + t.Fatal(err) + } + if match.Placeholders["locale_name"] != "de" { + t.Errorf("placeholders = %v", match.Placeholders) + } + if _, err := MatchSlots("Other/x.strings", "./Modules/{module}/{name}.strings"); err == nil { + t.Error("a path outside the pattern must not match") + } +} + +func TestSlotsFromTagRejectsNonFittingTags(t *testing.T) { + pattern := "./{module}//{name}.json" + for _, tag := range []string{"single", "", "a____b"} { + if _, err := SlotsFromTag(tag, pattern); err == nil { + t.Errorf("tag %q should not fit", tag) + } + } + if values, err := SlotsFromTag("a__b__c__d", pattern); err != nil || !reflect.DeepEqual(values, []string{"a/b/c", "d"}) { + t.Errorf("values = %v, %v", values, err) + } +} + +func TestTagRejectsSeparatorInValues(t *testing.T) { + match, err := MatchSlots("a__b/en.json", "{name}/.json") + if err != nil { + t.Fatal(err) + } + if _, err := match.Tag(); err == nil { + t.Error("a value containing __ cannot be turned back from a tag") + } +} + +func TestValidateSlots(t *testing.T) { + valid := []string{"./a/{x}/en.json", "./{x}//{y}.json", "./plain/.json"} + invalid := map[string]string{ + "./{x}/{x}.json": "duplicate", + "./{a}/{b}/x.json": "two spanning slots", + "./{a}{b}.json": "adjacent slots", + "./{a}/.json": "tag placeholder", + "./{a}/**/x.json": "double star", + } + for _, pattern := range valid { + if err := ValidateSlots(pattern); err != nil { + t.Errorf("%s: %v", pattern, err) + } + } + for pattern, reason := range invalid { + if err := ValidateSlots(pattern); err == nil { + t.Errorf("%s should be invalid (%s)", pattern, reason) + } + } +} + +func TestToGlobbingPatternWithSlots(t *testing.T) { + got := ToGlobbingPattern("./Modules/{module}/Strings/.lproj/{name}.strings") + if want := "./Modules/**/Strings/*.lproj/*.strings"; got != want { + t.Errorf("got %q, want %q", got, want) + } +} + +func TestFillSlots(t *testing.T) { + got := FillSlots("./Modules/{module}/{name}.strings", []string{"Auth/Passkey", "Passkey"}) + if want := "./Modules/Auth/Passkey/Passkey.strings"; got != want { + t.Errorf("got %q, want %q", got, want) + } +} diff --git a/clients/cli/cmd/internal/pull.go b/clients/cli/cmd/internal/pull.go index ab2a69c23..7b7d4aa5b 100644 --- a/clients/cli/cmd/internal/pull.go +++ b/clients/cli/cmd/internal/pull.go @@ -98,6 +98,10 @@ func (cmd *PullCommand) Run(config *phrase.Config) error { return fmt.Errorf("Could not find any locales for project %q", target.ProjectID) } target.RemoteLocales = val + + if err := target.expandWildcardTags(client); err != nil { + return err + } } var cache *DownloadCache @@ -568,7 +572,7 @@ func (target *Target) LocaleFiles() (LocaleFiles, error) { func (target *Target) createLocaleFiles(remoteLocale *phrase.Locale) (LocaleFiles, error) { files := []*LocaleFile{} tags := target.GetTags() - if len(tags) > 0 && placeholders.ContainsTagPlaceholder(target.File) { + if len(tags) > 0 && (placeholders.ContainsTagPlaceholder(target.File) || placeholders.ContainsSlots(target.File)) { for _, tag := range tags { localeFile, err := createLocaleFile(target, remoteLocale, tag) if err != nil { diff --git a/clients/cli/cmd/internal/pull_target.go b/clients/cli/cmd/internal/pull_target.go index 65ba96e7b..f0faf02a9 100644 --- a/clients/cli/cmd/internal/pull_target.go +++ b/clients/cli/cmd/internal/pull_target.go @@ -4,8 +4,10 @@ import ( "bytes" "fmt" "path/filepath" + "regexp" "strings" + "github.com/antihax/optional" "github.com/phrase/phrase-cli/cmd/internal/paths" "github.com/phrase/phrase-cli/cmd/internal/placeholders" "github.com/phrase/phrase-cli/cmd/internal/shared" @@ -50,6 +52,7 @@ func (target *Target) CheckPreconditions() error { containsDuplicatePlaceholders, containsAmbiguousLocaleInformation, containsInvalidTagInformation, + containsInvalidSlots, } for _, precondition := range preconditions { @@ -104,6 +107,10 @@ func containsInvalidTagInformation(target *Target) error { return nil } +func containsInvalidSlots(target *Target) error { + return placeholders.ValidateSlots(target.File) +} + func (target *Target) localeForRemote() (*phrase.Locale, error) { for _, locale := range target.RemoteLocales { if locale.Id == target.GetLocaleID() || locale.Name == target.GetLocaleID() { @@ -114,7 +121,16 @@ func (target *Target) localeForRemote() (*phrase.Locale, error) { } func (target *Target) ReplacePlaceholders(localeFile *LocaleFile) (string, error) { - absPath, err := filepath.Abs(target.File) + file := target.File + if placeholders.ContainsSlots(file) { + values, err := placeholders.SlotsFromTag(localeFile.Tag, file) + if err != nil { + return "", err + } + file = placeholders.FillSlots(file, values) + } + + absPath, err := filepath.Abs(file) if err != nil { return "", err } @@ -208,3 +224,66 @@ func TargetsFromConfig(config phrase.Config) (Targets, error) { return validTargets, nil } + +// expandWildcardTags replaces tag entries containing "*" by the matching tags of the +// project: tags: "*" is all tags, tags: "Auth__*" only those starting with Auth__. +// With {slot} placeholders in the file pattern, omitting tags means all tags that +// fit the slots. Both need a or {slot} placeholder in the file pattern to know +// where to write each tag. With slots, tags that do not fit the slot count are left out. +func (target *Target) expandWildcardTags(client *phrase.APIClient) error { + hasSlots := placeholders.ContainsSlots(target.File) + entries := target.GetTags() + switch { + case hasSlots && len(entries) == 0: + entries = []string{"*"} + case target.Params != nil && strings.Contains(target.Params.Tags.Value(), "*"): + default: + return nil + } + if !placeholders.ContainsTagPlaceholder(target.File) && !hasSlots { + return fmt.Errorf("tags with \"*\" require a or {slot} placeholder in the file pattern %q", target.File) + } + + names, err := RemoteTagNames(client, target.ProjectID, target.GetBranch()) + if err != nil { + return err + } + + expanded := []string{} + seen := map[string]bool{} + add := func(name string) { + if !seen[name] { + seen[name] = true + expanded = append(expanded, name) + } + } + for _, entry := range entries { + if !strings.Contains(entry, "*") { + add(entry) + continue + } + glob := regexp.MustCompile("^" + strings.ReplaceAll(regexp.QuoteMeta(entry), `\*`, ".*") + "$") + for _, name := range names { + if glob.MatchString(name) && target.tagFitsPattern(name) { + add(name) + } + } + } + if len(expanded) == 0 { + return fmt.Errorf("could not find any tags in project %q that match %q and fit the file pattern %q", target.ProjectID, strings.Join(entries, ","), target.File) + } + + if target.Params == nil { + target.Params = &PullParams{} + } + target.Params.Tags = optional.NewString(strings.Join(expanded, ",")) + return nil +} + +func (target *Target) tagFitsPattern(tag string) bool { + if !placeholders.ContainsSlots(target.File) { + return true + } + _, err := placeholders.SlotsFromTag(tag, target.File) + return err == nil +} diff --git a/clients/cli/cmd/internal/pull_target_wildcard_test.go b/clients/cli/cmd/internal/pull_target_wildcard_test.go new file mode 100644 index 000000000..e3d3676da --- /dev/null +++ b/clients/cli/cmd/internal/pull_target_wildcard_test.go @@ -0,0 +1,149 @@ +package internal + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + + "github.com/antihax/optional" + "github.com/phrase/phrase-go/v4" +) + +func TestExpandWildcardTags(t *testing.T) { + const totalTags, perPage = 305, 100 + var queries []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + queries = append(queries, r.URL.RawQuery) + w.Header().Set("Content-Type", "application/json") + page, _ := strconv.Atoi(r.URL.Query().Get("page")) + first, last := (page-1)*perPage, min(page*perPage, totalTags) + if last < totalTags { + w.Header().Set("Link", fmt.Sprintf("; rel=next", r.Host, page+1)) + } + items := []string{} + for i := first; i < last; i++ { + items = append(items, fmt.Sprintf(`{"name":"Tag__%d"}`, i)) + } + fmt.Fprintf(w, "[%s]", strings.Join(items, ",")) + })) + defer srv.Close() + + previousAuth := Auth + Auth = context.Background() + t.Cleanup(func() { Auth = previousAuth }) + + cfg := phrase.NewConfiguration() + cfg.BasePath = srv.URL + client := phrase.NewAPIClient(cfg) + + newTarget := func(file, tags string) *Target { + params := &PullParams{} + params.Tags = optional.NewString(tags) + return &Target{File: file, ProjectID: "proj1", Params: params} + } + + target := newTarget("./{group}/{name}.json", "*") + if err := target.expandWildcardTags(client); err != nil { + t.Fatal(err) + } + names := strings.Split(target.Params.Tags.Value(), ",") + if len(names) != totalTags || names[0] != "Tag__0" || names[totalTags-1] != "Tag__304" { + t.Errorf("got %d tags (%v ... %v), want %d", len(names), names[0], names[len(names)-1], totalTags) + } + if len(queries) != 4 { + t.Errorf("requests = %d, want 4 pages", len(queries)) + } + for _, query := range queries { + if !strings.Contains(query, "exclude_system_tags=true") || !strings.Contains(query, "per_page=100") { + t.Errorf("unexpected query %q", query) + } + } + + filtered := newTarget("./{group}/{name}.json", "Tag__30*") + if err := filtered.expandWildcardTags(client); err != nil { + t.Fatal(err) + } + if got := filtered.Params.Tags.Value(); got != "Tag__30,Tag__300,Tag__301,Tag__302,Tag__303,Tag__304" { + t.Errorf("filtered tags = %q", got) + } + + omitted := &Target{File: "./{group}/{name}.json", ProjectID: "proj1"} + if err := omitted.expandWildcardTags(client); err != nil { + t.Fatal(err) + } + if got := len(strings.Split(omitted.Params.Tags.Value(), ",")); got != totalTags { + t.Errorf("omitted tags with slots: got %d tags, want all %d", got, totalTags) + } + + noSlots := &Target{File: "./.json", ProjectID: "proj1"} + if err := noSlots.expandWildcardTags(client); err != nil || noSlots.Params != nil { + t.Errorf("omitted tags without slots must stay untouched, got %v, %v", noSlots.Params, err) + } + if err := containsInvalidTagInformation(noSlots); err == nil { + t.Error(" without tags must still be rejected") + } + if err := containsInvalidTagInformation(&Target{File: "./{group}/{name}.json"}); err != nil { + t.Errorf("slots without tags must be accepted: %v", err) + } + + tagsWithoutSlotFit := newTarget("./{a}/{b}//{c}.json", "*") + if err := tagsWithoutSlotFit.expandWildcardTags(client); err == nil { + t.Error("tags with two parts cannot fill three slots, expected an error") + } + + explicit := newTarget("./{group}/{name}.json", "A__B") + if err := explicit.expandWildcardTags(client); err != nil || explicit.Params.Tags.Value() != "A__B" { + t.Errorf("explicit tags must stay untouched, got %q, %v", explicit.Params.Tags.Value(), err) + } + + if err := newTarget("./en.json", "*").expandWildcardTags(client); err == nil { + t.Error("expected error for * without placeholder") + } +} + +func TestLocaleFilesFromSlots(t *testing.T) { + params := &PullParams{} + params.Tags = optional.NewString("Auth__Passkey__Passkey,Billing__Invoice") + target := &Target{ + File: "./Modules/{module}/Strings/.lproj/{name}.strings", + ProjectID: "proj1", + Params: params, + RemoteLocales: []*phrase.Locale{{Id: "1", Name: "en", Code: "en"}, {Id: "2", Name: "de", Code: "de"}}, + } + + if err := target.CheckPreconditions(); err != nil { + t.Fatal(err) + } + files, err := target.LocaleFiles() + if err != nil { + t.Fatal(err) + } + + want := []string{ + "Modules/Auth/Passkey/Strings/en.lproj/Passkey.strings", + "Modules/Billing/Strings/en.lproj/Invoice.strings", + "Modules/Auth/Passkey/Strings/de.lproj/Passkey.strings", + "Modules/Billing/Strings/de.lproj/Invoice.strings", + } + if len(files) != len(want) { + t.Fatalf("got %d files, want %d", len(files), len(want)) + } + for i, file := range files { + if file.RelPath() != want[i] { + t.Errorf("path = %q, want %q", file.RelPath(), want[i]) + } + } + if files[0].Tag != "Auth__Passkey__Passkey" || files[1].Tag != "Billing__Invoice" { + t.Errorf("tags used as download filter: %q, %q", files[0].Tag, files[1].Tag) + } + + badTag := &Target{File: target.File, ProjectID: "proj1", Params: &PullParams{}, RemoteLocales: target.RemoteLocales} + badTag.Params.Tags = optional.NewString("only_one_part") + if _, err := badTag.LocaleFiles(); err == nil { + t.Error("a tag that does not fit the slots must be an error") + } +} diff --git a/clients/cli/cmd/internal/push.go b/clients/cli/cmd/internal/push.go index 9828be444..9bbbfa343 100644 --- a/clients/cli/cmd/internal/push.go +++ b/clients/cli/cmd/internal/push.go @@ -467,7 +467,22 @@ func (source *Source) LocaleFiles() (LocaleFiles, error) { } localeFile := new(LocaleFile) - localeFile.fillFromPath(path, sourcePattern) + if placeholders.ContainsSlots(sourcePattern) { + match, err := placeholders.MatchSlots(path, sourcePattern) + if err != nil { + // e.g. ** matched no folder at all + continue + } + tag, err := match.Tag() + if err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } + localeFile.Tag = tag + localeFile.Name = match.Placeholders["locale_name"] + localeFile.Code = match.Placeholders["locale_code"] + } else { + localeFile.fillFromPath(path, sourcePattern) + } // Apply reverse locale mapping (local → remote) if configured localeFile.Name = ApplyLocaleMapping(source.LocaleMapping, localeFile.Name) diff --git a/clients/cli/cmd/internal/push_slots_test.go b/clients/cli/cmd/internal/push_slots_test.go new file mode 100644 index 000000000..804e35b5a --- /dev/null +++ b/clients/cli/cmd/internal/push_slots_test.go @@ -0,0 +1,56 @@ +package internal + +import ( + "os" + "path/filepath" + "sort" + "testing" + + "github.com/phrase/phrase-go/v4" +) + +func TestSourceLocaleFilesFromSlots(t *testing.T) { + dir := t.TempDir() + for _, relative := range []string{ + "Modules/Auth/Passkey/Strings/en.lproj/Passkey.strings", + "Modules/Auth/Passkey/Strings/de.lproj/Passkey.strings", + "Modules/Billing/Strings/en.lproj/Invoice.strings", + } { + path := filepath.Join(dir, relative) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(`"a" = "b";`), 0o600); err != nil { + t.Fatal(err) + } + } + + source := &Source{ + File: filepath.Join(dir, "Modules/{module}/Strings/.lproj/{name}.strings"), + Params: &UploadParams{}, + Format: &phrase.Format{}, + } + if err := source.CheckPreconditions(); err != nil { + t.Fatal(err) + } + files, err := source.LocaleFiles() + if err != nil { + t.Fatal(err) + } + + got := []string{} + for _, file := range files { + got = append(got, file.Name+" "+file.Tag) + } + sort.Strings(got) + want := []string{"de Auth__Passkey__Passkey", "en Auth__Passkey__Passkey", "en Billing__Invoice"} + if len(got) != len(want) { + t.Fatalf("got %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Errorf("got %v, want %v", got, want) + break + } + } +} diff --git a/clients/cli/cmd/internal/push_source.go b/clients/cli/cmd/internal/push_source.go index ff08c2656..586fb8404 100644 --- a/clients/cli/cmd/internal/push_source.go +++ b/clients/cli/cmd/internal/push_source.go @@ -150,6 +150,10 @@ func (source *Source) CheckPreconditions() error { return err } + if err := placeholders.ValidateSlots(source.File); err != nil { + return err + } + duplicatedPlaceholders := []string{} for _, name := range []string{"", "", ""} { if strings.Count(source.File, name) > 1 { diff --git a/clients/cli/cmd/internal/shared.go b/clients/cli/cmd/internal/shared.go index 40742ddef..208c860b8 100644 --- a/clients/cli/cmd/internal/shared.go +++ b/clients/cli/cmd/internal/shared.go @@ -266,3 +266,30 @@ func ApplyLocaleMapping(localeMapping map[string]string, remoteName string) stri } return remoteName } + +// RemoteTagNames returns the names of all non-system tags of a project branch. +func RemoteTagNames(client *phrase.APIClient, projectID string, branch string) ([]string, error) { + opts := phrase.TagsListOpts{ + Page: optional.NewInt32(1), + PerPage: optional.NewInt32(100), + ExcludeSystemTags: optional.NewBool(true), + } + if branch != "" { + opts.Branch = optional.NewString(branch) + } + + names := []string{} + for { + tags, response, err := client.TagsApi.TagsList(Auth, projectID, &opts) + if err != nil { + return nil, err + } + for _, tag := range tags { + names = append(names, tag.Name) + } + if response.NextPage <= 0 { + return names, nil + } + opts.Page = optional.NewInt32(int32(response.NextPage)) + } +}