|
- package pubshards
-
- import (
- "fmt"
- "os"
- "strconv"
- "strings"
-
- "github.com/spf13/cobra"
- "gitlink.org.cn/cloudream/common/sdks"
- cliapi "gitlink.org.cn/cloudream/jcs-pub/client/sdk/api/v1"
- "gitlink.org.cn/cloudream/jcs-pub/common/ecode"
- jcstypes "gitlink.org.cn/cloudream/jcs-pub/common/types"
- "gitlink.org.cn/cloudream/jcs-pub/jcsctl/cmd"
- )
-
- func init() {
- var opt import2Option
- c := &cobra.Command{
- Use: "import <local_file> <package_path>",
- Short: "import package object metadata from local file",
- Args: cobra.ExactArgs(2),
- RunE: func(c *cobra.Command, args []string) error {
- ctx := cmd.GetCmdCtx(c)
- return import2(c, ctx, opt, args)
- },
- }
- PubShardsCmd.AddCommand(c)
- c.Flags().BoolVarP(&opt.UseID, "id", "i", false, "treat first argumnet as package ID instead of package path")
- c.Flags().BoolVar(&opt.Create, "create", false, "create package if not exists")
- }
-
- type import2Option struct {
- UseID bool
- Create bool
- }
-
- func import2(c *cobra.Command, ctx *cmd.CommandContext, opt import2Option, args []string) error {
- var pkgID jcstypes.PackageID
- if opt.UseID {
- id, err := strconv.ParseInt(args[1], 10, 64)
- if err != nil {
- return fmt.Errorf("invalid package ID %v: %w", args[1], err)
- }
- pkgID = jcstypes.PackageID(id)
- } else {
- comps := strings.Split(args[1], "/")
-
- resp, err := ctx.Client.Package().GetByFullName(cliapi.PackageGetByFullName{
- BucketName: comps[0],
- PackageName: comps[1],
- })
- if err != nil {
- if !sdks.IsErrorCode(err, string(ecode.DataNotFound)) {
- return err
- }
-
- if !opt.Create {
- return fmt.Errorf("package not found")
- }
-
- bkt, err := ctx.Client.Bucket().GetByName(cliapi.BucketGetByName{
- Name: comps[0],
- })
- if err != nil {
- return fmt.Errorf("get bucket %v: %w", comps[0], err)
- }
-
- cpkg, err := ctx.Client.Package().Create(cliapi.PackageCreate{
- BucketID: bkt.Bucket.BucketID,
- Name: comps[1],
- })
- if err != nil {
- return fmt.Errorf("create package %v: %w", args[1], err)
- }
- pkgID = cpkg.Package.PackageID
- } else {
- pkgID = resp.Package.PackageID
- }
- }
-
- file, err := os.Open(args[0])
- if err != nil {
- return fmt.Errorf("open file %v: %w", args[0], err)
- }
- defer file.Close()
-
- resp, err := ctx.Client.PubShards().ImportPackage(cliapi.PubShardsImportPackage{
- PackageID: pkgID,
- PackFile: file,
- })
- if err != nil {
- return fmt.Errorf("import package: %w", err)
- }
- if len(resp.InvalidObjects) > 0 {
- fmt.Printf("below objects are invalid and will not be imported:\n")
- for _, obj := range resp.InvalidObjects {
- fmt.Printf("%v\n", obj.Path)
- }
- }
-
- return nil
- }
|