/
export_cmd.go
96 lines (90 loc) · 2.12 KB
/
export_cmd.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// SPDX-License-Identifier: Apache-2.0
// Copyright © 2022 Wrangle Ltd
package wrgl
import (
"encoding/csv"
"strings"
"github.com/spf13/cobra"
"github.com/wrgl/wrgl/cmd/wrgl/utils"
"github.com/wrgl/wrgl/pkg/objects"
"github.com/wrgl/wrgl/pkg/ref"
)
func newExportCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "export COMMIT",
Short: "Print commit content as CSV",
Args: cobra.ExactArgs(1),
Example: strings.Join([]string{
` # export latest commit to CSV file`,
` wrgl export my-branch > my_branch.csv`,
"",
` # export commit to CSV file`,
` wrgl export 1a2ed6248c7243cdaaecb98ac12213a7 > my_data.csv`,
}, "\n"),
RunE: func(cmd *cobra.Command, args []string) error {
cStr := args[0]
return exportCommit(cmd, cStr)
},
}
cmd.Flags().String("delimiter", "", "CSV delimiter. Defaults to comma.")
cmd.Flags().String("txid", "", "export commit with specified transaction id. COMMIT must be a branch name.")
return cmd
}
func exportCommit(cmd *cobra.Command, cStr string) error {
rd := utils.GetRepoDir(cmd)
defer rd.Close()
if err := quitIfRepoDirNotExist(cmd, rd); err != nil {
return err
}
db, err := rd.OpenObjectsStore()
if err != nil {
return err
}
defer db.Close()
rs := rd.OpenRefStore()
txid, err := cmd.Flags().GetString("txid")
if err != nil {
return err
}
var commit *objects.Commit
if txid != "" {
_, commit, err = getCommitWithTxid(db, rs, txid, cStr)
} else {
_, _, commit, err = ref.InterpretCommitName(db, rs, cStr, false)
}
if err != nil {
return err
}
tbl, err := utils.GetTable(db, rs, commit)
if err != nil {
return err
}
delim, err := utils.GetRuneFromFlag(cmd, "delimiter")
if err != nil {
return err
}
writer := csv.NewWriter(cmd.OutOrStdout())
if delim != 0 {
writer.Comma = delim
}
err = writer.Write(tbl.Columns)
if err != nil {
return err
}
var buf []byte
var blk [][]string
for _, sum := range tbl.Blocks {
blk, buf, err = objects.GetBlock(db, buf, sum)
if err != nil {
return err
}
for _, row := range blk {
err = writer.Write(row)
if err != nil {
return err
}
}
}
writer.Flush()
return writer.Error()
}