[#624] cli: Do not print help on any failure

Change usage function to `Run`(does not return
err). Log errors with `cmd.PrintErrln`. Change
all `fmt.Print*` to `cmd.Print*`.

Signed-off-by: Pavel Karpy <carpawell@nspcc.ru>
This commit is contained in:
Pavel Karpy 2021-06-21 02:02:56 +03:00 committed by Alex Vanin
parent af72412b77
commit 02ca1c4cc1
7 changed files with 479 additions and 360 deletions

View file

@ -25,48 +25,50 @@ var accountingBalanceCmd = &cobra.Command{
Use: "balance", Use: "balance",
Short: "Get internal balance of NeoFS account", Short: "Get internal balance of NeoFS account",
Long: `Get internal balance of NeoFS account`, Long: `Get internal balance of NeoFS account`,
RunE: func(cmd *cobra.Command, args []string) error { Run: func(cmd *cobra.Command, args []string) {
var ( var (
response *accounting.Decimal response *accounting.Decimal
oid *owner.ID oid *owner.ID
err error
ctx = context.Background() ctx = context.Background()
) )
key, err := getKey() key, err := getKey()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
if balanceOwner == "" { if balanceOwner == "" {
wallet, err := owner.NEO3WalletFromPublicKey(&key.PublicKey) wallet, err := owner.NEO3WalletFromPublicKey(&key.PublicKey)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
oid = owner.NewIDFromNeo3Wallet(wallet) oid = owner.NewIDFromNeo3Wallet(wallet)
} else { } else {
oid, err = ownerFromString(balanceOwner) oid, err = ownerFromString(balanceOwner)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
} }
response, err = cli.GetBalance(ctx, oid, globalCallOptions()...) response, err = cli.GetBalance(ctx, oid, globalCallOptions()...)
if err != nil { if err != nil {
return fmt.Errorf("rpc error: %w", err) cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
} }
// print to stdout // print to stdout
prettyPrintDecimal(response) prettyPrintDecimal(cmd, response)
return nil
}, },
} }
@ -87,14 +89,14 @@ func init() {
accountingBalanceCmd.Flags().StringVar(&balanceOwner, "owner", "", "owner of balance account (omit to use owner from private key)") accountingBalanceCmd.Flags().StringVar(&balanceOwner, "owner", "", "owner of balance account (omit to use owner from private key)")
} }
func prettyPrintDecimal(decimal *accounting.Decimal) { func prettyPrintDecimal(cmd *cobra.Command, decimal *accounting.Decimal) {
if decimal == nil { if decimal == nil {
return return
} }
if verbose { if verbose {
fmt.Println("value:", decimal.Value()) cmd.Println("value:", decimal.Value())
fmt.Println("precision:", decimal.Precision()) cmd.Println("precision:", decimal.Precision())
} else { } else {
// divider = 10^{precision}; v:365, p:2 => 365 / 10^2 = 3.65 // divider = 10^{precision}; v:365, p:2 => 365 / 10^2 = 3.65
divider := math.Pow(10, float64(decimal.Precision())) divider := math.Pow(10, float64(decimal.Precision()))
@ -102,6 +104,6 @@ func prettyPrintDecimal(decimal *accounting.Decimal) {
// %0.8f\n for precision 8 // %0.8f\n for precision 8
format := fmt.Sprintf("%%0.%df\n", decimal.Precision()) format := fmt.Sprintf("%%0.%df\n", decimal.Precision())
fmt.Printf(format, float64(decimal.Value())/divider) cmd.Printf(format, float64(decimal.Value())/divider)
} }
} }

View file

@ -78,48 +78,50 @@ var listContainersCmd = &cobra.Command{
Use: "list", Use: "list",
Short: "List all created containers", Short: "List all created containers",
Long: "List all created containers", Long: "List all created containers",
RunE: func(cmd *cobra.Command, args []string) error { Run: func(cmd *cobra.Command, args []string) {
var ( var (
response []*cid.ID response []*cid.ID
oid *owner.ID oid *owner.ID
err error
ctx = context.Background() ctx = context.Background()
) )
key, err := getKey() key, err := getKey()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
if containerOwner == "" { if containerOwner == "" {
wallet, err := owner.NEO3WalletFromPublicKey(&key.PublicKey) wallet, err := owner.NEO3WalletFromPublicKey(&key.PublicKey)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
oid = owner.NewIDFromNeo3Wallet(wallet) oid = owner.NewIDFromNeo3Wallet(wallet)
} else { } else {
oid, err = ownerFromString(containerOwner) oid, err = ownerFromString(containerOwner)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
} }
response, err = cli.ListContainers(ctx, oid, globalCallOptions()...) response, err = cli.ListContainers(ctx, oid, globalCallOptions()...)
if err != nil { if err != nil {
return fmt.Errorf("rpc error: %w", err) cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
} }
// print to stdout // print to stdout
prettyPrintContainerList(response) prettyPrintContainerList(cmd, response)
return nil
}, },
} }
@ -128,42 +130,49 @@ var createContainerCmd = &cobra.Command{
Short: "Create new container", Short: "Create new container",
Long: `Create new container and register it in the NeoFS. Long: `Create new container and register it in the NeoFS.
It will be stored in sidechain when inner ring will accepts it.`, It will be stored in sidechain when inner ring will accepts it.`,
RunE: func(cmd *cobra.Command, args []string) error { Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background() ctx := context.Background()
key, err := getKey() key, err := getKey()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
placementPolicy, err := parseContainerPolicy(containerPolicy) placementPolicy, err := parseContainerPolicy(containerPolicy)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
attributes, err := parseAttributes(containerAttributes) attributes, err := parseAttributes(containerAttributes)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
basicACL, err := parseBasicACL(containerACL) basicACL, err := parseBasicACL(containerACL)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
nonce, err := parseNonce(containerNonce) nonce, err := parseNonce(containerNonce)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
tok, err := getSessionToken(sessionTokenPath) tok, err := getSessionToken(sessionTokenPath)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
cnr := container.New() cnr := container.New()
@ -176,28 +185,27 @@ It will be stored in sidechain when inner ring will accepts it.`,
id, err := cli.PutContainer(ctx, cnr, globalCallOptions()...) id, err := cli.PutContainer(ctx, cnr, globalCallOptions()...)
if err != nil { if err != nil {
return fmt.Errorf("rpc error: %w", err) cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
} }
fmt.Println("container ID:", id) cmd.Println("container ID:", id)
if containerAwait { if containerAwait {
fmt.Println("awaiting...") cmd.Println("awaiting...")
for i := 0; i < awaitTimeout; i++ { for i := 0; i < awaitTimeout; i++ {
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
_, err := cli.GetContainer(ctx, id, globalCallOptions()...) _, err := cli.GetContainer(ctx, id, globalCallOptions()...)
if err == nil { if err == nil {
fmt.Println("container has been persisted on sidechain") cmd.Println("container has been persisted on sidechain")
return nil return
} }
} }
return errors.New("timeout: container has not been persisted on sidechain") cmd.PrintErrln("timeout: container has not been persisted on sidechain")
} }
return nil
}, },
} }
@ -206,27 +214,31 @@ var deleteContainerCmd = &cobra.Command{
Short: "Delete existing container", Short: "Delete existing container",
Long: `Delete existing container. Long: `Delete existing container.
Only owner of the container has a permission to remove container.`, Only owner of the container has a permission to remove container.`,
RunE: func(cmd *cobra.Command, args []string) error { Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background() ctx := context.Background()
key, err := getKey() key, err := getKey()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
id, err := parseContainerID(containerID) id, err := parseContainerID(containerID)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
tok, err := getSessionToken(sessionTokenPath) tok, err := getSessionToken(sessionTokenPath)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
callOpts := globalCallOptions() callOpts := globalCallOptions()
@ -237,28 +249,27 @@ Only owner of the container has a permission to remove container.`,
err = cli.DeleteContainer(ctx, id, callOpts...) err = cli.DeleteContainer(ctx, id, callOpts...)
if err != nil { if err != nil {
return fmt.Errorf("rpc error: %w", err) cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
} }
fmt.Println("container delete method invoked") cmd.Println("container delete method invoked")
if containerAwait { if containerAwait {
fmt.Println("awaiting...") cmd.Println("awaiting...")
for i := 0; i < awaitTimeout; i++ { for i := 0; i < awaitTimeout; i++ {
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
_, err := cli.GetContainer(ctx, id, globalCallOptions()...) _, err := cli.GetContainer(ctx, id, globalCallOptions()...)
if err != nil { if err != nil {
fmt.Println("container has been removed:", containerID) cmd.Println("container has been removed:", containerID)
return nil return
} }
} }
return errors.New("timeout: container has not been removed from sidechain") cmd.PrintErrln("timeout: container has not been removed from sidechain")
} }
return nil
}, },
} }
@ -266,27 +277,31 @@ var listContainerObjectsCmd = &cobra.Command{
Use: "list-objects", Use: "list-objects",
Short: "List existing objects in container", Short: "List existing objects in container",
Long: `List existing objects in container`, Long: `List existing objects in container`,
RunE: func(cmd *cobra.Command, args []string) error { Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background() ctx := context.Background()
key, err := getKey() key, err := getKey()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
id, err := parseContainerID(containerID) id, err := parseContainerID(containerID)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
sessionToken, err := cli.CreateSession(ctx, math.MaxUint64) sessionToken, err := cli.CreateSession(ctx, math.MaxUint64)
if err != nil { if err != nil {
return fmt.Errorf("can't create session token: %w", err) cmd.PrintErrln(fmt.Errorf("can't create session token: %w", err))
return
} }
filters := new(object.SearchFilters) filters := new(object.SearchFilters)
@ -302,14 +317,13 @@ var listContainerObjectsCmd = &cobra.Command{
)..., )...,
) )
if err != nil { if err != nil {
return fmt.Errorf("rpc error: %w", err) cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
} }
for i := range objectIDs { for i := range objectIDs {
fmt.Println(objectIDs[i]) cmd.Println(objectIDs[i])
} }
return nil
}, },
} }
@ -317,7 +331,7 @@ var getContainerInfoCmd = &cobra.Command{
Use: "get", Use: "get",
Short: "Get container field info", Short: "Get container field info",
Long: `Get container field info`, Long: `Get container field info`,
RunE: func(cmd *cobra.Command, args []string) error { Run: func(cmd *cobra.Command, args []string) {
var ( var (
cnr *container.Container cnr *container.Container
@ -327,36 +341,42 @@ var getContainerInfoCmd = &cobra.Command{
if containerPathFrom != "" { if containerPathFrom != "" {
data, err := ioutil.ReadFile(containerPathFrom) data, err := ioutil.ReadFile(containerPathFrom)
if err != nil { if err != nil {
return fmt.Errorf("can't read file: %w", err) cmd.PrintErrln(fmt.Errorf("can't read file: %w", err))
return
} }
cnr = container.New() cnr = container.New()
if err := cnr.Unmarshal(data); err != nil { if err := cnr.Unmarshal(data); err != nil {
return fmt.Errorf("can't unmarshal container: %w", err) cmd.PrintErrln(fmt.Errorf("can't unmarshal container: %w", err))
return
} }
} else { } else {
key, err := getKey() key, err := getKey()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
id, err := parseContainerID(containerID) id, err := parseContainerID(containerID)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
cnr, err = cli.GetContainer(ctx, id, globalCallOptions()...) cnr, err = cli.GetContainer(ctx, id, globalCallOptions()...)
if err != nil { if err != nil {
return fmt.Errorf("rpc error: %w", err) cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
} }
} }
prettyPrintContainer(cnr, containerJSON) prettyPrintContainer(cmd, cnr, containerJSON)
if containerPathTo != "" { if containerPathTo != "" {
var ( var (
@ -367,22 +387,23 @@ var getContainerInfoCmd = &cobra.Command{
if containerJSON { if containerJSON {
data, err = cnr.MarshalJSON() data, err = cnr.MarshalJSON()
if err != nil { if err != nil {
return fmt.Errorf("can't JSON encode container: %w", err) cmd.PrintErrln(fmt.Errorf("can't JSON encode container: %w", err))
return
} }
} else { } else {
data, err = cnr.Marshal() data, err = cnr.Marshal()
if err != nil { if err != nil {
return fmt.Errorf("can't binary encode container: %w", err) cmd.PrintErrln(fmt.Errorf("can't binary encode container: %w", err))
return
} }
} }
err = ioutil.WriteFile(containerPathTo, data, 0644) err = ioutil.WriteFile(containerPathTo, data, 0644)
if err != nil { if err != nil {
return fmt.Errorf("can't write container to file: %w", err) cmd.PrintErrln(fmt.Errorf("can't write container to file: %w", err))
return
} }
} }
return nil
}, },
} }
@ -390,40 +411,44 @@ var getExtendedACLCmd = &cobra.Command{
Use: "get-eacl", Use: "get-eacl",
Short: "Get extended ACL table of container", Short: "Get extended ACL table of container",
Long: `Get extended ACL talbe of container`, Long: `Get extended ACL talbe of container`,
RunE: func(cmd *cobra.Command, args []string) error { Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background() ctx := context.Background()
key, err := getKey() key, err := getKey()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
id, err := parseContainerID(containerID) id, err := parseContainerID(containerID)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
res, err := cli.GetEACL(ctx, id, globalCallOptions()...) res, err := cli.GetEACL(ctx, id, globalCallOptions()...)
if err != nil { if err != nil {
return fmt.Errorf("rpc error: %w", err) cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
} }
eaclTable := res.EACL() eaclTable := res.EACL()
sig := eaclTable.Signature() sig := eaclTable.Signature()
if containerPathTo == "" { if containerPathTo == "" {
fmt.Println("eACL: ") cmd.Println("eACL: ")
prettyPrintEACL(eaclTable) prettyPrintEACL(cmd, eaclTable)
fmt.Println("Signature:") cmd.Println("Signature:")
printJSONMarshaler(sig, "signature") printJSONMarshaler(cmd, sig, "signature")
return nil return
} }
var data []byte var data []byte
@ -431,21 +456,25 @@ var getExtendedACLCmd = &cobra.Command{
if containerJSON { if containerJSON {
data, err = eaclTable.MarshalJSON() data, err = eaclTable.MarshalJSON()
if err != nil { if err != nil {
return fmt.Errorf("can't enode to JSON: %w", err) cmd.PrintErrln(fmt.Errorf("can't enode to JSON: %w", err))
return
} }
} else { } else {
data, err = eaclTable.Marshal() data, err = eaclTable.Marshal()
if err != nil { if err != nil {
return fmt.Errorf("can't enode to binary: %w", err) cmd.PrintErrln(fmt.Errorf("can't enode to binary: %w", err))
return
} }
} }
fmt.Println("dumping data to file:", containerPathTo) cmd.Println("dumping data to file:", containerPathTo)
fmt.Println("Signature:") cmd.Println("Signature:")
printJSONMarshaler(sig, "signature") printJSONMarshaler(cmd, sig, "signature")
return ioutil.WriteFile(containerPathTo, data, 0644) if err = ioutil.WriteFile(containerPathTo, data, 0644); err != nil {
cmd.PrintErrln(err)
}
}, },
} }
@ -454,32 +483,37 @@ var setExtendedACLCmd = &cobra.Command{
Short: "Set new extended ACL table for container", Short: "Set new extended ACL table for container",
Long: `Set new extended ACL table for container. Long: `Set new extended ACL table for container.
Container ID in EACL table will be substituted with ID from the CLI.`, Container ID in EACL table will be substituted with ID from the CLI.`,
RunE: func(cmd *cobra.Command, args []string) error { Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background() ctx := context.Background()
key, err := getKey() key, err := getKey()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
id, err := parseContainerID(containerID) id, err := parseContainerID(containerID)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
eaclTable, err := parseEACL(eaclPathFrom) eaclTable, err := parseEACL(eaclPathFrom)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
tok, err := getSessionToken(sessionTokenPath) tok, err := getSessionToken(sessionTokenPath)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
eaclTable.SetCID(id) eaclTable.SetCID(id)
@ -487,16 +521,18 @@ Container ID in EACL table will be substituted with ID from the CLI.`,
err = cli.SetEACL(ctx, eaclTable, globalCallOptions()...) err = cli.SetEACL(ctx, eaclTable, globalCallOptions()...)
if err != nil { if err != nil {
return fmt.Errorf("rpc error: %w", err) cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
} }
if containerAwait { if containerAwait {
exp, err := eaclTable.Marshal() exp, err := eaclTable.Marshal()
if err != nil { if err != nil {
return errors.New("broken EACL table") cmd.PrintErrln("broken EACL table")
return
} }
fmt.Println("awaiting...") cmd.Println("awaiting...")
for i := 0; i < awaitTimeout; i++ { for i := 0; i < awaitTimeout; i++ {
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
@ -510,16 +546,15 @@ Container ID in EACL table will be substituted with ID from the CLI.`,
} }
if bytes.Equal(exp, got) { if bytes.Equal(exp, got) {
fmt.Println("EACL has been persisted on sidechain") cmd.Println("EACL has been persisted on sidechain")
return nil return
} }
} }
} }
return errors.New("timeout: EACL has not been persisted on sidechain") cmd.PrintErrln("timeout: EACL has not been persisted on sidechain")
return
} }
return nil
}, },
} }
@ -615,9 +650,9 @@ func getSessionToken(path string) (*session.Token, error) {
return tok, nil return tok, nil
} }
func prettyPrintContainerList(list []*cid.ID) { func prettyPrintContainerList(cmd *cobra.Command, list []*cid.ID) {
for i := range list { for i := range list {
fmt.Println(list[i]) cmd.Println(list[i])
} }
} }
@ -730,7 +765,7 @@ func parseContainerID(idStr string) (*cid.ID, error) {
return id, nil return id, nil
} }
func prettyPrintContainer(cnr *container.Container, jsonEncoding bool) { func prettyPrintContainer(cmd *cobra.Command, cnr *container.Container, jsonEncoding bool) {
if cnr == nil { if cnr == nil {
return return
} }
@ -746,35 +781,35 @@ func prettyPrintContainer(cnr *container.Container, jsonEncoding bool) {
printVerbose("Can't pretty print json: %w", err) printVerbose("Can't pretty print json: %w", err)
} }
fmt.Println(buf) cmd.Println(buf)
return return
} }
id := container.CalculateID(cnr) id := container.CalculateID(cnr)
fmt.Println("container ID:", id) cmd.Println("container ID:", id)
version := cnr.Version() version := cnr.Version()
fmt.Printf("version: %d.%d\n", version.Major(), version.Minor()) cmd.Printf("version: %d.%d\n", version.Major(), version.Minor())
fmt.Println("owner ID:", cnr.OwnerID()) cmd.Println("owner ID:", cnr.OwnerID())
basicACL := cnr.BasicACL() basicACL := cnr.BasicACL()
fmt.Printf("basic ACL: %s", strconv.FormatUint(uint64(basicACL), 16)) cmd.Printf("basic ACL: %s", strconv.FormatUint(uint64(basicACL), 16))
switch basicACL { switch basicACL {
case acl.PublicBasicRule: case acl.PublicBasicRule:
fmt.Printf(" (%s)\n", basicACLPublic) cmd.Printf(" (%s)\n", basicACLPublic)
case acl.PrivateBasicRule: case acl.PrivateBasicRule:
fmt.Printf(" (%s)\n", basicACLPrivate) cmd.Printf(" (%s)\n", basicACLPrivate)
case acl.ReadOnlyBasicRule: case acl.ReadOnlyBasicRule:
fmt.Printf(" (%s)\n", basicACLReadOnly) cmd.Printf(" (%s)\n", basicACLReadOnly)
default: default:
fmt.Println() cmd.Println()
} }
for _, attribute := range cnr.Attributes() { for _, attribute := range cnr.Attributes() {
if attribute.Key() == container.AttributeTimestamp { if attribute.Key() == container.AttributeTimestamp {
fmt.Printf("attribute: %s=%s (%s)\n", cmd.Printf("attribute: %s=%s (%s)\n",
attribute.Key(), attribute.Key(),
attribute.Value(), attribute.Value(),
prettyPrintUnixTime(attribute.Value())) prettyPrintUnixTime(attribute.Value()))
@ -782,18 +817,18 @@ func prettyPrintContainer(cnr *container.Container, jsonEncoding bool) {
continue continue
} }
fmt.Printf("attribute: %s=%s\n", attribute.Key(), attribute.Value()) cmd.Printf("attribute: %s=%s\n", attribute.Key(), attribute.Value())
} }
nonce, err := cnr.NonceUUID() nonce, err := cnr.NonceUUID()
if err == nil { if err == nil {
fmt.Println("nonce:", nonce) cmd.Println("nonce:", nonce)
} else { } else {
fmt.Println("invalid nonce:", err) cmd.Println("invalid nonce:", err)
} }
fmt.Println("placement policy:") cmd.Println("placement policy:")
fmt.Println(strings.Join(policy.Encode(cnr.PlacementPolicy()), "\n")) cmd.Println(strings.Join(policy.Encode(cnr.PlacementPolicy()), "\n"))
} }
func parseEACL(eaclPath string) (*eacl.Table, error) { func parseEACL(eaclPath string) (*eacl.Table, error) {
@ -823,11 +858,11 @@ func parseEACL(eaclPath string) (*eacl.Table, error) {
return nil, fmt.Errorf("can't parse EACL table: %w", err) return nil, fmt.Errorf("can't parse EACL table: %w", err)
} }
func prettyPrintEACL(table *eacl.Table) { func prettyPrintEACL(cmd *cobra.Command, table *eacl.Table) {
printJSONMarshaler(table, "eACL") printJSONMarshaler(cmd, table, "eACL")
} }
func printJSONMarshaler(j json.Marshaler, entity string) { func printJSONMarshaler(cmd *cobra.Command, j json.Marshaler, entity string) {
data, err := j.MarshalJSON() data, err := j.MarshalJSON()
if err != nil { if err != nil {
printVerbose("Can't convert %s to json: %w", entity, err) printVerbose("Can't convert %s to json: %w", entity, err)
@ -838,5 +873,5 @@ func printJSONMarshaler(j json.Marshaler, entity string) {
printVerbose("Can't pretty print json: %w", err) printVerbose("Can't pretty print json: %w", err)
return return
} }
fmt.Println(buf) cmd.Println(buf)
} }

View file

@ -24,14 +24,14 @@ var healthCheckCmd = &cobra.Command{
Use: "healthcheck", Use: "healthcheck",
Short: "Health check of the storage node", Short: "Health check of the storage node",
Long: "Health check of the storage node", Long: "Health check of the storage node",
RunE: healthCheck, Run: healthCheck,
} }
var setNetmapStatusCmd = &cobra.Command{ var setNetmapStatusCmd = &cobra.Command{
Use: "set-status", Use: "set-status",
Short: "Set status of the storage node in NeoFS network map", Short: "Set status of the storage node in NeoFS network map",
Long: "Set status of the storage node in NeoFS network map", Long: "Set status of the storage node in NeoFS network map",
RunE: setNetmapStatus, Run: setNetmapStatus,
} }
const ( const (
@ -79,20 +79,22 @@ func init() {
healthCheckCmd.Flags().BoolVar(&healthCheckIRVar, healthcheckIRFlag, false, "Communicate with IR node") healthCheckCmd.Flags().BoolVar(&healthCheckIRVar, healthcheckIRFlag, false, "Communicate with IR node")
} }
func healthCheck(cmd *cobra.Command, _ []string) error { func healthCheck(cmd *cobra.Command, _ []string) {
key, err := getKey() key, err := getKey()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
if healthCheckIRVar { if healthCheckIRVar {
healthCheckIR(cmd, key, cli) healthCheckIR(cmd, key, cli)
return nil return
} }
req := new(control.HealthCheckRequest) req := new(control.HealthCheckRequest)
@ -100,12 +102,14 @@ func healthCheck(cmd *cobra.Command, _ []string) error {
req.SetBody(new(control.HealthCheckRequest_Body)) req.SetBody(new(control.HealthCheckRequest_Body))
if err := controlSvc.SignMessage(key, req); err != nil { if err := controlSvc.SignMessage(key, req); err != nil {
return err cmd.PrintErrln(err)
return
} }
resp, err := control.HealthCheck(cli.Raw(), req) resp, err := control.HealthCheck(cli.Raw(), req)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
sign := resp.GetSignature() sign := resp.GetSignature()
@ -113,13 +117,12 @@ func healthCheck(cmd *cobra.Command, _ []string) error {
if err := signature.VerifyDataWithSource(resp, func() ([]byte, []byte) { if err := signature.VerifyDataWithSource(resp, func() ([]byte, []byte) {
return sign.GetKey(), sign.GetSign() return sign.GetKey(), sign.GetSign()
}); err != nil { }); err != nil {
return err cmd.PrintErrln(err)
return
} }
cmd.Printf("Network status: %s\n", resp.GetBody().GetNetmapStatus()) cmd.Printf("Network status: %s\n", resp.GetBody().GetNetmapStatus())
cmd.Printf("Health status: %s\n", resp.GetBody().GetHealthStatus()) cmd.Printf("Health status: %s\n", resp.GetBody().GetHealthStatus())
return nil
} }
func healthCheckIR(cmd *cobra.Command, key *ecdsa.PrivateKey, c client.Client) { func healthCheckIR(cmd *cobra.Command, key *ecdsa.PrivateKey, c client.Client) {
@ -150,17 +153,19 @@ func healthCheckIR(cmd *cobra.Command, key *ecdsa.PrivateKey, c client.Client) {
cmd.Printf("Health status: %s\n", resp.GetBody().GetHealthStatus()) cmd.Printf("Health status: %s\n", resp.GetBody().GetHealthStatus())
} }
func setNetmapStatus(cmd *cobra.Command, _ []string) error { func setNetmapStatus(cmd *cobra.Command, _ []string) {
key, err := getKey() key, err := getKey()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
var status control.NetmapStatus var status control.NetmapStatus
switch netmapStatus { switch netmapStatus {
default: default:
return fmt.Errorf("unsupported status %s", netmapStatus) cmd.PrintErrln(fmt.Errorf("unsupported status %s", netmapStatus))
return
case netmapStatusOnline: case netmapStatusOnline:
status = control.NetmapStatus_ONLINE status = control.NetmapStatus_ONLINE
case netmapStatusOffline: case netmapStatusOffline:
@ -175,17 +180,20 @@ func setNetmapStatus(cmd *cobra.Command, _ []string) error {
body.SetStatus(status) body.SetStatus(status)
if err := controlSvc.SignMessage(key, req); err != nil { if err := controlSvc.SignMessage(key, req); err != nil {
return err cmd.PrintErrln(err)
return
} }
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
resp, err := control.SetNetmapStatus(cli.Raw(), req) resp, err := control.SetNetmapStatus(cli.Raw(), req)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
sign := resp.GetSignature() sign := resp.GetSignature()
@ -193,12 +201,11 @@ func setNetmapStatus(cmd *cobra.Command, _ []string) error {
if err := signature.VerifyDataWithSource(resp, func() ([]byte, []byte) { if err := signature.VerifyDataWithSource(resp, func() ([]byte, []byte) {
return sign.GetKey(), sign.GetSign() return sign.GetKey(), sign.GetSign()
}); err != nil { }); err != nil {
return err cmd.PrintErrln(err)
return
} }
cmd.Println("Network status update request successfully sent.") cmd.Println("Network status update request successfully sent.")
return nil
} }
const dropObjectsFlag = "objects" const dropObjectsFlag = "objects"
@ -209,10 +216,11 @@ var dropObjectsCmd = &cobra.Command{
Use: "drop-objects", Use: "drop-objects",
Short: "Drop objects from the node's local storage", Short: "Drop objects from the node's local storage",
Long: "Drop objects from the node's local storage", Long: "Drop objects from the node's local storage",
RunE: func(cmd *cobra.Command, args []string) error { Run: func(cmd *cobra.Command, args []string) {
key, err := getKey() key, err := getKey()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
binAddrList := make([][]byte, 0, len(dropObjectsList)) binAddrList := make([][]byte, 0, len(dropObjectsList))
@ -222,12 +230,14 @@ var dropObjectsCmd = &cobra.Command{
err := a.Parse(dropObjectsList[i]) err := a.Parse(dropObjectsList[i])
if err != nil { if err != nil {
return fmt.Errorf("could not parse address #%d: %w", i, err) cmd.PrintErrln(fmt.Errorf("could not parse address #%d: %w", i, err))
return
} }
binAddr, err := a.Marshal() binAddr, err := a.Marshal()
if err != nil { if err != nil {
return fmt.Errorf("could not marshal the address: %w", err) cmd.PrintErrln(fmt.Errorf("could not marshal the address: %w", err))
return
} }
binAddrList = append(binAddrList, binAddr) binAddrList = append(binAddrList, binAddr)
@ -241,17 +251,20 @@ var dropObjectsCmd = &cobra.Command{
body.SetAddressList(binAddrList) body.SetAddressList(binAddrList)
if err := controlSvc.SignMessage(key, req); err != nil { if err := controlSvc.SignMessage(key, req); err != nil {
return err cmd.PrintErrln(err)
return
} }
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
resp, err := control.DropObjects(cli.Raw(), req) resp, err := control.DropObjects(cli.Raw(), req)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
sign := resp.GetSignature() sign := resp.GetSignature()
@ -259,11 +272,10 @@ var dropObjectsCmd = &cobra.Command{
if err := signature.VerifyDataWithSource(resp, func() ([]byte, []byte) { if err := signature.VerifyDataWithSource(resp, func() ([]byte, []byte) {
return sign.GetKey(), sign.GetSign() return sign.GetKey(), sign.GetSign()
}); err != nil { }); err != nil {
return err cmd.PrintErrln(err)
return
} }
cmd.Println("Objects were successfully marked to be removed.") cmd.Println("Objects were successfully marked to be removed.")
return nil
}, },
} }

View file

@ -4,7 +4,6 @@ import (
"context" "context"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"github.com/mr-tron/base58" "github.com/mr-tron/base58"
"github.com/nspcc-dev/neo-go/pkg/config/netmode" "github.com/nspcc-dev/neo-go/pkg/config/netmode"
"github.com/nspcc-dev/neofs-api-go/pkg/netmap" "github.com/nspcc-dev/neofs-api-go/pkg/netmap"
@ -47,25 +46,26 @@ var getEpochCmd = &cobra.Command{
Use: "epoch", Use: "epoch",
Short: "Get current epoch number", Short: "Get current epoch number",
Long: "Get current epoch number", Long: "Get current epoch number",
RunE: func(cmd *cobra.Command, args []string) error { Run: func(cmd *cobra.Command, args []string) {
key, err := getKey() key, err := getKey()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
netInfo, err := cli.NetworkInfo(context.Background(), globalCallOptions()...) netInfo, err := cli.NetworkInfo(context.Background(), globalCallOptions()...)
if err != nil { if err != nil {
return fmt.Errorf("rpc error: %w", err) cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
} }
fmt.Println(netInfo.CurrentEpoch()) cmd.Println(netInfo.CurrentEpoch())
return nil
}, },
} }
@ -73,25 +73,26 @@ var localNodeInfoCmd = &cobra.Command{
Use: "nodeinfo", Use: "nodeinfo",
Short: "Get local node info", Short: "Get local node info",
Long: `Get local node info`, Long: `Get local node info`,
RunE: func(cmd *cobra.Command, args []string) error { Run: func(cmd *cobra.Command, args []string) {
key, err := getKey() key, err := getKey()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
nodeInfo, err := cli.EndpointInfo(context.Background(), globalCallOptions()...) nodeInfo, err := cli.EndpointInfo(context.Background(), globalCallOptions()...)
if err != nil { if err != nil {
return fmt.Errorf("rpc error: %w", err) cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
} }
prettyPrintNodeInfo(nodeInfo.NodeInfo(), nodeInfoJSON) prettyPrintNodeInfo(cmd, nodeInfo.NodeInfo(), nodeInfoJSON)
return nil
}, },
} }
@ -99,27 +100,31 @@ var snapshotCmd = &cobra.Command{
Use: "snapshot", Use: "snapshot",
Short: "Get network map snapshot", Short: "Get network map snapshot",
Long: "Get network map snapshot", Long: "Get network map snapshot",
RunE: func(cmd *cobra.Command, args []string) error { Run: func(cmd *cobra.Command, args []string) {
key, err := getKey() key, err := getKey()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
req := new(control.NetmapSnapshotRequest) req := new(control.NetmapSnapshotRequest)
req.SetBody(new(control.NetmapSnapshotRequest_Body)) req.SetBody(new(control.NetmapSnapshotRequest_Body))
if err := controlSvc.SignMessage(key, req); err != nil { if err := controlSvc.SignMessage(key, req); err != nil {
return err cmd.PrintErrln(err)
return
} }
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
resp, err := control.NetmapSnapshot(cli.Raw(), req) resp, err := control.NetmapSnapshot(cli.Raw(), req)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
sign := resp.GetSignature() sign := resp.GetSignature()
@ -127,12 +132,11 @@ var snapshotCmd = &cobra.Command{
if err := signature.VerifyDataWithSource(resp, func() ([]byte, []byte) { if err := signature.VerifyDataWithSource(resp, func() ([]byte, []byte) {
return sign.GetKey(), sign.GetSign() return sign.GetKey(), sign.GetSign()
}); err != nil { }); err != nil {
return err cmd.PrintErrln(err)
return
} }
prettyPrintNetmap(resp.GetBody().GetNetmap(), netmapSnapshotJSON) prettyPrintNetmap(cmd, resp.GetBody().GetNetmap(), netmapSnapshotJSON)
return nil
}, },
} }
@ -140,63 +144,64 @@ var netInfoCmd = &cobra.Command{
Use: "netinfo", Use: "netinfo",
Short: "Get information about NeoFS network", Short: "Get information about NeoFS network",
Long: "Get information about NeoFS network", Long: "Get information about NeoFS network",
RunE: func(cmd *cobra.Command, args []string) error { Run: func(cmd *cobra.Command, args []string) {
key, err := getKey() key, err := getKey()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
cli, err := getSDKClient(key) cli, err := getSDKClient(key)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
netInfo, err := cli.NetworkInfo(context.Background(), globalCallOptions()...) netInfo, err := cli.NetworkInfo(context.Background(), globalCallOptions()...)
if err != nil { if err != nil {
return fmt.Errorf("rpc error: %w", err) cmd.PrintErrln(fmt.Errorf("rpc error: %w", err))
return
} }
cmd.Printf("Epoch: %d\n", netInfo.CurrentEpoch()) cmd.Printf("Epoch: %d\n", netInfo.CurrentEpoch())
magic := netInfo.MagicNumber() magic := netInfo.MagicNumber()
cmd.Printf("Network magic: [%s] %d\n", netmode.Magic(magic), magic) cmd.Printf("Network magic: [%s] %d\n", netmode.Magic(magic), magic)
return nil
}, },
} }
func prettyPrintNodeInfo(i *netmap.NodeInfo, jsonEncoding bool) { func prettyPrintNodeInfo(cmd *cobra.Command, i *netmap.NodeInfo, jsonEncoding bool) {
if jsonEncoding { if jsonEncoding {
printJSONMarshaler(i, "node info") printJSONMarshaler(cmd, i, "node info")
return return
} }
fmt.Println("key:", hex.EncodeToString(i.PublicKey())) cmd.Println("key:", hex.EncodeToString(i.PublicKey()))
fmt.Println("address:", i.Address()) cmd.Println("address:", i.Address())
fmt.Println("state:", i.State()) cmd.Println("state:", i.State())
for _, attribute := range i.Attributes() { for _, attribute := range i.Attributes() {
fmt.Printf("attribute: %s=%s\n", attribute.Key(), attribute.Value()) cmd.Printf("attribute: %s=%s\n", attribute.Key(), attribute.Value())
} }
} }
func prettyPrintNetmap(nm *control.Netmap, jsonEncoding bool) { func prettyPrintNetmap(cmd *cobra.Command, nm *control.Netmap, jsonEncoding bool) {
if jsonEncoding { if jsonEncoding {
printJSONMarshaler(nm, "netmap") printJSONMarshaler(cmd, nm, "netmap")
return return
} }
fmt.Println("Epoch:", nm.GetEpoch()) cmd.Println("Epoch:", nm.GetEpoch())
for i, node := range nm.GetNodes() { for i, node := range nm.GetNodes() {
fmt.Printf("Node %d: %s %s %s\n", i+1, cmd.Printf("Node %d: %s %s %s\n", i+1,
base58.Encode(node.GetPublicKey()), base58.Encode(node.GetPublicKey()),
node.GetAddress(), node.GetAddress(),
node.GetState(), node.GetState(),
) )
for _, attr := range node.GetAttributes() { for _, attr := range node.GetAttributes() {
fmt.Printf("\t%s: %s\n", attr.GetKey(), attr.GetValue()) cmd.Printf("\t%s: %s\n", attr.GetKey(), attr.GetValue())
} }
} }
} }

View file

@ -48,14 +48,14 @@ var (
Use: "put", Use: "put",
Short: "Put object to NeoFS", Short: "Put object to NeoFS",
Long: "Put object to NeoFS", Long: "Put object to NeoFS",
RunE: putObject, Run: putObject,
} }
objectGetCmd = &cobra.Command{ objectGetCmd = &cobra.Command{
Use: "get", Use: "get",
Short: "Get object from NeoFS", Short: "Get object from NeoFS",
Long: "Get object from NeoFS", Long: "Get object from NeoFS",
RunE: getObject, Run: getObject,
} }
objectDelCmd = &cobra.Command{ objectDelCmd = &cobra.Command{
@ -63,7 +63,7 @@ var (
Aliases: []string{"del"}, Aliases: []string{"del"},
Short: "Delete object from NeoFS", Short: "Delete object from NeoFS",
Long: "Delete object from NeoFS", Long: "Delete object from NeoFS",
RunE: deleteObject, Run: deleteObject,
} }
searchFilters []string searchFilters []string
@ -72,28 +72,28 @@ var (
Use: "search", Use: "search",
Short: "Search object", Short: "Search object",
Long: "Search object", Long: "Search object",
RunE: searchObject, Run: searchObject,
} }
objectHeadCmd = &cobra.Command{ objectHeadCmd = &cobra.Command{
Use: "head", Use: "head",
Short: "Get object header", Short: "Get object header",
Long: "Get object header", Long: "Get object header",
RunE: getObjectHeader, Run: getObjectHeader,
} }
objectHashCmd = &cobra.Command{ objectHashCmd = &cobra.Command{
Use: "hash", Use: "hash",
Short: "Get object hash", Short: "Get object hash",
Long: "Get object hash", Long: "Get object hash",
RunE: getObjectHash, Run: getObjectHash,
} }
objectRangeCmd = &cobra.Command{ objectRangeCmd = &cobra.Command{
Use: getRangeCmdUse, Use: getRangeCmdUse,
Short: getRangeCmdShortDesc, Short: getRangeCmdShortDesc,
Long: getRangeCmdLongDesc, Long: getRangeCmdLongDesc,
RunE: getObjectRange, Run: getObjectRange,
} }
) )
@ -210,25 +210,29 @@ func initSession(ctx context.Context) (client.Client, *session.Token, error) {
return cli, tok, nil return cli, tok, nil
} }
func putObject(cmd *cobra.Command, _ []string) error { func putObject(cmd *cobra.Command, _ []string) {
ownerID, err := getOwnerID() ownerID, err := getOwnerID()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
cid, err := getCID(cmd) cid, err := getCID(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
filename := cmd.Flag("file").Value.String() filename := cmd.Flag("file").Value.String()
f, err := os.OpenFile(filename, os.O_RDONLY, os.ModePerm) f, err := os.OpenFile(filename, os.O_RDONLY, os.ModePerm)
if err != nil { if err != nil {
return fmt.Errorf("can't open file '%s': %w", filename, err) cmd.PrintErrln(fmt.Errorf("can't open file '%s': %w", filename, err))
return
} }
attrs, err := parseObjectAttrs(cmd) attrs, err := parseObjectAttrs(cmd)
if err != nil { if err != nil {
return fmt.Errorf("can't parse object attributes: %w", err) cmd.PrintErrln(fmt.Errorf("can't parse object attributes: %w", err))
return
} }
expiresOn, _ := cmd.Flags().GetUint64(putExpiresOnFlag) expiresOn, _ := cmd.Flags().GetUint64(putExpiresOnFlag)
@ -259,11 +263,13 @@ func putObject(cmd *cobra.Command, _ []string) error {
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx) cli, tok, err := initSession(ctx)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
btok, err := getBearerToken(cmd, "bearer") btok, err := getBearerToken(cmd, "bearer")
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
oid, err := cli.PutObject(ctx, oid, err := cli.PutObject(ctx,
new(client.PutObjectParams). new(client.PutObjectParams).
@ -275,28 +281,31 @@ func putObject(cmd *cobra.Command, _ []string) error {
)..., )...,
) )
if err != nil { if err != nil {
return fmt.Errorf("can't put object: %w", err) cmd.PrintErrln(fmt.Errorf("can't put object: %w", err))
return
} }
cmd.Printf("[%s] Object successfully stored\n", filename) cmd.Printf("[%s] Object successfully stored\n", filename)
cmd.Printf(" ID: %s\n CID: %s\n", oid, cid) cmd.Printf(" ID: %s\n CID: %s\n", oid, cid)
return nil
} }
func deleteObject(cmd *cobra.Command, _ []string) error { func deleteObject(cmd *cobra.Command, _ []string) {
objAddr, err := getObjectAddress(cmd) objAddr, err := getObjectAddress(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx) cli, tok, err := initSession(ctx)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
btok, err := getBearerToken(cmd, "bearer") btok, err := getBearerToken(cmd, "bearer")
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
tombstoneAddr, err := client.DeleteObject(ctx, cli, tombstoneAddr, err := client.DeleteObject(ctx, cli,
@ -307,18 +316,19 @@ func deleteObject(cmd *cobra.Command, _ []string) error {
)..., )...,
) )
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
cmd.Println("Object removed successfully.") cmd.Println("Object removed successfully.")
cmd.Printf(" ID: %s\n CID: %s\n", tombstoneAddr.ObjectID(), tombstoneAddr.ContainerID()) cmd.Printf(" ID: %s\n CID: %s\n", tombstoneAddr.ObjectID(), tombstoneAddr.ContainerID())
return nil
} }
func getObject(cmd *cobra.Command, _ []string) error { func getObject(cmd *cobra.Command, _ []string) {
objAddr, err := getObjectAddress(cmd) objAddr, err := getObjectAddress(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
var out io.Writer var out io.Writer
@ -328,7 +338,8 @@ func getObject(cmd *cobra.Command, _ []string) error {
} else { } else {
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, os.ModePerm) f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, os.ModePerm)
if err != nil { if err != nil {
return fmt.Errorf("can't open file '%s': %w", filename, err) cmd.PrintErrln(fmt.Errorf("can't open file '%s': %w", filename, err))
return
} }
defer f.Close() defer f.Close()
out = f out = f
@ -337,11 +348,13 @@ func getObject(cmd *cobra.Command, _ []string) error {
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx) cli, tok, err := initSession(ctx)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
btok, err := getBearerToken(cmd, "bearer") btok, err := getBearerToken(cmd, "bearer")
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
raw, _ := cmd.Flags().GetBool(rawFlag) raw, _ := cmd.Flags().GetBool(rawFlag)
@ -358,10 +371,11 @@ func getObject(cmd *cobra.Command, _ []string) error {
) )
if err != nil { if err != nil {
if ok := printSplitInfoErr(cmd, err); ok { if ok := printSplitInfoErr(cmd, err); ok {
return nil return
} }
return fmt.Errorf("can't get object: %w", err) cmd.PrintErrln(fmt.Errorf("can't get object: %w", err))
return
} }
if filename != "" { if filename != "" {
@ -371,25 +385,30 @@ func getObject(cmd *cobra.Command, _ []string) error {
// Print header only if file is not streamed to stdout. // Print header only if file is not streamed to stdout.
hdrFile := cmd.Flag("header").Value.String() hdrFile := cmd.Flag("header").Value.String()
if filename != "" || hdrFile != "" { if filename != "" || hdrFile != "" {
return saveAndPrintHeader(cmd, obj, hdrFile) if err = saveAndPrintHeader(cmd, obj, hdrFile); err != nil {
cmd.PrintErrln(err)
return
}
} }
return nil
} }
func getObjectHeader(cmd *cobra.Command, _ []string) error { func getObjectHeader(cmd *cobra.Command, _ []string) {
objAddr, err := getObjectAddress(cmd) objAddr, err := getObjectAddress(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx) cli, tok, err := initSession(ctx)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
btok, err := getBearerToken(cmd, "bearer") btok, err := getBearerToken(cmd, "bearer")
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
ps := new(client.ObjectHeaderParams).WithAddress(objAddr) ps := new(client.ObjectHeaderParams).WithAddress(objAddr)
if ok, _ := cmd.Flags().GetBool("main-only"); ok { if ok, _ := cmd.Flags().GetBool("main-only"); ok {
@ -407,34 +426,42 @@ func getObjectHeader(cmd *cobra.Command, _ []string) error {
) )
if err != nil { if err != nil {
if ok := printSplitInfoErr(cmd, err); ok { if ok := printSplitInfoErr(cmd, err); ok {
return nil return
} }
return fmt.Errorf("can't get object header: %w", err) cmd.PrintErrln(fmt.Errorf("can't get object header: %w", err))
return
} }
return saveAndPrintHeader(cmd, obj, cmd.Flag("file").Value.String()) if err = saveAndPrintHeader(cmd, obj, cmd.Flag("file").Value.String()); err != nil {
cmd.PrintErrln(err)
return
}
} }
func searchObject(cmd *cobra.Command, _ []string) error { func searchObject(cmd *cobra.Command, _ []string) {
cid, err := getCID(cmd) cid, err := getCID(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
sf, err := parseSearchFilters(cmd) sf, err := parseSearchFilters(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx) cli, tok, err := initSession(ctx)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
btok, err := getBearerToken(cmd, "bearer") btok, err := getBearerToken(cmd, "bearer")
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
ps := new(client.SearchObjectParams).WithContainerID(cid).WithSearchFilters(sf) ps := new(client.SearchObjectParams).WithContainerID(cid).WithSearchFilters(sf)
ids, err := cli.SearchObject(ctx, ps, ids, err := cli.SearchObject(ctx, ps,
@ -444,44 +471,50 @@ func searchObject(cmd *cobra.Command, _ []string) error {
)..., )...,
) )
if err != nil { if err != nil {
return fmt.Errorf("can't search object: %w", err) cmd.PrintErrln(fmt.Errorf("can't search object: %w", err))
return
} }
cmd.Printf("Found %d objects.\n", len(ids)) cmd.Printf("Found %d objects.\n", len(ids))
for _, id := range ids { for _, id := range ids {
cmd.Println(id) cmd.Println(id)
} }
return nil
} }
func getObjectHash(cmd *cobra.Command, _ []string) error { func getObjectHash(cmd *cobra.Command, _ []string) {
objAddr, err := getObjectAddress(cmd) objAddr, err := getObjectAddress(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
ranges, err := getRangeList(cmd) ranges, err := getRangeList(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
typ, err := getHashType(cmd) typ, err := getHashType(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
strSalt := strings.TrimPrefix(cmd.Flag(getRangeHashSaltFlag).Value.String(), "0x") strSalt := strings.TrimPrefix(cmd.Flag(getRangeHashSaltFlag).Value.String(), "0x")
salt, err := hex.DecodeString(strSalt) salt, err := hex.DecodeString(strSalt)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx) cli, tok, err := initSession(ctx)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
btok, err := getBearerToken(cmd, "bearer") btok, err := getBearerToken(cmd, "bearer")
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
if len(ranges) == 0 { // hash of full payload if len(ranges) == 0 { // hash of full payload
obj, err := cli.GetObjectHeader(ctx, obj, err := cli.GetObjectHeader(ctx,
@ -492,7 +525,8 @@ func getObjectHash(cmd *cobra.Command, _ []string) error {
)..., )...,
) )
if err != nil { if err != nil {
return fmt.Errorf("can't get object header: %w", err) cmd.PrintErrln(fmt.Errorf("can't get object header: %w", err))
return
} }
switch typ { switch typ {
case hashSha256: case hashSha256:
@ -500,7 +534,7 @@ func getObjectHash(cmd *cobra.Command, _ []string) error {
case hashTz: case hashTz:
cmd.Println(hex.EncodeToString(obj.PayloadHomomorphicHash().Sum())) cmd.Println(hex.EncodeToString(obj.PayloadHomomorphicHash().Sum()))
} }
return nil return
} }
ps := new(client.RangeChecksumParams). ps := new(client.RangeChecksumParams).
@ -517,7 +551,8 @@ func getObjectHash(cmd *cobra.Command, _ []string) error {
)..., )...,
) )
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
for i := range res { for i := range res {
cmd.Printf("Offset=%d (Length=%d)\t: %s\n", ranges[i].GetOffset(), ranges[i].GetLength(), cmd.Printf("Offset=%d (Length=%d)\t: %s\n", ranges[i].GetOffset(), ranges[i].GetLength(),
@ -531,14 +566,14 @@ func getObjectHash(cmd *cobra.Command, _ []string) error {
)..., )...,
) )
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
for i := range res { for i := range res {
cmd.Printf("Offset=%d (Length=%d)\t: %s\n", ranges[i].GetOffset(), ranges[i].GetLength(), cmd.Printf("Offset=%d (Length=%d)\t: %s\n", ranges[i].GetOffset(), ranges[i].GetLength(),
hex.EncodeToString(res[i][:])) hex.EncodeToString(res[i][:]))
} }
} }
return nil
} }
func getOwnerID() (*owner.ID, error) { func getOwnerID() (*owner.ID, error) {
@ -861,17 +896,20 @@ func getBearerToken(cmd *cobra.Command, flagname string) (*token.BearerToken, er
return tok, nil return tok, nil
} }
func getObjectRange(cmd *cobra.Command, _ []string) error { func getObjectRange(cmd *cobra.Command, _ []string) {
objAddr, err := getObjectAddress(cmd) objAddr, err := getObjectAddress(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
ranges, err := getRangeList(cmd) ranges, err := getRangeList(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} else if len(ranges) != 1 { } else if len(ranges) != 1 {
return errors.New("exactly one range must be specified") cmd.PrintErrln(err)
return
} }
var out io.Writer var out io.Writer
@ -882,7 +920,8 @@ func getObjectRange(cmd *cobra.Command, _ []string) error {
} else { } else {
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, os.ModePerm) f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, os.ModePerm)
if err != nil { if err != nil {
return fmt.Errorf("can't open file '%s': %w", filename, err) cmd.PrintErrln(fmt.Errorf("can't open file '%s': %w", filename, err))
return
} }
defer f.Close() defer f.Close()
@ -894,12 +933,14 @@ func getObjectRange(cmd *cobra.Command, _ []string) error {
c, sessionToken, err := initSession(ctx) c, sessionToken, err := initSession(ctx)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
bearerToken, err := getBearerToken(cmd, "bearer") bearerToken, err := getBearerToken(cmd, "bearer")
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
raw, _ := cmd.Flags().GetBool(rawFlag) raw, _ := cmd.Flags().GetBool(rawFlag)
@ -917,17 +958,16 @@ func getObjectRange(cmd *cobra.Command, _ []string) error {
) )
if err != nil { if err != nil {
if ok := printSplitInfoErr(cmd, err); ok { if ok := printSplitInfoErr(cmd, err); ok {
return nil return
} }
return fmt.Errorf("can't get object payload range: %w", err) cmd.PrintErrln(fmt.Errorf("can't get object payload range: %w", err))
return
} }
if filename != "" { if filename != "" {
cmd.Printf("[%s] Payload successfully saved\n", filename) cmd.Printf("[%s] Payload successfully saved\n", filename)
} }
return nil
} }
func printSplitInfoErr(cmd *cobra.Command, err error) bool { func printSplitInfoErr(cmd *cobra.Command, err error) bool {

View file

@ -26,28 +26,28 @@ var sgPutCmd = &cobra.Command{
Use: "put", Use: "put",
Short: "Put storage group to NeoFS", Short: "Put storage group to NeoFS",
Long: "Put storage group to NeoFS", Long: "Put storage group to NeoFS",
RunE: putSG, Run: putSG,
} }
var sgGetCmd = &cobra.Command{ var sgGetCmd = &cobra.Command{
Use: "get", Use: "get",
Short: "Get storage group from NeoFS", Short: "Get storage group from NeoFS",
Long: "Get storage group from NeoFS", Long: "Get storage group from NeoFS",
RunE: getSG, Run: getSG,
} }
var sgListCmd = &cobra.Command{ var sgListCmd = &cobra.Command{
Use: "list", Use: "list",
Short: "List storage groups in NeoFS container", Short: "List storage groups in NeoFS container",
Long: "List storage groups in NeoFS container", Long: "List storage groups in NeoFS container",
RunE: listSG, Run: listSG,
} }
var sgDelCmd = &cobra.Command{ var sgDelCmd = &cobra.Command{
Use: "delete", Use: "delete",
Short: "Delete storage group from NeoFS", Short: "Delete storage group from NeoFS",
Long: "Delete storage group from NeoFS", Long: "Delete storage group from NeoFS",
RunE: delSG, Run: delSG,
} }
const ( const (
@ -127,15 +127,17 @@ func sgBearerToken(cmd *cobra.Command) (*token.BearerToken, error) {
return getBearerToken(cmd, sgBearerFlag) return getBearerToken(cmd, sgBearerFlag)
} }
func putSG(cmd *cobra.Command, _ []string) error { func putSG(cmd *cobra.Command, _ []string) {
ownerID, err := getOwnerID() ownerID, err := getOwnerID()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
cid, err := getCID(cmd) cid, err := getCID(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
members := make([]*objectSDK.ID, 0, len(sgMembers)) members := make([]*objectSDK.ID, 0, len(sgMembers))
@ -143,7 +145,8 @@ func putSG(cmd *cobra.Command, _ []string) error {
for i := range sgMembers { for i := range sgMembers {
id := objectSDK.NewID() id := objectSDK.NewID()
if err := id.Parse(sgMembers[i]); err != nil { if err := id.Parse(sgMembers[i]); err != nil {
return err cmd.PrintErrln(err)
return
} }
members = append(members, id) members = append(members, id)
@ -151,14 +154,16 @@ func putSG(cmd *cobra.Command, _ []string) error {
bearerToken, err := sgBearerToken(cmd) bearerToken, err := sgBearerToken(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx) cli, tok, err := initSession(ctx)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
sg, err := storagegroup.CollectMembers(&sgHeadReceiver{ sg, err := storagegroup.CollectMembers(&sgHeadReceiver{
@ -168,12 +173,14 @@ func putSG(cmd *cobra.Command, _ []string) error {
bearerToken: bearerToken, bearerToken: bearerToken,
}, cid, members) }, cid, members)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
sgContent, err := sg.Marshal() sgContent, err := sg.Marshal()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
obj := objectSDK.NewRaw() obj := objectSDK.NewRaw()
@ -191,13 +198,12 @@ func putSG(cmd *cobra.Command, _ []string) error {
)..., )...,
) )
if err != nil { if err != nil {
return fmt.Errorf("can't put storage group: %w", err) cmd.PrintErrln(fmt.Errorf("can't put storage group: %w", err))
return
} }
cmd.Println("Storage group successfully stored") cmd.Println("Storage group successfully stored")
cmd.Printf(" ID: %s\n CID: %s\n", oid, cid) cmd.Printf(" ID: %s\n CID: %s\n", oid, cid)
return nil
} }
func getSGID() (*objectSDK.ID, error) { func getSGID() (*objectSDK.ID, error) {
@ -207,20 +213,23 @@ func getSGID() (*objectSDK.ID, error) {
return oid, err return oid, err
} }
func getSG(cmd *cobra.Command, _ []string) error { func getSG(cmd *cobra.Command, _ []string) {
cid, err := getCID(cmd) cid, err := getCID(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
id, err := getSGID() id, err := getSGID()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
bearerToken, err := sgBearerToken(cmd) bearerToken, err := sgBearerToken(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
addr := objectSDK.NewAddress() addr := objectSDK.NewAddress()
@ -231,7 +240,8 @@ func getSG(cmd *cobra.Command, _ []string) error {
cli, tok, err := initSession(ctx) cli, tok, err := initSession(ctx)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
obj, err := cli.GetObject(ctx, obj, err := cli.GetObject(ctx,
@ -243,12 +253,14 @@ func getSG(cmd *cobra.Command, _ []string) error {
)..., )...,
) )
if err != nil { if err != nil {
return fmt.Errorf("can't get storage group: %w", err) cmd.PrintErrln(fmt.Errorf("can't get storage group: %w", err))
return
} }
sg := storagegroupAPI.New() sg := storagegroupAPI.New()
if err := sg.Unmarshal(obj.Payload()); err != nil { if err := sg.Unmarshal(obj.Payload()); err != nil {
return err cmd.PrintErrln(err)
return
} }
cmd.Printf("Expiration epoch: %d\n", sg.ExpirationEpoch()) cmd.Printf("Expiration epoch: %d\n", sg.ExpirationEpoch())
@ -262,26 +274,27 @@ func getSG(cmd *cobra.Command, _ []string) error {
cmd.Printf("\t%s\n", members[i]) cmd.Printf("\t%s\n", members[i])
} }
} }
return nil
} }
func listSG(cmd *cobra.Command, _ []string) error { func listSG(cmd *cobra.Command, _ []string) {
cid, err := getCID(cmd) cid, err := getCID(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
bearerToken, err := sgBearerToken(cmd) bearerToken, err := sgBearerToken(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx) cli, tok, err := initSession(ctx)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
ids, err := cli.SearchObject(ctx, ids, err := cli.SearchObject(ctx,
@ -294,7 +307,8 @@ func listSG(cmd *cobra.Command, _ []string) error {
)..., )...,
) )
if err != nil { if err != nil {
return fmt.Errorf("can't search storage groups: %w", err) cmd.PrintErrln(fmt.Errorf("can't search storage groups: %w", err))
return
} }
cmd.Printf("Found %d storage groups.\n", len(ids)) cmd.Printf("Found %d storage groups.\n", len(ids))
@ -302,31 +316,33 @@ func listSG(cmd *cobra.Command, _ []string) error {
for _, id := range ids { for _, id := range ids {
cmd.Println(id) cmd.Println(id)
} }
return nil
} }
func delSG(cmd *cobra.Command, _ []string) error { func delSG(cmd *cobra.Command, _ []string) {
cid, err := getCID(cmd) cid, err := getCID(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
id, err := getSGID() id, err := getSGID()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
bearerToken, err := sgBearerToken(cmd) bearerToken, err := sgBearerToken(cmd)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
ctx := context.Background() ctx := context.Background()
cli, tok, err := initSession(ctx) cli, tok, err := initSession(ctx)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
addr := objectSDK.NewAddress() addr := objectSDK.NewAddress()
@ -342,11 +358,10 @@ func delSG(cmd *cobra.Command, _ []string) error {
)..., )...,
) )
if err != nil { if err != nil {
return fmt.Errorf("can't get storage group: %w", err) cmd.PrintErrln(fmt.Errorf("can't get storage group: %w", err))
return
} }
cmd.Println("Storage group removed successfully.") cmd.Println("Storage group removed successfully.")
cmd.Printf(" Tombstone: %s\n", tombstone.ObjectID()) cmd.Printf(" Tombstone: %s\n", tombstone.ObjectID())
return nil
} }

View file

@ -38,13 +38,13 @@ var (
signBearerCmd = &cobra.Command{ signBearerCmd = &cobra.Command{
Use: "bearer-token", Use: "bearer-token",
Short: "Sign bearer token to use it in requests", Short: "Sign bearer token to use it in requests",
RunE: signBearerToken, Run: signBearerToken,
} }
signSessionCmd = &cobra.Command{ signSessionCmd = &cobra.Command{
Use: "session-token", Use: "session-token",
Short: "Sign session token to use it in requests", Short: "Sign session token to use it in requests",
RunE: signSessionToken, Run: signSessionToken,
} }
convertCmd = &cobra.Command{ convertCmd = &cobra.Command{
@ -55,13 +55,13 @@ var (
convertEACLCmd = &cobra.Command{ convertEACLCmd = &cobra.Command{
Use: "eacl", Use: "eacl",
Short: "Convert representation of extended ACL table", Short: "Convert representation of extended ACL table",
RunE: convertEACLTable, Run: convertEACLTable,
} }
keyerCmd = &cobra.Command{ keyerCmd = &cobra.Command{
Use: "keyer", Use: "keyer",
Short: "Generate or print information about keys", Short: "Generate or print information about keys",
RunE: processKeyer, Run: processKeyer,
} }
) )
@ -96,7 +96,7 @@ var (
locodeGenerateCmd = &cobra.Command{ locodeGenerateCmd = &cobra.Command{
Use: "generate", Use: "generate",
Short: "generate UN/LOCODE database for NeoFS", Short: "generate UN/LOCODE database for NeoFS",
RunE: func(cmd *cobra.Command, _ []string) error { Run: func(cmd *cobra.Command, _ []string) {
locodeDB := csvlocode.New( locodeDB := csvlocode.New(
csvlocode.Prm{ csvlocode.Prm{
Path: locodeGenerateInPaths[0], Path: locodeGenerateInPaths[0],
@ -120,7 +120,8 @@ var (
err := targetDB.Open() err := targetDB.Open()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
defer targetDB.Close() defer targetDB.Close()
@ -132,10 +133,9 @@ var (
err = locodedb.FillDatabase(locodeDB, airportDB, continentsDB, names, targetDB) err = locodedb.FillDatabase(locodeDB, airportDB, continentsDB, names, targetDB)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
return nil
}, },
} }
) )
@ -152,34 +152,34 @@ var (
locodeInfoCmd = &cobra.Command{ locodeInfoCmd = &cobra.Command{
Use: "info", Use: "info",
Short: "print information about UN/LOCODE from NeoFS database", Short: "print information about UN/LOCODE from NeoFS database",
RunE: func(cmd *cobra.Command, _ []string) error { Run: func(cmd *cobra.Command, _ []string) {
targetDB := locodebolt.New(locodebolt.Prm{ targetDB := locodebolt.New(locodebolt.Prm{
Path: locodeInfoDBPath, Path: locodeInfoDBPath,
}) })
err := targetDB.Open() err := targetDB.Open()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
defer targetDB.Close() defer targetDB.Close()
record, err := locodedb.LocodeRecord(targetDB, locodeInfoCode) record, err := locodedb.LocodeRecord(targetDB, locodeInfoCode)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
fmt.Printf("Country: %s\n", record.CountryName()) cmd.Printf("Country: %s\n", record.CountryName())
fmt.Printf("Location: %s\n", record.LocationName()) cmd.Printf("Location: %s\n", record.LocationName())
fmt.Printf("Continent: %s\n", record.Continent()) cmd.Printf("Continent: %s\n", record.Continent())
if subDivCode := record.SubDivCode(); subDivCode != "" { if subDivCode := record.SubDivCode(); subDivCode != "" {
fmt.Printf("Subdivision: [%s] %s\n", subDivCode, record.SubDivName()) cmd.Printf("Subdivision: [%s] %s\n", subDivCode, record.SubDivName())
} }
geoPoint := record.GeoPoint() geoPoint := record.GeoPoint()
fmt.Printf("Coordinates: %0.2f, %0.2f\n", geoPoint.Latitude(), geoPoint.Longitude()) cmd.Printf("Coordinates: %0.2f, %0.2f\n", geoPoint.Latitude(), geoPoint.Longitude())
return nil
}, },
} }
) )
@ -254,25 +254,29 @@ func init() {
_ = locodeGenerateCmd.MarkFlagRequired(locodeInfoCodeFlag) _ = locodeGenerateCmd.MarkFlagRequired(locodeInfoCodeFlag)
} }
func signBearerToken(cmd *cobra.Command, _ []string) error { func signBearerToken(cmd *cobra.Command, _ []string) {
btok, err := getBearerToken(cmd, "from") btok, err := getBearerToken(cmd, "from")
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
key, err := getKey() key, err := getKey()
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
err = completeBearerToken(btok) err = completeBearerToken(btok)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
err = btok.SignToken(key) err = btok.SignToken(key)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
to := cmd.Flag("to").Value.String() to := cmd.Flag("to").Value.String()
@ -282,113 +286,119 @@ func signBearerToken(cmd *cobra.Command, _ []string) error {
if jsonFlag || len(to) == 0 { if jsonFlag || len(to) == 0 {
data, err = btok.MarshalJSON() data, err = btok.MarshalJSON()
if err != nil { if err != nil {
return fmt.Errorf("can't JSON encode bearer token: %w", err) cmd.PrintErrln(fmt.Errorf("can't JSON encode bearer token: %w", err))
return
} }
} else { } else {
data, err = btok.Marshal() data, err = btok.Marshal()
if err != nil { if err != nil {
return fmt.Errorf("can't binary encode bearer token: %w", err) cmd.PrintErrln(fmt.Errorf("can't binary encode bearer token: %w", err))
return
} }
} }
if len(to) == 0 { if len(to) == 0 {
prettyPrintJSON(cmd, data) prettyPrintJSON(cmd, data)
return nil return
} }
err = ioutil.WriteFile(to, data, 0644) err = ioutil.WriteFile(to, data, 0644)
if err != nil { if err != nil {
return fmt.Errorf("can't write signed bearer token to file: %w", err) cmd.PrintErrln(fmt.Errorf("can't write signed bearer token to file: %w", err))
return
} }
cmd.Printf("signed bearer token was successfully dumped to %s\n", to) cmd.Printf("signed bearer token was successfully dumped to %s\n", to)
return nil
} }
func signSessionToken(cmd *cobra.Command, _ []string) error { func signSessionToken(cmd *cobra.Command, _ []string) {
path, err := cmd.Flags().GetString("from") path, err := cmd.Flags().GetString("from")
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
stok, err := getSessionToken(path) stok, err := getSessionToken(path)
if err != nil { if err != nil {
return fmt.Errorf("can't read session token from %s: %w", path, err) cmd.PrintErrln(fmt.Errorf("can't read session token from %s: %w", path, err))
return
} }
key, err := getKey() key, err := getKey()
if err != nil { if err != nil {
return fmt.Errorf("can't get private key, make sure it is provided: %w", err) cmd.PrintErrln(fmt.Errorf("can't get private key, make sure it is provided: %w", err))
return
} }
err = stok.Sign(key) err = stok.Sign(key)
if err != nil { if err != nil {
return fmt.Errorf("can't sign token: %w", err) cmd.PrintErrln(fmt.Errorf("can't sign token: %w", err))
return
} }
data, err := stok.MarshalJSON() data, err := stok.MarshalJSON()
if err != nil { if err != nil {
return fmt.Errorf("can't encode session token: %w", err) cmd.PrintErrln(fmt.Errorf("can't encode session token: %w", err))
return
} }
to := cmd.Flag("to").Value.String() to := cmd.Flag("to").Value.String()
if len(to) == 0 { if len(to) == 0 {
prettyPrintJSON(cmd, data) prettyPrintJSON(cmd, data)
return nil return
} }
err = ioutil.WriteFile(to, data, 0644) err = ioutil.WriteFile(to, data, 0644)
if err != nil { if err != nil {
return fmt.Errorf("can't write signed session token to %s: %w", to, err) cmd.PrintErrln(fmt.Errorf("can't write signed session token to %s: %w", to, err))
return
} }
fmt.Printf("signed session token saved in %s\n", to) cmd.Printf("signed session token saved in %s\n", to)
return nil
} }
func convertEACLTable(cmd *cobra.Command, _ []string) error { func convertEACLTable(cmd *cobra.Command, _ []string) {
pathFrom := cmd.Flag("from").Value.String() pathFrom := cmd.Flag("from").Value.String()
to := cmd.Flag("to").Value.String() to := cmd.Flag("to").Value.String()
jsonFlag, _ := cmd.Flags().GetBool("json") jsonFlag, _ := cmd.Flags().GetBool("json")
table, err := parseEACL(pathFrom) table, err := parseEACL(pathFrom)
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
var data []byte var data []byte
if jsonFlag || len(to) == 0 { if jsonFlag || len(to) == 0 {
data, err = table.MarshalJSON() data, err = table.MarshalJSON()
if err != nil { if err != nil {
return fmt.Errorf("can't JSON encode extended ACL table: %w", err) cmd.PrintErrln(fmt.Errorf("can't JSON encode extended ACL table: %w", err))
return
} }
} else { } else {
data, err = table.Marshal() data, err = table.Marshal()
if err != nil { if err != nil {
return fmt.Errorf("can't binary encode extended ACL table: %w", err) cmd.PrintErrln(fmt.Errorf("can't binary encode extended ACL table: %w", err))
return
} }
} }
if len(to) == 0 { if len(to) == 0 {
prettyPrintJSON(cmd, data) prettyPrintJSON(cmd, data)
return
return nil
} }
err = ioutil.WriteFile(to, data, 0644) err = ioutil.WriteFile(to, data, 0644)
if err != nil { if err != nil {
return fmt.Errorf("can't write exteded ACL table to file: %w", err) cmd.PrintErrln(fmt.Errorf("can't write exteded ACL table to file: %w", err))
return
} }
cmd.Printf("extended ACL table was successfully dumped to %s\n", to) cmd.Printf("extended ACL table was successfully dumped to %s\n", to)
return nil
} }
func processKeyer(cmd *cobra.Command, args []string) error { func processKeyer(cmd *cobra.Command, args []string) {
var ( var (
err error err error
@ -403,7 +413,8 @@ func processKeyer(cmd *cobra.Command, args []string) error {
err = result.ParseMultiSig(args) err = result.ParseMultiSig(args)
} else { } else {
if len(args) > 1 { if len(args) > 1 {
return errKeyerSingleArgument cmd.PrintErrln(errKeyerSingleArgument)
return
} }
var argument string var argument string
@ -422,12 +433,11 @@ func processKeyer(cmd *cobra.Command, args []string) error {
} }
if err != nil { if err != nil {
return err cmd.PrintErrln(err)
return
} }
result.PrettyPrint(uncompressed, useHex) result.PrettyPrint(uncompressed, useHex)
return nil
} }
func completeBearerToken(btok *token.BearerToken) error { func completeBearerToken(btok *token.BearerToken) error {