-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtres.go
executable file
·921 lines (847 loc) · 25 KB
/
tres.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
package tres
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"github.com/tealeg/xlsx"
)
type TrelloName struct {
ID string `json:"id"`
Name string `json:"name"`
}
type TrelloNameList []*TrelloName
type Config struct {
ShowUsage bool
Command string
SearchResultFields string
ColSep string
RowSep string
QuoteChar string
CardLimit int
NumberOutput bool
Format string
BoardName string
ListName string
}
type TrelloClient struct {
TrelloKey string
TrelloToken string
HTTPClient *http.Client
TrelloBoards TrelloNameList
TrelloLists map[string]TrelloNameList
config *Config
}
// NewTrelloClient allocates new TrelloClient and reads environment variables.
func NewTrelloClient(c *Config) *TrelloClient {
client := &TrelloClient{
HTTPClient: &http.Client{},
TrelloLists: make(map[string]TrelloNameList),
config: c,
}
key := os.ExpandEnv("$TRELLO_KEY")
if key == "" {
fmt.Println("TRELLO_KEY environment variable not set, exiting.")
os.Exit(1)
} else {
client.TrelloKey = key
}
tok := os.ExpandEnv("$TRELLO_TOKEN")
if key == "" {
fmt.Println("TRELLO_TOKEN environment variable not set, exiting.")
os.Exit(1)
} else {
client.TrelloToken = tok
}
return client
}
type TrelloBadges struct {
Attachments int `json:"attachments"`
CheckItems int `json:"checkItems"`
CheckItemsChecked int `json:"checkItemsChecked"`
Comments int `json:"comments"`
Description bool `json:"description"`
Due string `json:"due"`
Fogbugz string `json:"fogbugz"`
Subscribed bool `json:"subscribed"`
ViewingMemberVoted bool `json:"viewingMemberVoted"`
Votes int `json:"votes"`
}
type TrelloLabel struct {
Color string `json:"color"`
ID string `json:"id"`
IDBoard string `json:"idBoard"`
Name string `json:"name"`
Uses int `json:"uses"`
}
type TrelloCardSearchResult struct {
ID string `json:"id"`
Badges *TrelloBadges `json:"badges"`
CheckItemStates []*struct {
IDCheckItem string `json:"idCheckItem"`
State string `json:"state"`
} `json:"checkItemStates"`
Closed bool `json:"closed"`
DateLastActivity string `json:"dateLastActivity"`
Desc string `json:"desc"`
DescData interface{} `json:"descData"`
Due string `json:"due"`
Email string `json:"email"`
IDAttachmentCover string `json:"idAttachmentCover"`
IDBoard string `json:"idBoard"`
IDChecklists []string `json:"idChecklists"`
IDLabels []string `json:"idLabels"`
IDList string `json:"idList"`
IDMembers []string `json:"idMembers"`
IDMembersVoted []string `json:"idMembersVoted"`
IDShort int `json:"idShort"`
Labels []*TrelloLabel `json:"labels"`
ManualCoverAttachment bool `json:"manualCoverAttachment"`
Name string `json:"name"`
Pos float64 `json:"pos"`
ShortLink string `json:"shortLink"`
ShortURL string `json:"shortUrl"`
Subscribed bool `json:"subscribed"`
URL string `json:"url "`
}
type TrelloSearchResult struct {
Cards []*TrelloCardSearchResult `json:"cards"`
Options interface{}
}
type TrelloCardComment struct {
Type string `json:"type"`
Date string `json:"date"`
IDComment string `json:"id"`
IDMemberCreator string `json:"idMemberCreator"`
Data struct {
Board struct {
IDBoard string `json:"id"`
BoardName string `json:"name"`
ShortLink string `json:"shortLink"`
} `json:"board"`
Card struct {
IDCard string `json:"id"`
CardName string `json:"name"`
IDShort int64 `json:"idShort"`
ShortLink string `json:"shortLink"`
} `json:"card"`
List struct {
IDList string `json:"id"`
ListName string `json:"name"`
} `json:"list"`
Text string `json:"text"`
} `json:"data"`
MemberCreator struct {
AvatarHash string `json:"avatarHash"`
FullName string `json:"fullName"`
IDMember string `json:"id"`
Initials string `json:"initials"`
UserName string `json:"username"`
} `json:"memberCreator"`
}
type TrelloChecklist struct {
IDChecklist string `json:"id"`
IDBoard string `json:"idBoard"`
IDCard string `json:"idCard"`
Name string `json:"name"`
Position float64 `json:"pos"`
CheckItems []struct {
ID string `json:"id"`
Name string `json:"name"`
NameData interface{} `json:"nameData"`
Pos float64 `json:"pos"`
State string `json:"state"`
} `json:"checkItems"`
}
type TrelloMember struct {
AvatarHash string `json:"avatarHash"`
Bio string `json:"bio"`
BioData interface{} `json:"bioData"`
Confirmed bool `json:"confirmed"`
FullName string `json:"fullName"`
IDMember string `json:"id"`
IDPremOrgsAdmin interface{} `json:"idPremOrgsAdmin"`
Initials string `json:"initials"`
MemberType string `json:"memberType"`
Products []int `json:"products"`
Status string `json:"status"`
URL string `json:"url"`
UserName string `json:"username"`
}
type TrelloList struct {
IDList string `json:"id"`
ListName string `json:"name"`
Closed bool `json:"closed"`
IDBoard string `json:"idBoard"`
Position float64 `json:"pos"`
}
func IDFromName(name string, nameList TrelloNameList) string {
for _, v := range nameList {
if strings.ToUpper(v.Name) == strings.ToUpper(name) {
return v.ID
}
}
return ""
}
func NameFromID(theID string, nameList TrelloNameList) string {
for _, v := range nameList {
if v.ID == theID {
return v.Name
}
}
return ""
}
func (client *TrelloClient) prepareQuery(path string, query map[string]string) *url.URL {
theURL := &url.URL{}
theURL.Scheme = "https"
theURL.Host = "api.trello.com"
theURL.Path = path
if query != nil {
q := theURL.Query()
for key, value := range query {
q.Set(key, value)
}
q.Set("key", client.TrelloKey)
q.Set("token", client.TrelloToken)
theURL.RawQuery = q.Encode()
}
return theURL
}
func processResponse(resp *http.Response, err error, result interface{}) error {
if err != nil {
return err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return errors.New("HTTP Status " + resp.Status)
}
data, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return err
}
err = json.Unmarshal(data, &result)
return err
}
func (client *TrelloClient) TrelloNamesFromURL(theURL string) (TrelloNameList, error) {
result := TrelloNameList{}
resp, err := client.HTTPClient.Get(theURL)
err = processResponse(resp, err, &result)
return result, err
}
func (client *TrelloClient) ListNames(boardID string) (TrelloNameList, error) {
q := map[string]string{
"fields": "name",
}
theURL := client.prepareQuery("/1/boards/"+strings.TrimSpace(boardID)+"/lists", q)
return client.TrelloNamesFromURL(theURL.String())
}
func (client *TrelloClient) BoardNames(memberID string) (TrelloNameList, error) {
q := map[string]string{
"fields": "name",
}
theURL := client.prepareQuery("/1/members/"+strings.TrimSpace(memberID)+"/boards", q)
return client.TrelloNamesFromURL(theURL.String())
}
func (client *TrelloClient) LabelNames(boardID string) (TrelloNameList, error) {
q := map[string]string{
"fields": "name",
}
theURL := client.prepareQuery("/1/boards/"+strings.TrimSpace(boardID)+"/labels", q)
return client.TrelloNamesFromURL(theURL.String())
}
func (client *TrelloClient) CreateList(boardID, listName, position string) (*TrelloList, error) {
theURL := client.prepareQuery("/1/board/"+strings.TrimSpace(boardID)+"/lists", nil)
postData := fmt.Sprintf(`{"key": "%s", "token": "%s", "name": "%s", "pos": "%s"}`, client.TrelloKey, client.TrelloToken, listName, position)
req, err := http.NewRequest("POST", theURL.String(), bytes.NewReader([]byte(postData)))
req.Header.Set("Content-Type", "application/json")
resp, err := client.HTTPClient.Do(req)
result := &TrelloList{}
err = processResponse(resp, err, &result)
return result, err
}
func (client *TrelloClient) FetchBoardMembers(boardID string) ([]*TrelloMember, error) {
q := map[string]string{
"fields": "all",
}
theURL := client.prepareQuery("/1/board/"+strings.TrimSpace(boardID)+"/members", q)
result := []*TrelloMember{}
resp, err := client.HTTPClient.Get(theURL.String())
err = processResponse(resp, err, &result)
return result, err
}
func (client *TrelloClient) CardComments(cardID string) ([]*TrelloCardComment, error) {
q := map[string]string{
"filter": "commentCard",
}
theURL := client.prepareQuery("/1/card/"+strings.TrimSpace(cardID)+"/actions", q)
result := []*TrelloCardComment{}
resp, err := client.HTTPClient.Get(theURL.String())
err = processResponse(resp, err, &result)
return result, err
}
func (client *TrelloClient) CardChecklists(cardID string) ([]*TrelloChecklist, error) {
q := map[string]string{
"fields": "name,idBoard,idCard",
}
theURL := client.prepareQuery("/1/card/"+strings.TrimSpace(cardID)+"/checklists", q)
result := []*TrelloChecklist{}
resp, err := client.HTTPClient.Get(theURL.String())
err = processResponse(resp, err, &result)
return result, err
}
func (client *TrelloClient) SearchCards(query string, limit int) ([]*TrelloCardSearchResult, error) {
q := map[string]string{
"modelTypes": "cards",
"card_fields": "all",
"cards_limit": strconv.Itoa(limit),
"query": query,
}
theURL := client.prepareQuery("/1/search", q)
result := TrelloSearchResult{}
resp, err := client.HTTPClient.Get(theURL.String())
err = processResponse(resp, err, &result)
return result.Cards, err
}
func (client *TrelloClient) FetchBoardInfo() error {
var err error
trelloUser := os.ExpandEnv("$TRELLO_USER")
if trelloUser == "" {
trelloUser = "me" // default to "me" then
}
client.TrelloBoards, err = client.BoardNames(trelloUser)
if err != nil {
return err
}
for _, v := range client.TrelloBoards {
boardName := strings.ToLower(v.Name)
client.TrelloLists[boardName] = TrelloNameList{}
tmp, err := client.ListNames(v.ID)
if err != nil {
return err
}
for _, v := range tmp {
client.TrelloLists[boardName] = append(client.TrelloLists[boardName], v)
}
}
return nil
}
func (client *TrelloClient) buildOutputLine(card *TrelloCardSearchResult) []string {
list := strings.Split(client.config.SearchResultFields, ",")
result := []string{}
for _, v := range list {
var item string
v = strings.TrimSpace(strings.ToLower(v))
switch v {
case "id":
item = card.ID
case "attachmentcount":
item = strconv.Itoa(card.Badges.Attachments)
case "checked":
item = strconv.Itoa(card.Badges.CheckItemsChecked) + "/" + strconv.Itoa(card.Badges.CheckItems)
case "commentcount":
item = strconv.Itoa(card.Badges.Comments)
case "hasdesc":
item = strconv.FormatBool(card.Badges.Description)
case "closed":
item = strconv.FormatBool(card.Closed)
case "datelastactivity":
item = card.DateLastActivity
case "desc":
item = card.Desc
case "due":
item = card.Due
case "email":
item = card.Email
case "idattachmentcover":
item = card.IDAttachmentCover
case "idboard":
item = card.IDBoard
case "labels":
labels := []string{}
for _, v := range card.Labels {
s := v.Name
if s == "" {
s = strings.ToUpper(v.Color)
}
labels = append(labels, "["+s+"]")
}
item = strings.Join(labels, " ")
case "labelcolors":
labels := []string{}
for _, v := range card.Labels {
s := v.Color
s = strings.ToUpper(v.Color)
labels = append(labels, "["+s+"]")
}
item = strings.Join(labels, " ")
case "idlist":
item = card.IDList
case "listname":
s := NameFromID(card.IDBoard, client.TrelloBoards)
if s != "" {
s = strings.ToLower(s)
s = NameFromID(card.IDList, client.TrelloLists[s])
}
item = s
case "boardname":
item = NameFromID(card.IDBoard, client.TrelloBoards)
case "idshort":
item = strconv.Itoa(card.IDShort)
case "name":
item = card.Name
case "pos":
item = strconv.FormatFloat(card.Pos, 'g', 2, 64)
case "shortlink":
item = card.ShortLink
case "shorturl":
item = card.ShortURL
case "subscribed":
item = strconv.FormatBool(card.Subscribed)
case "comments":
item = ""
if card.Badges.Comments > 0 {
comments, err := client.CardComments(card.ID)
if err == nil {
for _, comment := range comments {
item += "@" + comment.MemberCreator.UserName + " on " + comment.Date + ": " + strings.Replace(comment.Data.Text, "\n", "\\n", -1) + "\n"
}
} else {
item = "[Could not read comments for card] " + err.Error()
}
}
case "url":
item = card.URL
}
if client.config.QuoteChar != "" {
item = client.config.QuoteChar + item + client.config.QuoteChar
}
result = append(result, item)
}
return result
}
func (client *TrelloClient) formatterText(cards []*TrelloCardSearchResult) error {
var err error
fmt.Printf("Found %d cards\n", len(cards))
fmt.Println()
header := strings.Split(client.config.SearchResultFields, ",")
for i, card := range cards {
if client.config.NumberOutput {
fmt.Printf("%4d ", i)
}
cols := client.buildOutputLine(card)
for i := range header {
fmt.Printf("%-25s: ", strings.Title(header[i]))
if strings.ToLower(header[i]) == "comments" { // do a break before comments
fmt.Println()
}
fmt.Println(cols[i])
}
if card.Badges.CheckItems > 0 {
chklists, err := client.CardChecklists(card.ID)
if err != nil {
fmt.Println("[Could not read checklist items for card] ", err.Error())
} else {
fmt.Println("Checklists")
for _, chklist := range chklists {
fmt.Println(chklist.Name)
for i, v := range chklist.CheckItems {
s := fmt.Sprintf("%2d: %s ", i+1, v.Name)
if v.State == "complete" {
s += " ✅ (done)"
}
fmt.Println(s)
}
}
fmt.Println()
}
}
fmt.Println("--------")
}
return err
}
func (client *TrelloClient) formatterCsv(cards []*TrelloCardSearchResult) error {
var err error
header := strings.Join(strings.Split(client.config.SearchResultFields, ","), client.config.ColSep)
fmt.Println(header)
for _, card := range cards {
card.Desc = strings.Replace(card.Desc, "\n", "\\n", -1)
colbuf := client.buildOutputLine(card)
fmt.Print(strings.Join(colbuf, client.config.ColSep))
fmt.Print(client.config.RowSep)
}
return err
}
func (client *TrelloClient) formatterJSON(cards []*TrelloCardSearchResult) error {
var err error
doc := []byte{}
doc, err = json.Marshal(cards)
if err == nil {
fmt.Print(string(doc))
fmt.Print(client.config.RowSep)
}
return err
}
func (client *TrelloClient) formatterExcel(cards []*TrelloCardSearchResult) (err error) {
var (
file *xlsx.File
sheet *xlsx.Sheet
row *xlsx.Row
cell *xlsx.Cell
)
client.config.QuoteChar = "" // we do not need quoting in excel
file = xlsx.NewFile()
if sheet, err = file.AddSheet("Sheet1"); err != nil {
return
}
for _, card := range cards {
row = sheet.AddRow()
for _, column := range client.buildOutputLine(card) {
cell = row.AddCell()
cell.Value = column
}
}
if err != nil {
fmt.Printf(err.Error())
}
err = file.Write(os.Stdout)
if err != nil {
fmt.Printf(err.Error())
}
return err
}
func (client *TrelloClient) formatterMarkdown(cards []*TrelloCardSearchResult) error {
var err error
for _, card := range cards {
linebuf := []string{}
linebuf = append(linebuf, "# "+strings.TrimSpace(card.Name))
s := ""
for _, label := range card.Labels {
if label.Name == "" {
label.Name = "[" + strings.ToUpper(label.Color) + "]"
}
s += "<span style=\"background-color: " + label.Color + ";\">" + label.Name + "</span> "
}
linebuf = append(linebuf, s)
linebuf = append(linebuf, "")
linebuf = append(linebuf, "## Description")
linebuf = append(linebuf, card.Desc)
if card.Badges.Comments > 0 {
comments, err := client.CardComments(card.ID)
if err == nil {
linebuf = append(linebuf, "")
linebuf = append(linebuf, "## Card Comments")
for _, comment := range comments {
linebuf = append(linebuf, "")
linebuf = append(linebuf, "### "+comment.Date+" from @"+comment.MemberCreator.UserName)
linebuf = append(linebuf, "")
linebuf = append(linebuf, comment.Data.Text)
linebuf = append(linebuf, "")
}
} else {
linebuf = append(linebuf, "[Could not read comments for card] ", err.Error())
}
}
if card.Badges.CheckItems > 0 {
chklists, err := client.CardChecklists(card.ID)
if err != nil {
linebuf = append(linebuf, "[Could not read checklist items for card] ", err.Error())
} else {
linebuf = append(linebuf, "")
linebuf = append(linebuf, "## Checklists")
for _, chklist := range chklists {
linebuf = append(linebuf, "### "+chklist.Name)
for _, v := range chklist.CheckItems {
s := " 1. " + v.Name
if v.State == "complete" {
s += " ✅ (done)"
}
linebuf = append(linebuf, s)
}
}
linebuf = append(linebuf, "")
}
}
linebuf = append(linebuf, "## Card Info")
linebuf = append(linebuf, " * last activity on "+card.DateLastActivity)
if card.Due != "" {
linebuf = append(linebuf, " * due on "+card.Due)
}
linebuf = append(linebuf, " * card shortUrl ["+card.ShortURL+"]("+card.ShortURL+")")
boardName := NameFromID(card.IDBoard, client.TrelloBoards)
linebuf = append(linebuf, " * board "+boardName)
linebuf = append(linebuf, " * list "+NameFromID(card.IDList, client.TrelloLists[strings.ToLower(boardName)]))
linebuf = append(linebuf, "")
linebuf = append(linebuf, "")
fmt.Print(strings.Join(linebuf, "\n"))
fmt.Print(client.config.RowSep)
}
return err
}
func (client *TrelloClient) buildMemberSlice(member *TrelloMember) []string {
list := strings.Split(client.config.SearchResultFields, ",")
result := []string{}
for _, v := range list {
var item string
v = strings.TrimSpace(strings.ToLower(v))
switch v {
case "id":
item = member.IDMember
case "url":
item = member.URL
case "avatarhash":
item = member.AvatarHash
case "bio":
item = strings.Replace(member.Bio, "\n", "\\n", -1)
case "confirmed":
item = strconv.FormatBool(member.Confirmed)
case "fullname":
item = member.FullName
case "idmember":
item = member.IDMember
case "initials":
item = member.Initials
case "membertype":
item = member.MemberType
case "status":
item = member.Status
case "name":
item = member.UserName
}
if client.config.QuoteChar != "" {
item = client.config.QuoteChar + item + client.config.QuoteChar
}
result = append(result, item)
}
return result
}
func (client *TrelloClient) memberFormatterJSON(members []*TrelloMember) error {
var err error
doc := []byte{}
doc, err = json.Marshal(members)
if err == nil {
fmt.Print(string(doc))
fmt.Print(client.config.RowSep)
}
return err
}
func (client *TrelloClient) memberFormatterText(members []*TrelloMember) error {
var err error
header := strings.Split(client.config.SearchResultFields, ",")
fmt.Println(header)
for _, member := range members {
colbuf := client.buildMemberSlice(member)
for i := 0; i < len(header); i++ {
fmt.Printf("%-20s : %s\n", header[i], colbuf[i])
}
fmt.Print("--------")
fmt.Print(client.config.RowSep)
}
return err
}
func (client *TrelloClient) memberFormatterCsv(members []*TrelloMember) error {
var err error
header := strings.Join(strings.Split(client.config.SearchResultFields, ","), client.config.ColSep)
fmt.Println(header)
for _, member := range members {
member.Bio = strings.Replace(member.Bio, "\n", "\\n", -1)
colbuf := client.buildMemberSlice(member)
fmt.Print(strings.Join(colbuf, client.config.ColSep))
fmt.Print(client.config.RowSep)
}
return err
}
func (client *TrelloClient) memberFormatterExcel(members []*TrelloMember) (err error) {
var (
file *xlsx.File
sheet *xlsx.Sheet
row *xlsx.Row
cell *xlsx.Cell
)
client.config.QuoteChar = "" // we do not need quoting in excel
file = xlsx.NewFile()
if sheet, err = file.AddSheet("Sheet1"); err != nil {
return
}
header := strings.Split(client.config.SearchResultFields, ",")
row = sheet.AddRow()
for _, column := range header {
cell = row.AddCell()
cell.Value = strings.Title(column)
}
for _, member := range members {
row = sheet.AddRow()
for _, column := range client.buildMemberSlice(member) {
cell = row.AddCell()
cell.Value = column
}
}
if err != nil {
fmt.Printf(err.Error())
}
err = file.Write(os.Stdout)
if err != nil {
fmt.Printf(err.Error())
}
return err
}
func (client *TrelloClient) memberFormatterMarkdown(members []*TrelloMember) error {
var err error
header := strings.Split(client.config.SearchResultFields, ",")
for _, member := range members {
colbuf := client.buildMemberSlice(member)
fmt.Println("## " + member.FullName)
fmt.Println()
for i, headercol := range header {
fmt.Printf(" * " + strings.Title(headercol) + ": " + colbuf[i] + "\n")
}
fmt.Print(client.config.RowSep)
}
return err
}
func (client *TrelloClient) outputCards(cards []*TrelloCardSearchResult, format string) error {
var err error
switch strings.ToLower(format) {
case "text":
err = client.formatterText(cards)
case "csv":
err = client.formatterCsv(cards)
case "json":
err = client.formatterJSON(cards)
case "excel":
err = client.formatterExcel(cards)
case "markdown":
err = client.formatterMarkdown(cards)
default:
err = errors.New("INVALID_OUTPUT_FORMAT")
}
return err
}
func (client *TrelloClient) outputMembers(cards []*TrelloMember, format string) error {
var err error
switch strings.ToLower(format) {
case "text":
err = client.memberFormatterText(cards)
case "csv":
err = client.memberFormatterCsv(cards)
case "json":
err = client.memberFormatterJSON(cards)
case "excel":
err = client.memberFormatterExcel(cards)
case "markdown":
err = client.memberFormatterMarkdown(cards)
default:
err = errors.New("INVALID_OUTPUT_FORMAT")
}
return err
}
func (client *TrelloClient) handleAtCommand(command string) error {
var err error
command = strings.ToLower(command)
cmd := strings.Split(command, " ")[0]
parms := strings.TrimSpace(strings.Replace(command, cmd, "", -1))
switch cmd {
case "@fields":
client.config.SearchResultFields = parms
case "@format":
client.config.Format = parms
case "@colsep":
client.config.ColSep = parms
case "@rowsep":
client.config.RowSep = parms
case "@limit":
client.config.CardLimit, err = strconv.Atoi(parms)
}
return err
}
func (client *TrelloClient) parseQuery(queryString string) (string, error) {
var err error
lines := strings.Split(queryString, "\n")
query := ""
for _, line := range lines {
line = strings.TrimSpace(line)
line = strings.Split(line, "//")[0] // dirty trick to get rid of the comments, if any
if line != "" {
if line[0] == '@' {
err = client.handleAtCommand(line)
if err != nil {
return "", err
}
} else {
query += line + " "
}
}
}
return query, err
}
func isFile(filename string) bool {
var err error
var fi os.FileInfo
fi, err = os.Stat(filename)
if err != nil || (err == nil && fi.IsDir()) {
return false
}
return true
}
func (client *TrelloClient) loadQuery(filename string) (string, error) {
var err error
data, err := ioutil.ReadFile(filename)
if err != nil {
return "", err
}
return client.parseQuery(string(data))
}
func (client *TrelloClient) Search() error {
var err error
query := flag.Arg(flag.NArg() - 1)
limit := client.config.CardLimit
if isFile(query) {
query, err = client.loadQuery(query)
if err != nil {
fmt.Println("Could not load query:", err.Error())
return err
}
}
cards, err := client.SearchCards(query, limit)
if err != nil {
fmt.Println("Error searching for cards:", err.Error())
} else {
err = client.outputCards(cards, client.config.Format)
if err != nil {
fmt.Println("Error writing search result:", err.Error())
}
}
return err
}
func (client *TrelloClient) FetchAllMembers() error {
var err error
board := flag.Arg(flag.NArg() - 1)
boardID := IDFromName(board, client.TrelloBoards)
members, err := client.FetchBoardMembers(boardID)
if err != nil {
} else {
err = client.outputMembers(members, client.config.Format)
}
return err
}
func (client *TrelloClient) FetchAllBoards() error {
var err error
format := strings.ToLower(client.config.Format)
if format == "excel" || format == "markdown" || format == "json" {
err = errors.New("Format not supported for this operation.")
}
for _, board := range client.TrelloBoards {
fmt.Println("Board" + client.config.ColSep + board.Name + client.config.ColSep + board.ID)
for _, list := range client.TrelloLists[strings.ToLower(board.Name)] {
fmt.Println("List" + client.config.ColSep + list.Name + client.config.ColSep + list.ID)
}
fmt.Println()
}
return err
}