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