Reputation: 75535
I am writing a utility function for my unit tests which is used by unit tests in multiple packages. This utility function must read a particular file (always the same file). Here are three solutions which do not work, to explain what I am looking for and why.
Hardcode the absolute path. This fails because another user who is trying to test the project might have a different prefix on the absolute path.
Hardcode a relative path from the path of the file which defines the utility function. This fails because packages which import and use this function are not necessarily at the same level of the file hierarchy as the file that defines the utility function, and relative paths are interpreted relative to the importer, not the imported.
Pass in the relative path to the file from every caller relative to the caller's package. This actually works but seems to be very verbose because now every caller must be changed to pass one file.
I see a fourth solution, whereby I can hardcode a path in the utility function which is relative to the root directory of the top-level package. However, I have not been able to find a way to get the root directory in code, although I suspect there is one because imports can be resolved from the root.
Thus, how might I get the sought-after root directory?
I've looked over various Go documents but have so far failed to find a solution. I have also seen this question but the solution there is equivalent to #3 above.
Upvotes: 80
Views: 69584
Reputation: 23
I was struggling with the same issue and finally made this package that solves our issues.
See:
go get github.com/flashlabs/rootpath
Configure the test working directory to always be the project root directory. It doesn't matter whether you run tests from the IDE or from the CLI, the context of their execution will always be the same.
Just import the package with a blank identifier (_
) and the working directory of your tests will be the root directory of your project.
package yours
import (
_ "github.com/flashlabs/rootpath"
)
Hope this will make your life easier!
Cheers!
Upvotes: 0
Reputation: 29483
Here is an example of a test helper to get the root path of your module (project) without having to set it as global variable, or using relative paths like ..
by utilize go list
in case you need to generate the path at runtime or if you don't want to be bound by in which file the variable is defined.
func getRelativeRootPath(tb testing.TB) string {
tb.Helper()
importPath := runGoList(tb, "list", "-f", "{{.ImportPath}}")
modulePath := runGoList(tb, "list", "-m", "-f", "{{.Path}}")
pkgPath := runGoList(tb, "list", "-f", "{{.Dir}}")
relativePath, err := filepath.Rel(importPath, modulePath)
if err != nil {
tb.Fatal(err)
}
return filepath.Join(pkgPath, relativePath)
}
func runGoList(tb testing.TB, arg ...string) string {
tb.Helper()
cmd := exec.Command("go", arg...)
output, err := cmd.CombinedOutput()
if err != nil {
tb.Fatalf("runGoList: %v: %s", err, string(output))
}
return strings.TrimSpace(string(output))
}
This will work independent on running go test
in the package where the test makes use of the helper or if go test
is run at the root level.
The import path is the path of the referenced package, the module path contains only the path for the module itself which we use here as a reference to figure out how deep another package is nested, allowing us to compute a relative path, for example .
or ..
or ../..
, and so on.
Finally we also use runtime.Caller(0)
to get the path of the current file but can now at runtime compute the root path of the project.
Upvotes: 1
Reputation: 2174
Go directories:
// from Executable Directory
ex, _ := os.Executable()
fmt.Println("Executable DIR:", filepath.Dir(ex))
// Current working directory
dir, _ := os.Getwd()
fmt.Println("CWD:", dir)
// Relative on runtime DIR:
_, b, _, _ := runtime.Caller(0)
d1 := path.Join(path.Dir(b))
fmt.Println("Relative", d1)
Upvotes: 17
Reputation: 766
Returns the root of the application:
import (
"path"
"path/filepath"
"runtime"
)
func RootDir() string {
_, b, _, _ := runtime.Caller(0)
d := path.Join(path.Dir(b))
return filepath.Dir(d)
}
Upvotes: 21
Reputation: 57184
Building on the answer by Oleksiy you can create a sub-package in your project called ./internal/projectpath/projectpath.go
and paste in the following:
package projectpath
import (
"path/filepath"
"runtime"
)
var (
_, b, _, _ = runtime.Caller(0)
// Root folder of this project
Root = filepath.Join(filepath.Dir(b), "../..")
)
Then you can use projectpath.Root
in any other package to have the root folder of your project.
Upvotes: 49
Reputation: 1384
You can also use my method without C:
package mypackage
import (
"path/filepath"
"runtime"
"fmt"
)
var (
_, b, _, _ = runtime.Caller(0)
basepath = filepath.Dir(b)
)
func PrintMyPath() {
fmt.Println(basepath)
}
https://play.golang.org/p/ifVRIq7Tx0
Upvotes: 99
Reputation: 306
Yes, Finding package path is possible:
pathfind.go:
package main
/*
const char* GetMyPathFILE = __FILE__;
*/
import "C"
import "path/filepath"
var basepath = ""
//GetMyPath Returns the absolute directory of this(pathfind.go) file
func GetMyPath() string {
if basepath == "" {
g := C.GoString(C.GetMyPathFILE)
basepath = filepath.Dir(g)
}
return basepath
}
All you have to do is copy this file to your project. Keep in mind this comes up with the path for the file, not the caller so you have to copy the function/file to every project you need the function in. Additionally if you put this in a file with other code be sure to respect CGO
's import rules.
Upvotes: -3