Skip to content

Commit

Permalink
Improve ParsePaths behavior in errors, and add a usage comment
Browse files Browse the repository at this point in the history
  • Loading branch information
sgmiller committed Jan 21, 2025
1 parent 226c32f commit 3fa335c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
21 changes: 17 additions & 4 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,12 +156,25 @@ func WithoutHMAC() Option {
}
}

// ParsePaths is a helper function to take each string pointer argument and call parseutil.ParsePath,
// replacing the contents of the target string with the result if no error occurs. The function exits
// early if it encounters an error. In that case no passed fields will have been modified.
//
// If any passed pointer is nil it will be ignored.
func ParsePaths(fields ...*string) error {
newVals := make([]string, len(fields))
for i := 0; i < len(fields); i++ {
if newVal, err := parseutil.ParsePath(*fields[i], parseutil.WithNoTrimSpaces(true), parseutil.WithErrorOnMissingEnv(true)); err != nil && !errors.Is(err, parseutil.ErrNotAUrl) {
return err
} else {
*fields[i] = newVal
if fields[i] != nil {
if newVal, err := parseutil.ParsePath(*fields[i], parseutil.WithNoTrimSpaces(true), parseutil.WithErrorOnMissingEnv(true)); err != nil && !errors.Is(err, parseutil.ErrNotAUrl) {
return err
} else {
newVals[i] = newVal
}
}
}
for i := 0; i < len(fields); i++ {
if fields[i] != nil {
*fields[i] = newVals[i]
}
}
return nil
Expand Down
18 changes: 17 additions & 1 deletion options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,26 @@ func TestParsePaths(t *testing.T) {
t.Fatalf("expected TopSecret, got %s", test.optionB)
}

// Test nil handling
test = options{
optionA: "file://test-fixtures/missing.txt",
optionA: "file://test-fixtures/secret.txt",
}
if err := ParsePaths(nil, &test.optionA, nil); err != nil {
t.Fatal(err)
}
if test.optionA != "Top Secret" {
t.Fatalf("expected TopSecret, got %s", test.optionB)
}

// Test errors and error atomicity
test = options{
optionA: "file://test-fixtures/secret.txt",
optionB: "file://test-fixtures/missing.txt",
}
if err := ParsePaths(&test.optionA, &test.optionB); err == nil {
t.Fatal("expected error but didn't get one")
}
if test.optionA != "file://test-fixtures/secret.txt" {
t.Fatalf("optionA was overwritten despite encountering an error")
}
}

0 comments on commit 3fa335c

Please sign in to comment.