2020-02-19 16:48:55 +00:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"io/ioutil"
|
2020-02-20 05:46:44 +00:00
|
|
|
"net/http"
|
|
|
|
"strings"
|
2020-10-07 04:11:36 +00:00
|
|
|
|
|
|
|
"go.jolheiser.com/gpm/config"
|
|
|
|
|
|
|
|
"github.com/urfave/cli/v2"
|
|
|
|
"go.jolheiser.com/beaver"
|
2020-02-19 16:48:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var Import = cli.Command{
|
|
|
|
Name: "import",
|
|
|
|
Usage: "Import JSON for local packages",
|
|
|
|
Flags: []cli.Flag{
|
|
|
|
&cli.BoolFlag{
|
|
|
|
Name: "force",
|
|
|
|
Aliases: []string{"f"},
|
|
|
|
Usage: "Overwrite any existing packages without prompt",
|
|
|
|
},
|
|
|
|
},
|
|
|
|
Action: doImport,
|
|
|
|
}
|
|
|
|
|
|
|
|
func doImport(ctx *cli.Context) error {
|
2020-10-07 04:11:36 +00:00
|
|
|
cfg, err := config.Load()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-02-20 05:46:44 +00:00
|
|
|
if ctx.NArg() == 0 {
|
|
|
|
return errors.New("must point to either a JSON file or gpm server export endpoint")
|
2020-02-19 16:48:55 +00:00
|
|
|
}
|
|
|
|
|
2020-02-20 05:46:44 +00:00
|
|
|
arg := ctx.Args().First()
|
|
|
|
isJSON := strings.HasSuffix(arg, ".json")
|
|
|
|
isHTTP := strings.HasPrefix(arg, "http")
|
|
|
|
|
|
|
|
if !isJSON && !isHTTP {
|
|
|
|
return errors.New("must point to either a JSON file or gpm server export endpoint")
|
|
|
|
}
|
|
|
|
|
|
|
|
var data []byte
|
|
|
|
if isJSON {
|
|
|
|
data, err = ioutil.ReadFile(arg)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
} else if isHTTP {
|
|
|
|
resp, err := http.Get(arg)
|
2020-02-19 16:48:55 +00:00
|
|
|
if err != nil {
|
2020-02-20 05:46:44 +00:00
|
|
|
return err
|
2020-02-19 16:48:55 +00:00
|
|
|
}
|
|
|
|
|
2020-02-20 05:46:44 +00:00
|
|
|
data, err = ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2020-02-19 16:48:55 +00:00
|
|
|
}
|
2020-02-20 05:46:44 +00:00
|
|
|
defer resp.Body.Close()
|
|
|
|
}
|
|
|
|
|
2020-10-07 04:11:36 +00:00
|
|
|
var importPkgs []config.Package
|
|
|
|
if err := json.Unmarshal(data, &importPkgs); err != nil {
|
2020-02-20 05:46:44 +00:00
|
|
|
return err
|
2020-02-19 16:48:55 +00:00
|
|
|
}
|
2020-10-07 04:11:36 +00:00
|
|
|
cfg.AddPackages(ctx.Bool("force"), importPkgs...)
|
2020-02-19 16:48:55 +00:00
|
|
|
|
2020-10-07 04:11:36 +00:00
|
|
|
if err := cfg.Save(); err != nil {
|
2020-02-19 16:48:55 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
beaver.Info("Import complete")
|
|
|
|
return nil
|
|
|
|
}
|