Skip to content

Instantly share code, notes, and snippets.

@MohitVachhani
Created December 9, 2022 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MohitVachhani/e331321bb6f8c3e5e26b0cb4ab792c55 to your computer and use it in GitHub Desktop.
Save MohitVachhani/e331321bb6f8c3e5e26b0cb4ab792c55 to your computer and use it in GitHub Desktop.
Detecting go.mod contains replace or not
package scan_for_locals
import (
"fmt"
"io/ioutil"
"os"
"golang.org/x/mod/modfile"
)
// HasLocals returns true if the go.mod contains local redirects
func hasLocals(fileToParse string) (bool, error) {
data, err := ioutil.ReadFile(fileToParse)
if err != nil {
return false, err
}
m, err := modfile.Parse(fileToParse, data, nil)
if err != nil {
return false, err
}
if scanForLocals(m) {
return true, nil
}
return false, nil
}
func scanForLocals(m *modfile.File) bool {
foundLocal := false
for _, r := range m.Replace {
if modfile.IsDirectoryPath(r.New.Path) {
fmt.Printf("%s@%s is replaced to a local path\n", r.Old.Path, r.Old.Version)
foundLocal = true
}
}
return foundLocal
}
func main() {
var fileToParse = "go.mod"
if _, err := os.Stat(fileToParse); err == nil {
result, err := hasLocals(fileToParse)
if err != nil {
fmt.Printf("error reading go.mod: %s", err)
os.Exit(1)
}
if result {
os.Exit(1)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment