0

I use this code to get a list of dependencies imported in a single Go source file:

// GetFileImports returns all the imports from the Golang source code file.
func GetFileImports(filepath string) ([]string, error) {
    fset := token.NewFileSet()
    file, err := parser.ParseFile(fset, filepath, nil, parser.ImportsOnly)

    if err != nil {
        return nil, err
    }

    imports := make([]string, len(file.Imports))

    for i := range file.Imports {
        imports[i] = strings.Trim(file.Imports[i].Path.Value, "\"")
    }

    return imports, nil
}

I get this list:

namoled-core/data
namoled-core/shared
encoding/json
fmt
io/ioutil
log
net/http
github.com/gorilla/mux
github.com/gorilla/websocket

Where namoled-core/data and namoled-core/shared are parts of my own project, github.com/gorilla/mux and github.com/gorilla/websocket are downloadable dependencies, and all the rest are standard library dependencies. Is there a solid and unambiguous way to distinct dependencies from the current project, downloadable dependencies and standard library dependencies only by their import paths? Taking in account that project path may also be a Github link.

zergon321
  • 210
  • 1
  • 10
  • 3
    In general, the import path won't be enough, since a `go.mod` may contain `replace` directives, and any packages from your module may be mapped to any other, and vice versa (e.g. `github.com/gorilla/mux` may be replaced with `namoled-core/mux`). – icza Oct 30 '19 at 12:47
  • "parts of my own project" is also a concept that only exists for humans; Go itself has no notion of a "project". – Adrian Oct 30 '19 at 14:11
  • @Adrian yeah, I know that, but things like **dep** and **Glide** somehow determine which dependencies are downloadable and must be added in index files. – zergon321 Oct 30 '19 at 16:14

1 Answers1

0

If you are using Go Modules, you can use the contents of the go.sum file to filter the downloadable dependencies out of the response provided by your method.

Edit: One thing to keep in mind is that imports are related to packages while downloadable dependencies are related to modules. A module is composed of several packages and the packages have their module name as a prefix. So you may need to look in the go.sum file for entries that are prefixes for the package names returned by your method.