Skip to content
210 changes: 210 additions & 0 deletions clients/cli/cmd/internal/placeholders/placeholders.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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(`<locale_name>|<locale_code>|<tag>|\{[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("<tag> 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,
// <locale_name>, <locale_code>, <tag> 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 == "<locale_name>" || text == "<locale_code>" || text == "<tag>":
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<slot_%s>[^/]+(?:/[^/]+)*?)", current.name)
} else {
fmt.Fprintf(&expression, "(?P<slot_%s>[^/]+?)", 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
})
}
120 changes: 119 additions & 1 deletion clients/cli/cmd/internal/placeholders/placeholders_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package placeholders

import "testing"
import (
"reflect"
"testing"
)

func TestResolve(t *testing.T) {
tests := map[struct {
Expand Down Expand Up @@ -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/<locale_name>.lproj/{name}.strings",
"Auth__Passkey__Passkey", []string{"Auth/Passkey", "Passkey"},
},
{
"locales/something/a/en.lang/data.json",
"./locales/{path}/<locale_name>.lang/data.json",
"something__a", []string{"something/a"},
},
{
"locales/another/structure/de.lang/data.json",
"./locales/{path}/<locale_name>.lang/data.json",
"another__structure", []string{"another/structure"},
},
{
"app/values-fr/Widget_Item.xml",
"app/values-<locale_code>/{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/<locale_name>.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}/<locale_name>/{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}/<locale_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}/<locale_name>/{y}.json", "./plain/<locale_name>.json"}
invalid := map[string]string{
"./{x}/{x}.json": "duplicate",
"./{a}/{b}/x.json": "two spanning slots",
"./{a}{b}.json": "adjacent slots",
"./{a}/<tag>.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/<locale_name>.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)
}
}
6 changes: 5 additions & 1 deletion clients/cli/cmd/internal/pull.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading