runpath package provides func to get the execution location of Go code, including the absolute path of the source file.
Install the package with:
go get github.com/yyle88/runpathrunpath is a runtime path utils package that obtains the absolute path of Go code execution locations.
Core Capabilities:
- Runtime Path Retrieval - Get code execution location's absolute path via
runtime.Caller() - Parent DIR Operations - Parent DIR related operations through
PARENT/DIRnamespace - Testing Support -
runtestpathsub-package specifically supports getting source file paths from test files - Path Extension Handling - Support for changing and removing file extensions
runpath Advantages:
Unlike the built-in filepath.Abs(".") which doesn't always provide the expected result in certain situations, runpath uses Go's runtime package to offer precise location tracking, making it especially useful when the exact execution path is needed.
Path Operations:
Path(),Current(),CurrentPath()- Get current source file absolute pathName(),CurrentName()- Get current source file nameSkip(skip int)- Skip specified levels to get caller pathGetPathChangeExtension(),GetRex()- Change file extensionGetPathRemoveExtension(),GetNox()- Remove .go extension
DIR Operations:
PARENT.Path(),DIR.Path()- Get parent DIR pathPARENT.Join(),DIR.Join()- Join pathsPARENT.Up(),DIR.UpTo()- Navigate up DIR structure
Test Utilities (runtestpath):
SrcPath(t)- Get tested source file path (from _test.go to corresponding .go file)SrcName(t)- Get tested source file nameSrcPathChangeExtension(t, ext)- Change tested file extension
- Dynamic Config File Paths - Read config.json from config.go dynamically
- Test Code Generation - Locate source files when generating code in tests
- Accurate Execution Paths - More reliable than
filepath.Abs(".")for execution location
path := runpath.Path()This method returns the absolute path of the source file at the point of execution, which is the execution location of the current code.
path := runpath.PARENT.Path()This method returns the absolute path of the DIR where the current source file resides, which can be useful for identifying the execution DIR abs-path.
path := runtestpath.SrcPath(t)This method returns the source path of the test file that is currently being run. It is particularly useful when testing and needing to know the exact location of the test file.
You can use runpath to easily build paths to configuration files based on the execution location of the code. This is especially useful in tests where different configurations are loaded depending on where the test is being executed.
path := runpath.DIR.Join("config.json")This dynamically constructs the path to config.json relative to the execution DIR abs-path.
You can also use PARENT for similar func:
path := runpath.PARENT.Join("config.json")If you need to navigate up multiple DIR levels from the execution location, use:
path := runpath.PARENT.UpTo(3, "config.json")This will return the path to config.json located three levels up from the execution DIR abs-path.
When running tests, you may need to generate code or reference the source file path dynamically. Here's how you can locate the test file’s source path:
func TestSrcPath(t *testing.T) {
path := runpath.SrcPath(t)
t.Log(path)
require.True(t, strings.HasSuffix(path, "runpath/runtestpath/utils_runtestpath.go"))
}This approach helps when generating code that needs to be placed alongside the original source files based on the execution location.
You can also change the file extension depending on the test context (e.g., from .go to .json):
func TestSrcPathChangeExtension(t *testing.T) {
path := runpath.SrcPathChangeExtension(t, ".json")
t.Log(path)
require.True(t, strings.HasSuffix(path, "runpath/runtestpath/utils_runtestpath.json"))
}
func TestSrcRex(t *testing.T) {
path := SrcRex(t, ".json")
t.Log(path)
require.True(t, strings.HasSuffix(path, "runpath/runtestpath/runtestpath.json"))
}This allows you to load different types of files (e.g., configuration files) based on the execution location and test requirements.
Path(): Returns the absolute path of the source file where the code is executed, representing the execution location.Current(),CurrentPath(),CurrentName(),Name(): Variants ofPath()that retrieve the file path or name based on the current execution context.Skip(int): Retrieves the path from a specified call frame, useful for getting the execution location of the caller.GetPathChangeExtension(): Returns the current source file path with a new extension (e.g., changing.goto.json).GetPathRemoveExtension(): Returns the current source file path without the.goextension.Join(): Joins the current DIR abs-path with additional path components, dynamically constructing paths based on the execution location.Up(),UpTo(): Navigates up the DIR structure a specified number of levels from the execution location.
SrcPath(t *testing.T): Retrieves the source path of the file being tested.SrcName(t *testing.T): Retrieves the name of the source file being tested.SrcPathChangeExtension(t *testing.T, ext string): Changes the extension of the test file path (e.g., from.goto.json).SrcSkipRemoveExtension(t *testing.T): Removes the.goextension from the test file path.
This package is particularly useful in test files, where you need to reference source code paths or configuration files based on the execution location of the test file.
MIT License. See LICENSE.
Contributions are welcome! Report bugs, suggest features, and contribute code:
- 🐛 Found a bug? Open an issue on GitHub with reproduction steps
- 💡 Have a feature idea? Create an issue to discuss the suggestion
- 📖 Documentation confusing? Report it so we can improve
- 🚀 Need new features? Share your use cases to help us understand requirements
- ⚡ Performance issue? Help us optimize by reporting slow operations
- 🔧 Configuration problem? Ask questions about complex setups
- 📢 Follow project progress? Watch the repo for new releases and features
- 🌟 Success stories? Share how this package improved your workflow
- 💬 General feedback? All suggestions and comments are welcome
New code contributions, follow this process:
- Fork: Fork the repo on GitHub (using the webpage interface).
- Clone: Clone the forked project (
git clone https://github.com/yourname/repo-name.git). - Navigate: Navigate to the cloned project (
cd repo-name) - Branch: Create a feature branch (
git checkout -b feature/xxx). - Code: Implement your changes with comprehensive tests
- Testing: (Golang project) Ensure tests pass (
go test ./...) and follow Go code style conventions - Documentation: Update documentation for user-facing changes and use meaningful commit messages
- Stage: Stage changes (
git add .) - Commit: Commit changes (
git commit -m "Add feature xxx") ensuring backward compatible code - Push: Push to the branch (
git push origin feature/xxx). - PR: Open a pull request on GitHub (on the GitHub webpage) with detailed description.
Please ensure tests pass and include relevant documentation updates.
Welcome to contribute to this project by submitting pull requests and reporting issues.
Project Support:
- ⭐ Give GitHub stars if this project helps you
- 🤝 Share with teammates and (golang) programming friends
- 📝 Write tech blogs about development tools and workflows - we provide content writing support
- 🌟 Join the ecosystem - committed to supporting open source and the (golang) development scene
Happy Coding with this package! 🎉
Give me stars! Thank you!!!