gpm/cmd/import.go

74 lines
1.4 KiB
Go
Raw Normal View History

package cmd
import (
"encoding/json"
"errors"
"github.com/urfave/cli/v2"
"go.jolheiser.com/beaver"
"go.jolheiser.com/gpm/modules/config"
"io/ioutil"
"net/http"
"strings"
)
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 {
if ctx.NArg() == 0 {
return errors.New("must point to either a JSON file or gpm server export endpoint")
}
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
var err error
if isJSON {
data, err = ioutil.ReadFile(arg)
if err != nil {
return err
}
} else if isHTTP {
resp, err := http.Get(arg)
if err != nil {
return err
}
data, err = ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
defer resp.Body.Close()
}
var cfg config.Config
if err := json.Unmarshal(data, &cfg); err != nil {
return err
}
config.AddPackages(ctx.Bool("force"), cfg.Packages...)
if err := config.Save(); err != nil {
return err
}
beaver.Info("Import complete")
return nil
}