diff --git a/testfile/testfile.go b/testfile/testfile.go index ff74b21..31141c9 100644 --- a/testfile/testfile.go +++ b/testfile/testfile.go @@ -9,6 +9,18 @@ import ( "testing" ) +// Ext return path with its current extension stripped and ext added. +// It treats ext with and without a leading dot the same for simplicity of operation. +// If ext is "", path is returned with its current extension stripped off. +func Ext(path, ext string) string { + currExt := filepath.Ext(path) + path = strings.TrimSuffix(path, currExt) + if !strings.HasPrefix(ext, ".") && ext != "" { + ext = "." + ext + } + return path + ext +} + // Read returns the contents of file at path. // It calls t.Fatalf if there is an error. func Read(t testing.TB, path string) string { diff --git a/testfile/testfile_example_test.go b/testfile/testfile_example_test.go index df294c3..9c03aed 100644 --- a/testfile/testfile_example_test.go +++ b/testfile/testfile_example_test.go @@ -1,6 +1,7 @@ package testfile_test import ( + "fmt" "strings" "testing" @@ -64,3 +65,21 @@ func ExampleRun() { } // Output: } + +func ExampleExt() { + for _, path := range []string{ + "foo.txt", + "foo.bar/spam", + } { + fmt.Println(testfile.Ext(path, "")) + fmt.Println(testfile.Ext(path, ".json")) + fmt.Println(testfile.Ext(path, "gob")) + } + // Output: + // foo + // foo.json + // foo.gob + // foo.bar/spam + // foo.bar/spam.json + // foo.bar/spam.gob +}