Skip to content

Commit dce9019

Browse files
committed
Add SourceFile and WD methods to Path struct for file path retrieval
1 parent 5a9ec96 commit dce9019

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

path.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"io/fs"
88
"os"
99
"path/filepath"
10+
"runtime"
1011
)
1112

1213
type Path string
@@ -15,6 +16,22 @@ func New(v ...string) Path {
1516
return Path(filepath.Join(v...))
1617
}
1718

19+
// ThisFile retrieves the path of the source file from which it was invoked.
20+
func ThisFile() Path {
21+
_, f, _, _ := runtime.Caller(1)
22+
return New(f)
23+
}
24+
25+
// WD returns the path of the application’s current working directory.
26+
func WD() Path {
27+
v := "."
28+
if wd, err := os.Getwd(); err == nil {
29+
v = wd
30+
}
31+
32+
return New(v)
33+
}
34+
1835
func (p Path) String() string {
1936
return string(p)
2037
}

path_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package ppath
22

33
import (
44
"io/fs"
5+
"log"
56
"os"
67
"path/filepath"
78
"runtime"
@@ -637,3 +638,25 @@ func TestAppendf(t *testing.T) {
637638
t.Errorf("expected %s, got %s", expected, result.String())
638639
}
639640
}
641+
642+
func TestSourceFile(t *testing.T) {
643+
// Test that SourceFile returns the correct path of the current file
644+
expected := WD().Join("path_test.go").String()
645+
log.Println(ThisFile())
646+
sourceFile := ThisFile().String()
647+
if sourceFile != expected {
648+
t.Errorf("expected %s, got %s", expected, sourceFile)
649+
}
650+
}
651+
652+
func TestWD(t *testing.T) {
653+
wd, err := os.Getwd()
654+
if err != nil {
655+
t.Fatalf("os.Getwd: %v", err)
656+
}
657+
658+
p := WD()
659+
if p.String() != wd {
660+
t.Errorf("expected %s, got %s", wd, p.String())
661+
}
662+
}

0 commit comments

Comments
 (0)