File tree Expand file tree Collapse file tree 2 files changed +40
-0
lines changed
Expand file tree Collapse file tree 2 files changed +40
-0
lines changed Original file line number Diff line number Diff line change 77 "io/fs"
88 "os"
99 "path/filepath"
10+ "runtime"
1011)
1112
1213type 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+
1835func (p Path ) String () string {
1936 return string (p )
2037}
Original file line number Diff line number Diff line change @@ -2,6 +2,7 @@ package ppath
22
33import (
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+ }
You can’t perform that action at this time.
0 commit comments