diff options
author | Noah Campbell <noahcampbell@gmail.com> | 2013-09-01 20:24:03 +0400 |
---|---|---|
committer | Noah Campbell <noahcampbell@gmail.com> | 2013-09-04 07:00:22 +0400 |
commit | 7919603fb58bbbec2cdef2e46ec2e3c3571c46c1 (patch) | |
tree | 1caa75f5ad694c606a0006e5375bb86b64089baa /target | |
parent | c6ad532b940fa07e5f32a3d1427348f5c4aaf12b (diff) |
Add Translate to target
Translate handles Ugly Urls.
Diffstat (limited to 'target')
-rw-r--r-- | target/file.go | 44 | ||||
-rw-r--r-- | target/file_test.go | 51 |
2 files changed, 95 insertions, 0 deletions
diff --git a/target/file.go b/target/file.go index a80d73dbe..ac7ab105c 100644 --- a/target/file.go +++ b/target/file.go @@ -1,9 +1,53 @@ package target import ( + "fmt" "io" + "path" ) type Publisher interface { Publish(string, io.Reader) error } + +type Translator interface { + Translate(string) (string, error) +} + +type Filesystem struct { + UglyUrls bool + DefaultExtension string +} + +func (fs *Filesystem) Translate(src string) (dest string, err error) { + if fs.UglyUrls { + return src, nil + } + + dir, file := path.Split(src) + ext := fs.extension(path.Ext(file)) + name := filename(file) + + return path.Join(dir, name, fmt.Sprintf("index%s", ext)), nil +} + +func (fs *Filesystem) extension(ext string) string { + if ext != "" { + return ext + } + + if fs.DefaultExtension != "" { + return fs.DefaultExtension + } + + return ".html" +} + +func filename(f string) string { + ext := path.Ext(f) + if ext == "" { + return f + } + + return f[:len(f)-len(ext)] +} diff --git a/target/file_test.go b/target/file_test.go new file mode 100644 index 000000000..1c31f5c6a --- /dev/null +++ b/target/file_test.go @@ -0,0 +1,51 @@ +package target + +import ( + "testing" +) + +func TestFileTranslator(t *testing.T) { + tests := []struct { + content string + expected string + }{ + {"foo", "foo/index.html"}, + {"foo.html", "foo/index.html"}, + {"foo.xhtml", "foo/index.xhtml"}, + {"section/foo", "section/foo/index.html"}, + {"section/foo.html", "section/foo/index.html"}, + {"section/foo.rss", "section/foo/index.rss"}, + } + + for _, test := range tests { + f := new(Filesystem) + dest, err := f.Translate(test.content) + if err != nil { + t.Fatalf("Translate returned and unexpected err: %s", err) + } + + if dest != test.expected { + t.Errorf("Tranlate expected return: %s, got: %s", test.expected, dest) + } + } +} + +func TestTranslateUglyUrls(t *testing.T) { + f := &Filesystem{UglyUrls: true} + dest, err := f.Translate("foo.html") + if err != nil { + t.Fatalf("Translate returned an unexpected err: %s", err) + } + + if dest != "foo.html" { + t.Errorf("Translate expected return: %s, got: %s", "foo.html", dest) + } +} + +func TestTranslateDefaultExtension(t *testing.T) { + f := &Filesystem{DefaultExtension: ".foobar"} + dest, _ := f.Translate("baz") + if dest != "baz/index.foobar" { + t.Errorf("Translate expected return: %s, got %s", "baz/index.foobar", dest) + } +} |