-
Notifications
You must be signed in to change notification settings - Fork 6
/
config.go
596 lines (497 loc) · 18.4 KB
/
config.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
// Copyright 2017 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
package config
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/dghubble/oauth1"
"github.com/fsnotify/fsnotify"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
jira "github.com/uwu-tools/go-jira/v2/cloud"
"golang.org/x/term"
"github.com/uwu-tools/gh-jira-issue-sync/internal/github"
"github.com/uwu-tools/gh-jira-issue-sync/internal/options"
)
// fieldKey is an enum-like type to represent the customfield ID keys.
type fieldKey int
const (
GitHubID fieldKey = iota
GitHubNumber fieldKey = iota
GitHubLabels fieldKey = iota
GitHubStatus fieldKey = iota
GitHubReporter fieldKey = iota
GitHubLastSync fieldKey = iota
// Custom field names.
CustomFieldNameGitHubID = "github-id"
CustomFieldNameGitHubNumber = "github-number"
CustomFieldNameGitHubLabels = "github-labels"
CustomFieldNameGitHubStatus = "github-status"
CustomFieldNameGitHubReporter = "github-reporter"
CustomFieldNameGitHubLastSync = "github-last-sync"
)
// fields represents the custom field IDs of the Jira custom fields we care about.
type fields struct {
githubID string
githubNumber string
githubLabels string
githubReporter string
githubStatus string
lastUpdate string
}
// Config is the root configuration object the application creates.
//
//nolint:govet
type Config struct {
// cmdFile is the file Viper is using for its configuration.
cmdFile string
// cmdConfig is the Viper configuration object created from the command line and config file.
cmdConfig viper.Viper
// ctx carries a deadline, a cancellation signal, and other values across
// API boundaries.
ctx context.Context
// basicAuth represents whether we're using HTTP Basic authentication or OAuth.
basicAuth bool
// fieldIDs is the list of custom fields we pulled from the `fields` Jira endpoint.
fieldIDs *fields
// project represents the Jira project the user has requested.
project *jira.Project
// components represents the Jira components the user would like use for the sync.
// Comes from the value of the `jira-components` configuration parameter.
// Items in Jira will have the components field set to these values.
components []*jira.Component
// since is the parsed value of the `since` configuration parameter, which is the earliest that
// a GitHub issue can have been updated to be retrieved.
since time.Time
}
// New creates a new, immutable configuration object. This object
// holds the Viper configuration and the logger, and is validated. The
// Jira configuration is not yet initialized.
func New(ctx context.Context, cmd *cobra.Command) (*Config, error) {
var cfg Config
cfgFilePath, err := cmd.Flags().GetString(options.ConfigKeyConfigFile)
if err != nil {
return nil, fmt.Errorf("getting config file: %w", err)
}
if cfgFilePath == "" {
log.Debug("config file path was not set, falling back to default")
cfgFileDir, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("getting working directory: %w", err)
}
cfgFilePath = filepath.Join(cfgFileDir, options.DefaultConfigFileName)
}
_, err = os.Stat(cfgFilePath)
if err != nil {
return nil, fmt.Errorf(
"checking if config file (%s) exists: %w",
cfgFilePath,
err,
)
}
log.Debugf("using config file: %s", cfgFilePath)
cfg.cmdFile = cfgFilePath
cfg.cmdConfig = *newViper(options.AppName, cfg.cmdFile)
cfg.cmdConfig.BindPFlags(cmd.Flags()) //nolint:errcheck
cfg.cmdFile = cfg.cmdConfig.ConfigFileUsed()
cfg.ctx = ctx
if err := cfg.validateConfig(); err != nil {
return nil, err
}
return &cfg, nil
}
// LoadJiraConfig loads the Jira configuration (project key,
// custom field IDs) from a remote Jira server.
func (c *Config) LoadJiraConfig(client *jira.Client) error {
proj, res, err := client.Project.Get(
c.Context(),
c.cmdConfig.GetString(options.ConfigKeyJiraProject),
)
if err != nil {
log.Errorf("error retrieving Jira project; check key and credentials. Error: %s", err)
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
log.Errorf("error occurred trying to read error body: %s", err)
return fmt.Errorf("reading Jira project: %w", err)
}
log.Debugf("Error body: %s", body)
return fmt.Errorf("reading error body: %s", string(body)) //nolint:goerr113
}
c.project = proj
c.components, err = c.getComponents(proj)
if err != nil {
return err
}
c.fieldIDs, err = c.getFieldIDs(client)
if err != nil {
return err
}
return nil
}
// Context returns the context.
func (c *Config) Context() context.Context {
return c.ctx
}
// GetConfigFile returns the file that Viper loaded the configuration from.
func (c *Config) GetConfigFile() string {
return c.cmdFile
}
// GetConfigString returns a string value from the Viper configuration.
func (c *Config) GetConfigString(key string) string {
return c.cmdConfig.GetString(key)
}
// IsBasicAuth is true if we're using HTTP Basic Authentication, and false if
// we're using OAuth.
func (c *Config) IsBasicAuth() bool {
return c.basicAuth
}
// GetSinceParam returns the `since` configuration parameter, parsed as a time.Time.
func (c *Config) GetSinceParam() time.Time {
return c.since
}
// IsDryRun returns whether the application is running in confirmed mode or not.
func (c *Config) IsDryRun() bool {
return !c.cmdConfig.GetBool(options.ConfigKeyConfirm)
}
// IsDaemon returns whether the application is running as a daemon.
func (c *Config) IsDaemon() bool {
return c.cmdConfig.GetDuration(options.ConfigKeyPeriod) != 0
}
// GetDaemonPeriod returns the period on which the tool runs if in daemon mode.
func (c *Config) GetDaemonPeriod() time.Duration {
return c.cmdConfig.GetDuration(options.ConfigKeyPeriod)
}
// GetTimeout returns the configured timeout on all API calls, parsed as a time.Duration.
func (c *Config) GetTimeout() time.Duration {
return c.cmdConfig.GetDuration(options.ConfigKeyTimeout)
}
// GetFieldID returns the customfield ID of a Jira custom field.
func (c *Config) GetFieldID(key fieldKey) string {
switch key {
case GitHubID:
return c.fieldIDs.githubID
case GitHubNumber:
return c.fieldIDs.githubNumber
case GitHubLabels:
return c.fieldIDs.githubLabels
case GitHubReporter:
return c.fieldIDs.githubReporter
case GitHubStatus:
return c.fieldIDs.githubStatus
case GitHubLastSync:
return c.fieldIDs.lastUpdate
default:
return ""
}
}
// GetFieldKey returns customfield_XXXXX, where XXXXX is the custom field ID (see GetFieldID).
func (c *Config) GetFieldKey(key fieldKey) string {
return fmt.Sprintf("customfield_%s", c.GetFieldID(key))
}
// GetProject returns the Jira project the user has configured.
func (c *Config) GetProject() *jira.Project {
return c.project
}
// GetProjectKey returns the Jira key of the configured project.
func (c *Config) GetProjectKey() string {
return c.project.Key
}
// GetRepo returns the user/org name and the repo name of the configured GitHub repository.
func (c *Config) GetRepo() (string, string) {
repoPath := c.cmdConfig.GetString(options.ConfigKeyRepoName)
// We check that repo-name is two parts separated by a slash in New, so this is safe
return github.GetRepo(repoPath)
}
// GetJiraComponents returns the Jira component the user has configured.
func (c *Config) GetJiraComponents() []*jira.Component {
return c.components
}
// SetJiraToken adds the Jira OAuth tokens in the Viper configuration, ensuring that they
// are saved for future runs.
func (c *Config) SetJiraToken(token *oauth1.Token) {
c.cmdConfig.Set(options.ConfigKeyJiraToken, token.Token)
c.cmdConfig.Set(options.ConfigKeyJiraSecret, token.TokenSecret)
}
// configFile is a serializable representation of the current Viper configuration.
type configFile struct {
LogLevel string `json:"log-level,omitempty" mapstructure:"log-level"`
GithubToken string `json:"github-token,omitempty" mapstructure:"github-token"`
JiraUser string `json:"jira-user,omitempty" mapstructure:"jira-user"`
JiraPass string `json:"jira-pass,omitempty" mapstructure:"jira-pass"`
JiraToken string `json:"jira-token,omitempty" mapstructure:"jira-token"`
JiraSecret string `json:"jira-secret,omitempty" mapstructure:"jira-secret"`
JiraKey string `json:"jira-private-key-path,omitempty" mapstructure:"jira-private-key-path"`
JiraCKey string `json:"jira-consumer-key,omitempty" mapstructure:"jira-consumer-key"`
RepoName string `json:"repo-name,omitempty" mapstructure:"repo-name"`
JiraURI string `json:"jira-uri,omitempty" mapstructure:"jira-uri"`
JiraProject string `json:"jira-project,omitempty" mapstructure:"jira-project"`
Since string `json:"since,omitempty" mapstructure:"since"`
JiraComponents []string `json:"jira-components,omitempty" mapstructure:"jira-components"`
Confirm bool `json:"confirm,omitempty" mapstructure:"confirm"`
Timeout time.Duration `json:"timeout,omitempty" mapstructure:"timeout"`
}
// SaveConfig updates the `since` parameter to now, then saves the configuration file.
func (c *Config) SaveConfig() error {
c.cmdConfig.Set(
options.ConfigKeySince,
time.Now().Format(options.DateFormat),
)
var cf configFile
if err := c.cmdConfig.Unmarshal(&cf); err != nil {
return fmt.Errorf("unmarshalling config: %w", err)
}
b, err := json.MarshalIndent(cf, "", " ")
if err != nil {
return fmt.Errorf("marshalling config: %w", err)
}
f, err := os.OpenFile(c.cmdConfig.ConfigFileUsed(), os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0o644)
if err != nil {
return fmt.Errorf("opening config file %s: %w", c.cmdConfig.ConfigFileUsed(), err)
}
defer f.Close()
_, err = f.WriteString(string(b))
if err != nil {
return fmt.Errorf("writing config: %w", err)
}
return nil
}
// newViper generates a viper configuration object which
// merges (in order from highest to lowest priority) the
// command line options, configuration file options, and
// default configuration values. This viper object becomes
// the single source of truth for the app configuration.
func newViper(appName, cfgFile string) *viper.Viper {
logger := log.New()
v := viper.New()
v.SetEnvPrefix(appName)
v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
v.AutomaticEnv()
v.SetConfigName(fmt.Sprintf("config-%s", appName))
v.AddConfigPath(".")
if cfgFile != "" {
v.SetConfigFile(cfgFile)
}
v.SetConfigType("json")
if err := v.ReadInConfig(); err == nil {
log.WithField("file", v.ConfigFileUsed()).Infof("config file loaded")
v.WatchConfig()
v.OnConfigChange(func(e fsnotify.Event) {
log.WithField("file", e.Name).Info("config file changed")
})
} else if cfgFile != "" {
log.WithError(err).Warningf("Error reading config file: %v", cfgFile)
}
if logger.Level == log.DebugLevel {
v.Debug()
}
return v
}
// validateConfig checks the values provided to all of the configuration
// options, ensuring that e.g. `since` is a valid date, `jira-uri` is a
// real URI, etc. This is the first level of checking. It does not confirm
// if a Jira cli is running at `jira-uri` for example; that is checked
// in getJiraClient when we actually make a call to the API.
func (c *Config) validateConfig() error {
// Log level and config file location are validated already
log.Debug("Checking config variables...")
token := c.cmdConfig.GetString(options.ConfigKeyGitHubToken)
if token == "" {
return errGitHubTokenRequired
}
c.basicAuth = (c.cmdConfig.GetString(options.ConfigKeyJiraUser) != "") &&
(c.cmdConfig.GetString(options.ConfigKeyJiraPassword) != "")
if c.basicAuth { //nolint:nestif // TODO(lint)
log.Debug("Using HTTP Basic Authentication")
jUser := c.cmdConfig.GetString(options.ConfigKeyJiraUser)
if jUser == "" {
return errJiraUsernameRequired
}
jPass := c.cmdConfig.GetString(options.ConfigKeyJiraPassword)
if jPass == "" {
fmt.Print("Enter your Jira password: ")
bytePass, err := term.ReadPassword(syscall.Stdin)
if err != nil {
return errJiraPasswordRequired
}
fmt.Println()
c.cmdConfig.Set(options.ConfigKeyJiraPassword, string(bytePass))
}
} else {
log.Debug("Using OAuth 1.0a authentication")
token := c.cmdConfig.GetString(options.ConfigKeyJiraToken)
if token == "" {
return errJiraAccessTokenRequired
}
secret := c.cmdConfig.GetString(options.ConfigKeyJiraSecret)
if secret == "" {
return errJiraAccessTokenSecretRequired
}
consumerKey := c.cmdConfig.GetString(options.ConfigKeyJiraConsumerKey)
if consumerKey == "" {
return errJiraConsumerKeyRequired
}
privateKey := c.cmdConfig.GetString(options.ConfigKeyJiraPrivateKeyPath)
if privateKey == "" {
return errJiraPrivateKeyRequired
}
_, err := os.Open(privateKey)
if err != nil {
return errJiraPEMFileInvalid
}
}
repo := c.cmdConfig.GetString(options.ConfigKeyRepoName)
if repo == "" {
return errGitHubRepoRequired
}
if !strings.Contains(repo, "/") || len(strings.Split(repo, "/")) != 2 {
return errGitHubRepoFormatInvalid
}
uri := c.cmdConfig.GetString(options.ConfigKeyJiraURI)
if uri == "" {
return errJiraURIRequired
}
if _, err := url.ParseRequestURI(uri); err != nil {
return errJiraURIInvalid
}
project := c.cmdConfig.GetString(options.ConfigKeyJiraProject)
if project == "" {
return errJiraProjectRequired
}
sinceStr := c.cmdConfig.GetString(options.ConfigKeySince)
if sinceStr == "" {
c.cmdConfig.Set(options.ConfigKeySince, options.DefaultSince)
}
since, err := time.Parse(options.DateFormat, sinceStr)
if err != nil {
return errDateInvalid
}
c.since = since
log.Debug("All config variables are valid!")
return nil
}
// getFieldIDs requests the metadata of every issue field in the Jira
// project, and saves the IDs of the custom fields used by issue-sync.
func (c *Config) getFieldIDs(client *jira.Client) (*fields, error) {
log.Debug("Collecting field IDs.")
req, err := client.NewRequest(c.Context(), "GET", "/rest/api/2/field", nil)
if err != nil {
return nil, fmt.Errorf("getting fields: %w", err)
}
jFieldsPtr := new([]jira.Field)
_, err = client.Do(req, jFieldsPtr)
if err != nil {
return nil, fmt.Errorf("getting field IDs: %w", err)
}
jFields := *jFieldsPtr
var fieldIDs fields
for i := range jFields {
field := jFields[i]
switch field.Name {
case CustomFieldNameGitHubID:
fieldIDs.githubID = fmt.Sprint(field.Schema.CustomID)
case CustomFieldNameGitHubNumber:
fieldIDs.githubNumber = fmt.Sprint(field.Schema.CustomID)
case CustomFieldNameGitHubLabels:
fieldIDs.githubLabels = fmt.Sprint(field.Schema.CustomID)
case CustomFieldNameGitHubStatus:
fieldIDs.githubStatus = fmt.Sprint(field.Schema.CustomID)
case CustomFieldNameGitHubReporter:
fieldIDs.githubReporter = fmt.Sprint(field.Schema.CustomID)
case CustomFieldNameGitHubLastSync:
fieldIDs.lastUpdate = fmt.Sprint(field.Schema.CustomID)
}
}
if fieldIDs.githubID == "" {
return nil, errCustomFieldIDNotFound(CustomFieldNameGitHubID)
}
if fieldIDs.githubNumber == "" {
return nil, errCustomFieldIDNotFound(CustomFieldNameGitHubNumber)
}
if fieldIDs.githubLabels == "" {
return nil, errCustomFieldIDNotFound(CustomFieldNameGitHubLabels)
}
if fieldIDs.githubStatus == "" {
return nil, errCustomFieldIDNotFound(CustomFieldNameGitHubStatus)
}
if fieldIDs.githubReporter == "" {
return nil, errCustomFieldIDNotFound(CustomFieldNameGitHubReporter)
}
if fieldIDs.lastUpdate == "" {
return nil, errCustomFieldIDNotFound(CustomFieldNameGitHubLastSync)
}
log.Debug("All fields have been checked.")
return &fieldIDs, nil
}
// getComponents resolves every component set in config against
// Jira project, and returns with these components used by issue-sync.
func (c *Config) getComponents(proj *jira.Project) ([]*jira.Component, error) {
var returnComponents []*jira.Component
components := c.cmdConfig.GetStringSlice(options.ConfigKeyJiraComponents)
for _, configComponent := range components {
found := false
for j := range proj.Components {
projComponent := &proj.Components[j]
if projComponent.Name == configComponent {
found = true
foundComponent := jira.Component{
Name: projComponent.Name,
ID: projComponent.ID,
}
returnComponents = append(returnComponents, &foundComponent)
}
}
if !found {
log.Errorf("The Jira project does not have such component defined: %s", configComponent)
return nil, ReadingJiraComponentError(configComponent)
}
}
return returnComponents, nil
}
// Errors
var (
errGitHubTokenRequired = errors.New("github token required")
errJiraUsernameRequired = errors.New("jira username required")
errJiraPasswordRequired = errors.New("jira password required")
errJiraAccessTokenRequired = errors.New("jira access token required")
errJiraAccessTokenSecretRequired = errors.New("jira access token secret required")
errJiraConsumerKeyRequired = errors.New("jira consumer key required for OAuth handshake")
errJiraPrivateKeyRequired = errors.New("jira private key required for OAuth handshake")
errJiraPEMFileInvalid = errors.New("jira private key must point to existing PEM file")
errGitHubRepoRequired = errors.New("github repository required")
errGitHubRepoFormatInvalid = errors.New("github repository must be of form user/repo")
errJiraURIRequired = errors.New("jira URI required")
errJiraURIInvalid = errors.New("jira URI must be valid URI")
errJiraProjectRequired = errors.New("jira project required")
errDateInvalid = errors.New("`since` date must be in ISO-8601 format")
)
func errCustomFieldIDNotFound(field string) error {
return fmt.Errorf("could not find ID custom field '%s'; check that it is named correctly", field) //nolint:goerr113
}
type ReadingJiraComponentError string
func (r ReadingJiraComponentError) Error() string {
return fmt.Sprintf("could not find Jira component: %s; check that it is named correctly", string(r))
}