user8557463
user8557463

Reputation:

How to get the root path of the project

I run the following code workingDir, _ := os.Getwd() in server.go file which is under the root project and get the root path, Now I need to move the server.go file to the following structure

myapp
  src
   server.go

and I want to ge the path of go/src/myapp currently after I move the server.go under myapp->src>server.go I got path of go/src/myapp/src/server.go and I want to get the previews path ,

How should I do it in go automatically? or should I put ../ explicit in get path ?

Upvotes: 9

Views: 21468

Answers (3)

Nabin Ale
Nabin Ale

Reputation: 1

cd "$(git rev-parse --show-toplevel)"

Upvotes: 0

Marco Vignati
Marco Vignati

Reputation: 103

If your project is a git repository you can also use the git rev-parse command with the --show-toplevel:

cmdOut, err := exec.Command("git", "rev-parse", "--show-toplevel").Output()
if err != nil {
    assert.Fail(t, fmt.Sprintf(`Error on getting the go-kit base path: %s - %s`, err.Error(), string(cmdOut)))
    return
}

fmt.Println(strings.TrimSpace(string(cmdOut)))

It'll print out the git project home path wherever in the sub path you are

Upvotes: 7

Arman Ordookhani
Arman Ordookhani

Reputation: 6537

os.Getwd() does not return your source file path. It returns program current working directory (Usually the directory that you executed your program).

Example:

Assume I have a main.go in /Users/Arman/go/src/github.com/rmaan/project/main.go that just outputs os.Getwd()

$ cd /Users/Arman/go/src/github.com/rmaan/project/
$ go run main.go
/Users/Arman/go/src/github.com/rmaan/project <nil>

If I change to other directory and execute there, result will change.

$ cd /Users/Arman/
$ go run ./go/src/github.com/rmaan/project/main.go
/Users/Arman <nil>

IMO you should explicitly pass the path you want to your program instead of trying to infer it from context (As it may change specially in production environment). Here is an example with flag package.

package main

import (
    "fmt"
    "flag"
)


func main() {
    var myPath string
    flag.StringVar(&myPath, "my-path", "/", "Provide project path as an absolute path")
    flag.Parse()

    fmt.Printf("provided path was %s\n", myPath)
}

then execute your program as follows:

$ cd /Users/Arman/go/src/github.com/rmaan/project/
$ go run main.go  --my-path /Users/Arman/go/src/github.com/rmaan/project/
provided path was /Users/Arman/go/src/github.com/rmaan/project/
$ # or more easily
$ go run main.go  --my-path `pwd`
provided path was /Users/Arman/go/src/github.com/rmaan/project/

Upvotes: 9

Related Questions