github.com/pachyderm/pachyderm@v1.13.4/src/server/transaction/cmds/util.go (about) 1 package cmds 2 3 import ( 4 "fmt" 5 "os" 6 7 "github.com/pachyderm/pachyderm/src/client" 8 "github.com/pachyderm/pachyderm/src/client/pkg/config" 9 "github.com/pachyderm/pachyderm/src/client/pkg/errors" 10 "github.com/pachyderm/pachyderm/src/client/transaction" 11 ) 12 13 // getActiveTransaction will read the active transaction from the config file 14 // (if it exists) and return it. If the config file is uninitialized or the 15 // active transaction is unset, `nil` will be returned. 16 func getActiveTransaction() (*transaction.Transaction, error) { 17 cfg, err := config.Read(false, false) 18 if err != nil { 19 return nil, errors.Wrapf(err, "error reading Pachyderm config") 20 } 21 _, context, err := cfg.ActiveContext(true) 22 if err != nil { 23 return nil, errors.Wrapf(err, "error getting the active context") 24 } 25 if context.ActiveTransaction == "" { 26 return nil, nil 27 } 28 return &transaction.Transaction{ID: context.ActiveTransaction}, nil 29 } 30 31 func requireActiveTransaction() (*transaction.Transaction, error) { 32 txn, err := getActiveTransaction() 33 if err != nil { 34 return nil, err 35 } else if txn == nil { 36 return nil, errors.Errorf("no active transaction") 37 } 38 return txn, nil 39 } 40 41 func setActiveTransaction(txn *transaction.Transaction) error { 42 cfg, err := config.Read(false, false) 43 if err != nil { 44 return errors.Wrapf(err, "error reading Pachyderm config") 45 } 46 _, context, err := cfg.ActiveContext(true) 47 if err != nil { 48 return errors.Wrapf(err, "error getting the active context") 49 } 50 if txn == nil { 51 context.ActiveTransaction = "" 52 } else { 53 context.ActiveTransaction = txn.ID 54 } 55 if err := cfg.Write(); err != nil { 56 return errors.Wrapf(err, "error writing Pachyderm config") 57 } 58 return nil 59 } 60 61 // ClearActiveTransaction will remove the active transaction from the pachctl 62 // config file - used by the 'delete all' command. 63 func ClearActiveTransaction() error { 64 return setActiveTransaction(nil) 65 } 66 67 // WithActiveTransaction is a helper function that will attach the given 68 // transaction to the given client (resulting in a new client), then run the 69 // given callback with the new client. This is for executing RPCs that can be 70 // run inside a transaction - if this isn't supported, it will have no effect. 71 func WithActiveTransaction(c *client.APIClient, callback func(*client.APIClient) error) error { 72 txn, err := getActiveTransaction() 73 if err != nil { 74 return err 75 } 76 if txn != nil { 77 c = c.WithTransaction(txn) 78 } 79 err = callback(c) 80 if err == nil && txn != nil { 81 fmt.Fprintf(os.Stdout, "Added to transaction: %s\n", txn.ID) 82 } 83 return err 84 }