-
Notifications
You must be signed in to change notification settings - Fork 152
/
custom_billing_download.go
239 lines (208 loc) · 5.57 KB
/
custom_billing_download.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package billing
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"strings"
"time"
"github.com/fatih/color"
"github.com/scaleway/scaleway-cli/v2/internal/core"
"github.com/scaleway/scaleway-cli/v2/internal/interactive"
"github.com/scaleway/scaleway-cli/v2/internal/terminal"
billing "github.com/scaleway/scaleway-sdk-go/api/billing/v2alpha1"
)
const (
invoiceDefaultPrefix = "scaleway-invoice"
)
type billingDownloadRequest struct {
billing.DownloadInvoiceRequest
// extra arguments
FilePath string
ForceReplace bool
}
func fileNameWithoutExtTrimSuffix(fileName string) string {
return strings.TrimSuffix(fileName, filepath.Ext(fileName))
}
func buildDownloadCommand(command *core.Command) *core.Command {
command.ArgsType = reflect.TypeOf(billingDownloadRequest{})
command.ArgSpecs = core.ArgSpecs{
{
Name: "invoice-id",
Short: `Invoice ID`,
Required: true,
Deprecated: false,
Positional: false,
},
{
Name: "file-path",
Short: `Wanted file path`,
Required: false,
Deprecated: false,
Positional: false,
Default: core.DefaultValueSetter("./"),
},
{
Name: "file-type",
Short: `Wanted file extension`,
Required: false,
Deprecated: false,
Positional: false,
Default: core.DefaultValueSetter(billing.DownloadInvoiceRequestFileTypePdf.String()),
},
{
Name: "force-replace",
Short: `Force file replacement`,
Required: false,
Deprecated: false,
Positional: false,
Default: core.DefaultValueSetter("false"),
},
}
command.Run = billingDownloadRun
command.PreValidateFunc = func(ctx context.Context, argsI interface{}) error {
args := argsI.(*billingDownloadRequest)
askPrompt := false
request := &billing.DownloadInvoiceRequest{
InvoiceID: args.InvoiceID,
FileType: args.FileType,
}
client := core.ExtractClient(ctx)
billingAPI := billing.NewAPI(client)
resp, err := billingAPI.DownloadInvoice(request)
if err != nil {
return err
}
date, err := trimDateFromFileName(resp.Name)
if err != nil {
return fmt.Errorf("parse date on file name")
}
dir, file := getDirFile(args.FilePath)
if len(file) > 0 {
fileExtension := filepath.Ext(file)
if extensionOnFile := checkInvoiceExt(fileExtension); !extensionOnFile {
return fmt.Errorf("file has not supported extension")
}
}
entries, err := os.ReadDir(dir)
if err != nil {
return err
}
if args.ForceReplace {
return nil
}
// check default name
defaultFileName := fmt.Sprintf("%s-%s-%s.%s", invoiceDefaultPrefix, date, args.InvoiceID, args.FileType)
// read only in the parent path
for _, e := range entries {
if e.IsDir() {
continue
}
// case default name on directory
if len(file) == 0 && e.Name() == defaultFileName {
file = defaultFileName
askPrompt = true
}
if file == e.Name() {
askPrompt = true
}
}
if askPrompt {
_, _ = interactive.PrintlnWithoutIndent(`
Current file exist is located at ` + terminal.Style(args.FilePath, color.Faint))
overrideFile, err := interactive.PromptBoolWithConfig(&interactive.PromptBoolConfig{
Prompt: fmt.Sprintf("Do you want to override the current file: %s ?", file),
DefaultValue: false,
Ctx: ctx,
})
if err != nil {
return err
}
if !overrideFile {
return fmt.Errorf("download file canceled")
}
}
return nil
}
return command
}
func getDirFile(filePath string) (string, string) {
dir := "."
dirTmp, file := filepath.Split(filePath)
if len(dirTmp) > 0 {
dir = dirTmp
}
if file == "." {
file = ""
}
return dir, file
}
func addExt(fileName, contentType string) string {
switch contentType {
case "application/pdf":
fileName = fmt.Sprintf("%s.pdf", fileName)
}
return fileName
}
func checkInvoiceExt(ext string) bool {
switch ext {
case ".pdf":
return true
}
return false
}
func billingDownloadRun(ctx context.Context, argsI interface{}) (interface{}, error) {
argsDownload := argsI.(*billingDownloadRequest)
request := &billing.DownloadInvoiceRequest{
InvoiceID: argsDownload.InvoiceID,
FileType: argsDownload.FileType,
}
client := core.ExtractClient(ctx)
billingAPI := billing.NewAPI(client)
resp, err := billingAPI.DownloadInvoice(request)
if err != nil {
return nil, err
}
fileName := fileNameWithoutExtTrimSuffix(argsDownload.FilePath)
// check file path argument
fInfo, err := os.Stat(argsDownload.FilePath)
if err == nil {
if fInfo.IsDir() {
// case when filepath is a directory: join default name with custom path
date, err := trimDateFromFileName(resp.Name)
if err != nil {
return nil, fmt.Errorf("parse date on file name")
}
defaultFileName := fmt.Sprintf("%s-%s-%s", invoiceDefaultPrefix, date, argsDownload.InvoiceID)
pathAbs, err := filepath.Abs(argsDownload.FilePath)
if err != nil {
return nil, err
}
fileName = filepath.Join(pathAbs, defaultFileName)
}
}
// add supported extension
fileName = addExt(fileName, resp.ContentType)
fileOutput, err := os.Create(fileName)
if err != nil {
dir, file := getDirFile(fileName)
return nil, fmt.Errorf("unavailable to create file %s on directory %s", file, dir)
}
defer fileOutput.Close()
_, err = io.Copy(fileOutput, resp.Content)
if err != nil {
return nil, err
}
return &core.SuccessResult{Empty: true}, nil
}
func trimDateFromFileName(filename string) (string, error) {
formatLayout := "2006-01"
m := strings.Split(filename, "-")
d, err := time.Parse(formatLayout, fmt.Sprintf("%s-%s", m[1], m[2]))
if err != nil {
return "", err
}
return d.Format(formatLayout), nil
}