aboutsummaryrefslogtreecommitdiff
path: root/pkg/u
diff options
context:
space:
mode:
authorGabriel A. Giovanini <mail@gabrielgio.me>2024-07-07 20:28:42 +0200
committerGabriel A. Giovanini <mail@gabrielgio.me>2024-07-07 20:29:43 +0200
commit78f3b007bf42846feff8342b64223252c3a74e2a (patch)
tree30c63c44a29ce84ce29052458c9ba901d16740e2 /pkg/u
parent8dff852753a1c4a708fd87e3cbb0f4844803aa95 (diff)
downloadcerrado-0.0.11.tar.gz
cerrado-0.0.11.tar.bz2
cerrado-0.0.11.zip
ref: Simplify path builder codev0.0.11
Diffstat (limited to 'pkg/u')
-rw-r--r--pkg/u/file.go44
-rw-r--r--pkg/u/file_test.go59
2 files changed, 92 insertions, 11 deletions
diff --git a/pkg/u/file.go b/pkg/u/file.go
index fafe0fb..5010b3e 100644
--- a/pkg/u/file.go
+++ b/pkg/u/file.go
@@ -4,7 +4,7 @@ import (
"errors"
"log/slog"
"os"
- "path/filepath"
+ "strings"
)
func FileExist(filename string) bool {
@@ -22,21 +22,43 @@ func FileExist(filename string) bool {
}
// This is just a slin wraper to make easier to compose path in the template
-type Pathing string
+type Pathing struct {
+ sb strings.Builder
+}
-func Root() Pathing {
- return "/"
+func NewPathing() *Pathing {
+ return &Pathing{}
}
-func (s Pathing) AddPath(p string) Pathing {
- return Pathing(filepath.Join(string(s), p))
+func (s *Pathing) AddPath(p string) *Pathing {
+ if len(p) == 0 {
+ return s
+ }
+
+ // if it has trailing / remove it
+ if p[len(p)-1] == '/' {
+ p = p[:len(p)-1]
+ return s.AddPath(p)
+ }
+
+ // if it does not have it so add
+ if p[0] == '/' {
+ s.sb.WriteString(p)
+ } else {
+ s.sb.WriteString("/" + p)
+ }
+
+ return s
}
-func (s Pathing) AddPaths(p []string) Pathing {
- f := filepath.Join(p...)
- return Pathing(filepath.Join(string(s), f))
+func (s *Pathing) AddPaths(p []string) *Pathing {
+ for _, v := range p {
+ s.AddPath(v)
+ }
+
+ return s
}
-func (s Pathing) Done() string {
- return string(s)
+func (s *Pathing) Done() string {
+ return s.sb.String()
}
diff --git a/pkg/u/file_test.go b/pkg/u/file_test.go
new file mode 100644
index 0000000..b7d6975
--- /dev/null
+++ b/pkg/u/file_test.go
@@ -0,0 +1,59 @@
+// go:build unit
+package u
+
+import "testing"
+
+func TestPathing(t *testing.T) {
+ testCases := []struct {
+ name string
+ in []any
+ out string
+ }{
+ {
+ name: "root",
+ in: []any{},
+ out: "",
+ },
+ {
+ name: "empty",
+ in: []any{
+ "/",
+ []string{"/", "/"},
+ "/",
+ []string{"/"},
+ },
+ out: "",
+ },
+ {
+ name: "empty",
+ in: []any{
+ "usr",
+ []string{"/share/", "lib"},
+ "/demo",
+ []string{"/out//"},
+ },
+ out: "/usr/share/lib/demo/out",
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ r := NewPathing()
+
+ for _, v := range tc.in {
+ switch s := v.(type) {
+ case string:
+ r = r.AddPath(s)
+ case []string:
+ r = r.AddPaths(s)
+ }
+ }
+
+ path := r.Done()
+ if tc.out != path {
+ t.Errorf("String mismatch: wanted %s got %s", tc.out, path)
+ }
+
+ })
+ }
+}