package cmd import ( "encoding/json" "fmt" "gitea.com/gpm/gpm/modules/config" "gitea.com/jolheiser/beaver" "github.com/AlecAivazis/survey/v2" "github.com/urfave/cli/v2" "io/ioutil" "net/http" "os" "os/exec" "strings" ) var Get = cli.Command{ Name: "get", Usage: "Get gpm package(s)", Flags: []cli.Flag{ &cli.BoolFlag{ Name: "ignore-local", Usage: "Ignore local packages", }, }, Action: doGet, } func doGet(ctx *cli.Context) error { pkgs := ctx.Args().Slice() if len(pkgs) == 0 { pkgsQuestion := &survey.Multiline{ Message: "Enter packages to get, one for each line", } var pkgsAnswer string if err := survey.AskOne(pkgsQuestion, &pkgsAnswer); err != nil { return err } pkgs = strings.Split(pkgsAnswer, "\n") } local := config.PackageMap() for _, pkg := range pkgs { var url string if u, ok := local[pkg]; ok { url = u } else { u, err := queryServer(ctx.String("url"), pkg) if err != nil { beaver.Error(err) continue } url = u } beaver.Infof("getting `%s`...", pkg) if err := goGet(url); err != nil { beaver.Error(err) } } return nil } type response struct { URL string `json:"url"` } func queryServer(server, name string) (string, error) { endpoint := fmt.Sprintf("%s/%s", server, name) resp, err := http.Get(endpoint) if err != nil { return "", nil } if resp.StatusCode != http.StatusOK { return "", fmt.Errorf("could not find server package for `%s`", name) } body, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } defer resp.Body.Close() var data response if err := json.Unmarshal(body, &data); err != nil { return "", err } return data.URL, nil } func goGet(url string) error { cmd := exec.Command("go", "get", url) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr return cmd.Run() }