80 lines
1.4 KiB
Go
80 lines
1.4 KiB
Go
package cmd
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
|
|
"go.jolheiser.com/gpm/config"
|
|
|
|
"github.com/urfave/cli/v2"
|
|
"go.jolheiser.com/beaver"
|
|
)
|
|
|
|
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 {
|
|
cfg, err := config.Load()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
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
|
|
if isJSON {
|
|
data, err = os.ReadFile(arg)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
} else if isHTTP {
|
|
resp, err := http.Get(arg)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
data, err = io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
}
|
|
|
|
var importPkgs []config.Package
|
|
if err := json.Unmarshal(data, &importPkgs); err != nil {
|
|
return err
|
|
}
|
|
cfg.AddPackages(ctx.Bool("force"), importPkgs...)
|
|
|
|
if err := cfg.Save(); err != nil {
|
|
return err
|
|
}
|
|
|
|
beaver.Info("Import complete")
|
|
return nil
|
|
}
|