-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathparams.go
1133 lines (945 loc) · 29 KB
/
params.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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package params
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"time"
"github.com/wakatime/wakatime-cli/pkg/api"
"github.com/wakatime/wakatime-cli/pkg/apikey"
"github.com/wakatime/wakatime-cli/pkg/heartbeat"
"github.com/wakatime/wakatime-cli/pkg/ini"
"github.com/wakatime/wakatime-cli/pkg/log"
"github.com/wakatime/wakatime-cli/pkg/output"
"github.com/wakatime/wakatime-cli/pkg/project"
"github.com/wakatime/wakatime-cli/pkg/regex"
"github.com/wakatime/wakatime-cli/pkg/vipertools"
"github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
"golang.org/x/net/http/httpproxy"
)
const (
errMsgTemplate = "invalid url %q. Must be in format" +
"'https://user:pass@host:port' or " +
"'socks5://user:pass@host:port' or " +
"'domain\\\\user:pass.'"
gitpodHostname = "Gitpod"
)
var (
// nolint
apiKeyRegex = regexp.MustCompile("^(waka_)?[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$")
// nolint
matchAllRegex = regexp.MustCompile(".*")
// nolint
matchNoneRegex = regexp.MustCompile("a^")
// nolint
ntlmProxyRegex = regexp.MustCompile(`^.*\\.+$`)
// nolint
proxyRegex = regexp.MustCompile(`^((https?|socks5)://)?([^:@]+(:([^:@])+)?@)?([^:]+|(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])))(:\d+)?$`)
)
type (
// Params contains params.
Params struct {
API API
Heartbeat Heartbeat
Offline Offline
StatusBar StatusBar
}
// API contains api related parameters.
API struct {
BackoffAt time.Time
BackoffRetries int
DisableSSLVerify bool
Hostname string
Key string
KeyPatterns []apikey.MapPattern
Plugin string
ProxyURL string
SSLCertFilepath string
Timeout time.Duration
URL string
}
// ExtraHeartbeat contains extra heartbeat.
ExtraHeartbeat struct {
BranchAlternate string `json:"alternate_branch"`
Category heartbeat.Category `json:"category"`
CursorPosition any `json:"cursorpos"`
Entity string `json:"entity"`
EntityType string `json:"entity_type"`
Type string `json:"type"`
IsUnsavedEntity any `json:"is_unsaved_entity"`
IsWrite any `json:"is_write"`
Language *string `json:"language"`
LanguageAlternate string `json:"alternate_language"`
LineAdditions any `json:"line_additions"`
LineDeletions any `json:"line_deletions"`
LineNumber any `json:"lineno"`
Lines any `json:"lines"`
Project string `json:"project"`
ProjectAlternate string `json:"alternate_project"`
Time any `json:"time"`
Timestamp any `json:"timestamp"`
}
// Heartbeat contains heartbeat command parameters.
Heartbeat struct {
Category heartbeat.Category
CursorPosition *int
Entity string
EntityType heartbeat.EntityType
ExtraHeartbeats []heartbeat.Heartbeat
GuessLanguage bool
IsUnsavedEntity bool
IsWrite *bool
Language *string
LanguageAlternate string
LineAdditions *int
LineDeletions *int
LineNumber *int
LinesInFile *int
LocalFile string
Time float64
Filter FilterParams
Project ProjectParams
Sanitize SanitizeParams
}
// FilterParams contains heartbeat filtering related command parameters.
FilterParams struct {
Exclude []regex.Regex
ExcludeUnknownProject bool
Include []regex.Regex
IncludeOnlyWithProjectFile bool
}
// Offline contains offline related parameters.
Offline struct {
Disabled bool
QueueFile string
PrintMax int
SyncMax int
}
// ProjectParams params for project name sanitization.
ProjectParams struct {
Alternate string
BranchAlternate string
MapPatterns []project.MapPattern
Override string
ProjectFromGitRemote bool
SubmodulesDisabled []regex.Regex
SubmoduleMapPatterns []project.MapPattern
}
// SanitizeParams params for heartbeat sanitization.
SanitizeParams struct {
HideBranchNames []regex.Regex
HideFileNames []regex.Regex
HideProjectFolder bool
HideProjectNames []regex.Regex
ProjectPathOverride string
}
// StatusBar contains status bar related parameters.
StatusBar struct {
HideCategories bool
Output output.Output
}
)
// LoadAPIParams loads API params from viper.Viper instance. Returns ErrAuth
// if failed to retrieve api key.
func LoadAPIParams(v *viper.Viper) (API, error) {
apiKey, err := LoadAPIKey(v)
if err != nil {
return API{}, err
}
var apiKeyPatterns []apikey.MapPattern
apiKeyMap := vipertools.GetStringMapString(v, "project_api_key")
for k, s := range apiKeyMap {
// make all regex case insensitive
if !strings.HasPrefix(k, "(?i)") {
k = "(?i)" + k
}
compiled, err := regex.Compile(k)
if err != nil {
log.Warnf("failed to compile project_api_key regex pattern %q", k)
continue
}
if !apiKeyRegex.MatchString(s) {
return API{}, api.ErrAuth{Err: fmt.Errorf("invalid api key format for %q", k)}
}
if s == apiKey {
continue
}
apiKeyPatterns = append(apiKeyPatterns, apikey.MapPattern{
APIKey: s,
Regex: compiled,
})
}
apiURLStr := api.BaseURL
if u := vipertools.FirstNonEmptyString(v, "api-url", "apiurl", "settings.api_url"); u != "" {
apiURLStr = u
}
// remove endpoint from api base url to support legacy api_url param
apiURLStr = strings.TrimSuffix(apiURLStr, "/")
apiURLStr = strings.TrimSuffix(apiURLStr, ".bulk")
apiURLStr = strings.TrimSuffix(apiURLStr, "/users/current/heartbeats")
apiURLStr = strings.TrimSuffix(apiURLStr, "/heartbeats")
apiURLStr = strings.TrimSuffix(apiURLStr, "/heartbeat")
apiURL, err := url.Parse(apiURLStr)
if err != nil {
return API{}, api.ErrAuth{Err: fmt.Errorf("invalid api url: %s", err)}
}
var backoffAt time.Time
backoffAtStr := vipertools.GetString(v, "internal.backoff_at")
if backoffAtStr != "" {
parsed, err := time.Parse(ini.DateFormat, backoffAtStr)
if err != nil {
log.Warnf("failed to parse backoff_at: %s", err)
} else {
backoffAt = parsed
}
}
var backoffRetries = 0
backoffRetriesStr := vipertools.GetString(v, "internal.backoff_retries")
if backoffRetriesStr != "" {
parsed, err := strconv.Atoi(backoffRetriesStr)
if err != nil {
log.Warnf("failed to parse backoff_retries: %s", err)
} else {
backoffRetries = parsed
}
}
hostname := vipertools.FirstNonEmptyString(v, "hostname", "settings.hostname")
gitpod := os.Getenv("GITPOD_WORKSPACE_ID")
if hostname == "" && gitpod != "" {
hostname = gitpodHostname
}
if hostname == "" {
hostname, err = os.Hostname()
if err != nil {
log.Warnf("failed to retrieve hostname from system: %s", err)
}
}
proxyURL := vipertools.FirstNonEmptyString(v, "proxy", "settings.proxy")
rgx := proxyRegex
if strings.Contains(proxyURL, `\\`) {
rgx = ntlmProxyRegex
}
if proxyURL != "" && !rgx.MatchString(proxyURL) {
return API{}, api.ErrAuth{Err: fmt.Errorf(errMsgTemplate, proxyURL)}
}
proxyEnv := httpproxy.FromEnvironment()
proxyEnvURL, err := proxyEnv.ProxyFunc()(apiURL)
if err != nil {
log.Warnf("failed to get proxy url from environment for api url: %s", err)
}
// try use proxy from environment if no custom proxy is set
if proxyURL == "" && proxyEnvURL != nil {
proxyURL = proxyEnvURL.String()
}
sslCertFilepath := vipertools.FirstNonEmptyString(v, "ssl-certs-file", "settings.ssl_certs_file")
if sslCertFilepath != "" {
sslCertFilepath, err = homedir.Expand(sslCertFilepath)
if err != nil {
return API{}, api.ErrAuth{Err: fmt.Errorf("failed expanding ssl certs file: %s", err)}
}
}
var timeout time.Duration
if timeoutSecs, ok := vipertools.FirstNonEmptyInt(v, "timeout", "settings.timeout"); ok {
timeout = time.Duration(timeoutSecs) * time.Second
}
return API{
BackoffAt: backoffAt,
BackoffRetries: backoffRetries,
DisableSSLVerify: vipertools.FirstNonEmptyBool(v, "no-ssl-verify", "settings.no_ssl_verify"),
Hostname: hostname,
Key: apiKey,
KeyPatterns: apiKeyPatterns,
Plugin: vipertools.GetString(v, "plugin"),
ProxyURL: proxyURL,
SSLCertFilepath: sslCertFilepath,
Timeout: timeout,
URL: apiURL.String(),
}, nil
}
// LoadAPIKey loads a valid default WakaTime API Key or returns an error.
func LoadAPIKey(v *viper.Viper) (string, error) {
apiKey := vipertools.FirstNonEmptyString(v, "key", "settings.api_key", "settings.apikey")
if apiKey != "" {
if !apiKeyRegex.MatchString(apiKey) {
return "", api.ErrAuth{Err: errors.New("invalid api key format")}
}
return apiKey, nil
}
apiKey, err := readAPIKeyFromCommand(vipertools.GetString(v, "settings.api_key_vault_cmd"))
if err != nil {
return "", api.ErrAuth{Err: fmt.Errorf("failed to read api key from vault: %s", err)}
}
if apiKey != "" {
if !apiKeyRegex.MatchString(apiKey) {
return "", api.ErrAuth{Err: errors.New("invalid api key format")}
}
log.Debugln("loaded api key from vault")
return apiKey, nil
}
apiKey = os.Getenv("WAKATIME_API_KEY")
if apiKey != "" {
if !apiKeyRegex.MatchString(apiKey) {
return "", api.ErrAuth{Err: errors.New("invalid api key format")}
}
log.Debugln("loaded api key from env var")
return apiKey, nil
}
if apiKey == "" {
return "", api.ErrAuth{Err: errors.New("api key not found or empty")}
}
return apiKey, nil
}
// LoadHeartbeatParams loads heartbeats params from viper.Viper instance.
func LoadHeartbeatParams(v *viper.Viper) (Heartbeat, error) {
var category heartbeat.Category
if categoryStr := vipertools.GetString(v, "category"); categoryStr != "" {
parsed, err := heartbeat.ParseCategory(categoryStr)
if err != nil {
return Heartbeat{}, fmt.Errorf("failed to parse category: %s", err)
}
category = parsed
}
var cursorPosition *int
if pos := v.GetInt("cursorpos"); v.IsSet("cursorpos") {
cursorPosition = heartbeat.PointerTo(pos)
}
entity := vipertools.FirstNonEmptyString(v, "entity", "file")
if entity == "" {
return Heartbeat{}, errors.New("failed to retrieve entity")
}
entityExpanded, err := homedir.Expand(entity)
if err != nil {
return Heartbeat{}, fmt.Errorf("failed expanding entity: %s", err)
}
var entityType heartbeat.EntityType
if entityTypeStr := vipertools.GetString(v, "entity-type"); entityTypeStr != "" {
parsed, err := heartbeat.ParseEntityType(entityTypeStr)
if err != nil {
return Heartbeat{}, fmt.Errorf("failed to parse entity type: %s", err)
}
entityType = parsed
}
var extraHeartbeats []heartbeat.Heartbeat
if v.GetBool("extra-heartbeats") {
extraHeartbeats, err = readExtraHeartbeats()
if err != nil {
log.Errorf("failed to read extra heartbeats: %s", err)
}
}
var isWrite *bool
if b := v.GetBool("write"); v.IsSet("write") {
isWrite = heartbeat.PointerTo(b)
}
var lineAdditions *int
if num := v.GetInt("line-additions"); v.IsSet("line-additions") {
lineAdditions = heartbeat.PointerTo(num)
}
var lineDeletions *int
if num := v.GetInt("line-deletions"); v.IsSet("line-deletions") {
lineDeletions = heartbeat.PointerTo(num)
}
var lineNumber *int
if num := v.GetInt("lineno"); v.IsSet("lineno") {
lineNumber = heartbeat.PointerTo(num)
}
var linesInFile *int
if num := v.GetInt("lines-in-file"); v.IsSet("lines-in-file") {
linesInFile = heartbeat.PointerTo(num)
}
timeSecs := v.GetFloat64("time")
if timeSecs == 0 {
timeSecs = float64(time.Now().UnixNano()) / 1000000000
}
projectParams, err := loadProjectParams(v)
if err != nil {
return Heartbeat{}, fmt.Errorf("failed to parse project params: %s", err)
}
sanitizeParams, err := loadSanitizeParams(v)
if err != nil {
return Heartbeat{}, fmt.Errorf("failed to load sanitize params: %s", err)
}
var language *string
if l := vipertools.GetString(v, "language"); l != "" {
language = &l
}
return Heartbeat{
Category: category,
CursorPosition: cursorPosition,
Entity: entityExpanded,
ExtraHeartbeats: extraHeartbeats,
EntityType: entityType,
GuessLanguage: vipertools.FirstNonEmptyBool(v, "guess-language", "settings.guess_language"),
IsUnsavedEntity: v.GetBool("is-unsaved-entity"),
IsWrite: isWrite,
Language: language,
LanguageAlternate: vipertools.GetString(v, "alternate-language"),
LineAdditions: lineAdditions,
LineDeletions: lineDeletions,
LineNumber: lineNumber,
LinesInFile: linesInFile,
LocalFile: vipertools.GetString(v, "local-file"),
Time: timeSecs,
Filter: loadFilterParams(v),
Project: projectParams,
Sanitize: sanitizeParams,
}, nil
}
func loadFilterParams(v *viper.Viper) FilterParams {
exclude := v.GetStringSlice("exclude")
exclude = append(exclude, v.GetStringSlice("settings.exclude")...)
exclude = append(exclude, v.GetStringSlice("settings.ignore")...)
var excludePatterns []regex.Regex
for _, s := range exclude {
// make all regex case insensitive
if !strings.HasPrefix(s, "(?i)") {
s = "(?i)" + s
}
compiled, err := regex.Compile(s)
if err != nil {
log.Warnf("failed to compile exclude regex pattern %q", s)
continue
}
excludePatterns = append(excludePatterns, compiled)
}
include := v.GetStringSlice("include")
include = append(include, v.GetStringSlice("settings.include")...)
var includePatterns []regex.Regex
for _, s := range include {
// make all regex case insensitive
if !strings.HasPrefix(s, "(?i)") {
s = "(?i)" + s
}
compiled, err := regex.Compile(s)
if err != nil {
log.Warnf("failed to compile include regex pattern %q", s)
continue
}
includePatterns = append(includePatterns, compiled)
}
return FilterParams{
Exclude: excludePatterns,
ExcludeUnknownProject: vipertools.FirstNonEmptyBool(
v,
"exclude-unknown-project",
"settings.exclude_unknown_project",
),
Include: includePatterns,
IncludeOnlyWithProjectFile: vipertools.FirstNonEmptyBool(
v,
"include-only-with-project-file",
"settings.include_only_with_project_file",
),
}
}
func loadSanitizeParams(v *viper.Viper) (SanitizeParams, error) {
// hide branch names
hideBranchNamesStr := vipertools.FirstNonEmptyString(
v,
"hide-branch-names",
"settings.hide_branch_names",
"settings.hide_branchnames",
"settings.hidebranchnames",
)
hideBranchNamesPatterns, err := parseBoolOrRegexList(hideBranchNamesStr)
if err != nil {
return SanitizeParams{}, fmt.Errorf(
"failed to parse regex hide branch names param %q: %s",
hideBranchNamesStr,
err,
)
}
// hide project names
hideProjectNamesStr := vipertools.FirstNonEmptyString(
v,
"hide-project-names",
"settings.hide_project_names",
"settings.hide_projectnames",
"settings.hideprojectnames",
)
hideProjectNamesPatterns, err := parseBoolOrRegexList(hideProjectNamesStr)
if err != nil {
return SanitizeParams{}, fmt.Errorf(
"failed to parse regex hide project names param %q: %s",
hideProjectNamesStr,
err,
)
}
// hide file names
hideFileNamesStr := vipertools.FirstNonEmptyString(
v,
"hide-file-names",
"hide-filenames",
"hidefilenames",
"settings.hide_file_names",
"settings.hide_filenames",
"settings.hidefilenames",
)
hideFileNamesPatterns, err := parseBoolOrRegexList(hideFileNamesStr)
if err != nil {
return SanitizeParams{}, fmt.Errorf(
"failed to parse regex hide file names param %q: %s",
hideFileNamesStr,
err,
)
}
return SanitizeParams{
HideBranchNames: hideBranchNamesPatterns,
HideFileNames: hideFileNamesPatterns,
HideProjectFolder: vipertools.FirstNonEmptyBool(v, "hide-project-folder", "settings.hide_project_folder"),
HideProjectNames: hideProjectNamesPatterns,
ProjectPathOverride: vipertools.GetString(v, "project-folder"),
}, nil
}
func loadProjectParams(v *viper.Viper) (ProjectParams, error) {
submodulesDisabled, err := parseBoolOrRegexList(vipertools.GetString(v, "git.submodules_disabled"))
if err != nil {
return ProjectParams{}, fmt.Errorf(
"failed to parse regex submodules disabled param: %s",
err,
)
}
return ProjectParams{
Alternate: vipertools.GetString(v, "alternate-project"),
BranchAlternate: vipertools.GetString(v, "alternate-branch"),
MapPatterns: loadProjectMapPatterns(v, "projectmap"),
Override: vipertools.GetString(v, "project"),
ProjectFromGitRemote: v.GetBool("git.project_from_git_remote"),
SubmodulesDisabled: submodulesDisabled,
SubmoduleMapPatterns: loadProjectMapPatterns(v, "git_submodule_projectmap"),
}, nil
}
func loadProjectMapPatterns(v *viper.Viper, prefix string) []project.MapPattern {
var mapPatterns []project.MapPattern
values := vipertools.GetStringMapString(v, prefix)
for k, s := range values {
// make all regex case insensitive
if !strings.HasPrefix(k, "(?i)") {
k = "(?i)" + k
}
compiled, err := regex.Compile(k)
if err != nil {
log.Warnf("failed to compile projectmap regex pattern %q", k)
continue
}
mapPatterns = append(mapPatterns, project.MapPattern{
Name: s,
Regex: compiled,
})
}
return mapPatterns
}
// LoadOfflineParams loads offline params from viper.Viper instance.
func LoadOfflineParams(v *viper.Viper) Offline {
disabled := vipertools.FirstNonEmptyBool(v, "disable-offline", "disableoffline")
if b := v.GetBool("settings.offline"); v.IsSet("settings.offline") {
disabled = !b
}
syncMax := v.GetInt("sync-offline-activity")
if syncMax < 0 {
log.Warnf("argument --sync-offline-activity must be zero or a positive integer number, got %d", syncMax)
syncMax = 0
}
return Offline{
Disabled: disabled,
QueueFile: vipertools.GetString(v, "offline-queue-file"),
PrintMax: v.GetInt("print-offline-heartbeats"),
SyncMax: syncMax,
}
}
// LoadStatusBarParams loads status bar params from viper.Viper instance.
func LoadStatusBarParams(v *viper.Viper) (StatusBar, error) {
var hideCategories bool
if hideCategoriesStr := vipertools.FirstNonEmptyString(
v,
"today-hide-categories",
"settings.status_bar_hide_categories",
); hideCategoriesStr != "" {
val, err := strconv.ParseBool(hideCategoriesStr)
if err != nil {
return StatusBar{}, fmt.Errorf("failed to parse today-hide-categories: %s", err)
}
hideCategories = val
}
var out output.Output
if outputStr := vipertools.GetString(v, "output"); outputStr != "" {
parsed, err := output.Parse(outputStr)
if err != nil {
return StatusBar{}, fmt.Errorf("failed to parse output: %s", err)
}
out = parsed
}
return StatusBar{
HideCategories: hideCategories,
Output: out,
}, nil
}
func readAPIKeyFromCommand(cmdStr string) (string, error) {
if cmdStr == "" {
return "", nil
}
cmdStr = strings.TrimSpace(cmdStr)
if cmdStr == "" {
return "", nil
}
cmdParts := strings.Split(cmdStr, " ")
if len(cmdParts) == 0 {
return "", nil
}
cmdName := cmdParts[0]
cmdArgs := cmdParts[1:]
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, cmdName, cmdArgs...) // nolint:gosec
cmd.Stderr = os.Stderr
out, err := cmd.Output()
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
}
func readExtraHeartbeats() ([]heartbeat.Heartbeat, error) {
in := bufio.NewReader(os.Stdin)
input, err := in.ReadString('\n')
if err != nil {
log.Debugf("failed to read data from stdin: %s", err)
}
heartbeats, err := parseExtraHeartbeats(input)
if err != nil {
return nil, fmt.Errorf("failed parsing: %s", err)
}
return heartbeats, nil
}
func parseExtraHeartbeats(data string) ([]heartbeat.Heartbeat, error) {
if data == "" {
log.Debugln("skipping extra heartbeats, as no data was provided")
return nil, nil
}
var extraHeartbeats []ExtraHeartbeat
err := json.Unmarshal([]byte(data), &extraHeartbeats)
if err != nil {
return nil, fmt.Errorf("failed to json decode from data %q: %s", data, err)
}
var heartbeats []heartbeat.Heartbeat
for _, h := range extraHeartbeats {
parsed, err := parseExtraHeartbeat(h)
if err != nil {
return nil, err
}
heartbeats = append(heartbeats, *parsed)
}
return heartbeats, nil
}
func parseExtraHeartbeat(h ExtraHeartbeat) (*heartbeat.Heartbeat, error) {
var err error
h.Entity, err = homedir.Expand(h.Entity)
if err != nil {
return nil, fmt.Errorf("failed expanding entity: %s", err)
}
var entityType heartbeat.EntityType
// Both type or entity_type are acceptable here. Type takes precedence.
entityTypeStr := firstNonEmptyString(h.Type, h.EntityType)
if entityTypeStr != "" {
entityType, err = heartbeat.ParseEntityType(entityTypeStr)
if err != nil {
return nil, err
}
}
var cursorPosition *int
switch cursorPositionVal := h.CursorPosition.(type) {
case float64:
cursorPosition = heartbeat.PointerTo(int(cursorPositionVal))
case string:
val, err := strconv.Atoi(cursorPositionVal)
if err != nil {
return nil, fmt.Errorf("failed to convert cursor position to int: %s", err)
}
cursorPosition = heartbeat.PointerTo(val)
}
var isWrite *bool
switch isWriteVal := h.IsWrite.(type) {
case bool:
isWrite = heartbeat.PointerTo(isWriteVal)
case string:
val, err := strconv.ParseBool(isWriteVal)
if err != nil {
return nil, fmt.Errorf("failed to convert is write to bool: %s", err)
}
isWrite = heartbeat.PointerTo(val)
}
var lineNumber *int
switch lineNumberVal := h.LineNumber.(type) {
case float64:
lineNumber = heartbeat.PointerTo(int(lineNumberVal))
case string:
val, err := strconv.Atoi(lineNumberVal)
if err != nil {
return nil, fmt.Errorf("failed to convert line number to int: %s", err)
}
lineNumber = heartbeat.PointerTo(val)
}
var lines *int
switch linesVal := h.Lines.(type) {
case float64:
lines = heartbeat.PointerTo(int(linesVal))
case string:
val, err := strconv.Atoi(linesVal)
if err != nil {
return nil, fmt.Errorf("failed to convert lines to int: %s", err)
}
lines = heartbeat.PointerTo(val)
}
var time float64
switch timeVal := h.Time.(type) {
case float64:
time = timeVal
case string:
val, err := strconv.ParseFloat(timeVal, 64)
if err != nil {
return nil, fmt.Errorf("failed to convert time to float64: %s", err)
}
time = val
}
var timestamp float64
switch timestampVal := h.Timestamp.(type) {
case float64:
timestamp = timestampVal
case string:
val, err := strconv.ParseFloat(timestampVal, 64)
if err != nil {
return nil, fmt.Errorf("failed to convert timestamp to float64: %s", err)
}
timestamp = val
}
var timestampParsed float64
switch {
case h.Time != nil && h.Time != 0:
timestampParsed = time
case h.Timestamp != nil && h.Timestamp != 0:
timestampParsed = timestamp
default:
return nil, fmt.Errorf("skipping extra heartbeat, as no valid timestamp was defined")
}
var isUnsavedEntity bool
switch isUnsavedEntityVal := h.IsUnsavedEntity.(type) {
case bool:
isUnsavedEntity = isUnsavedEntityVal
case string:
val, err := strconv.ParseBool(isUnsavedEntityVal)
if err != nil {
return nil, fmt.Errorf("failed to convert is_unsaved_entity to bool: %s", err)
}
isUnsavedEntity = val
}
return &heartbeat.Heartbeat{
BranchAlternate: h.BranchAlternate,
Category: h.Category,
CursorPosition: cursorPosition,
Entity: h.Entity,
EntityType: entityType,
IsUnsavedEntity: isUnsavedEntity,
IsWrite: isWrite,
Language: h.Language,
LanguageAlternate: h.LanguageAlternate,
LineNumber: lineNumber,
Lines: lines,
ProjectAlternate: h.ProjectAlternate,
ProjectOverride: h.Project,
Time: timestampParsed,
}, nil
}
// String implements fmt.Stringer interface.
func (p API) String() string {
var backoffAt string
if !p.BackoffAt.IsZero() {
backoffAt = p.BackoffAt.Format(ini.DateFormat)
}
apiKey := p.Key
if len(apiKey) > 4 {
// only show last 4 chars of api key in logs
apiKey = fmt.Sprintf("<hidden>%s", apiKey[len(apiKey)-4:])
}
keyPatterns := []apikey.MapPattern{}
for _, k := range p.KeyPatterns {
if len(k.APIKey) > 4 {
// only show last 4 chars of api key in logs
k.APIKey = fmt.Sprintf("<hidden>%s", k.APIKey[len(k.APIKey)-4:])
}
keyPatterns = append(keyPatterns, apikey.MapPattern{
Regex: k.Regex,
APIKey: k.APIKey,
})
}
return fmt.Sprintf(
"api key: '%s', api url: '%s', backoff at: '%s', backoff retries: %d,"+
" hostname: '%s', key patterns: '%s', plugin: '%s', proxy url: '%s',"+
" timeout: %s, disable ssl verify: %t, ssl cert filepath: '%s'",
apiKey,
p.URL,
backoffAt,
p.BackoffRetries,
p.Hostname,
keyPatterns,
p.Plugin,
p.ProxyURL,
p.Timeout,
p.DisableSSLVerify,
p.SSLCertFilepath,
)
}
func (p FilterParams) String() string {
return fmt.Sprintf(
"exclude: '%s', exclude unknown project: %t, include: '%s', include only with project file: %t",
p.Exclude,
p.ExcludeUnknownProject,
p.Include,
p.IncludeOnlyWithProjectFile,
)
}
func (p Heartbeat) String() string {
var cursorPosition string
if p.CursorPosition != nil {
cursorPosition = strconv.Itoa(*p.CursorPosition)
}
var isWrite bool
if p.IsWrite != nil {
isWrite = *p.IsWrite
}
var language string
if p.Language != nil {
language = *p.Language
}
var lineAdditions string
if p.LineAdditions != nil {
lineAdditions = strconv.Itoa(*p.LineAdditions)
}
var lineDeletions string
if p.LineDeletions != nil {
lineDeletions = strconv.Itoa(*p.LineDeletions)
}
var lineNumber string