Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support multiple config file types #172

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,16 @@ in

### Application Configuration

Arguments to the program may be passed on the command line or in a JSON
configuration file.
Arguments to the program may be passed on the command line or in a configuration file.
Currently supported configuration file types are: JSON, YAML, TOML.

For the command line arguments, run:

```console
gh-jira-issue-sync help
```

The JSON format is a single, flat object, with the argument long
The configuration is a single, flat object, with the argument long
names as keys.

Configuration arguments are as follows:
Expand Down
2 changes: 1 addition & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ var RootCmd = &cobra.Command{
logrus.Error(err)
}
if !cfg.IsDryRun() {
if err := cfg.SaveConfig(); err != nil {
if err := cfg.UpdateConfig(); err != nil {
// TODO(log): Better error message
logrus.Error(err)
}
Expand Down
9 changes: 6 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,18 @@ require (
github.com/fsnotify/fsnotify v1.6.0
github.com/google/go-github/v53 v53.2.0
github.com/magefile/mage v1.15.0
github.com/mitchellh/mapstructure v1.5.0
github.com/pelletier/go-toml/v2 v2.0.8
github.com/sirupsen/logrus v1.9.3
github.com/spf13/cobra v1.7.0
github.com/spf13/viper v1.16.0
github.com/stretchr/testify v1.8.4
github.com/trivago/tgo v1.0.7
github.com/uwu-tools/go-jira/v2 v2.0.0-20230801175343-52f822b5cb80
github.com/uwu-tools/magex v0.10.0
golang.org/x/oauth2 v0.11.0
golang.org/x/term v0.11.0
gopkg.in/yaml.v3 v3.0.1
sigs.k8s.io/release-sdk v0.10.3
sigs.k8s.io/release-utils v0.7.5-0.20230814131120-e16435f5a2de
)
Expand All @@ -37,6 +41,7 @@ require (
github.com/blang/semver/v4 v4.0.0 // indirect
github.com/cloudflare/circl v1.3.3 // indirect
github.com/common-nighthawk/go-figure v0.0.0-20210622060536-734e95fb86be // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dsnet/compress v0.0.2-0.20210315054119-f66993602bf5 // indirect
github.com/emirpasic/gods v1.18.1 // indirect
github.com/fatih/structs v1.1.0 // indirect
Expand All @@ -57,11 +62,10 @@ require (
github.com/klauspost/pgzip v1.2.5 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mholt/archiver/v3 v3.5.1 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/nwaples/rardecode v1.1.0 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/pierrec/lz4/v4 v4.1.2 // indirect
github.com/pjbgf/sha1cd v0.3.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/sergi/go-diff v1.3.1 // indirect
github.com/skeema/knownhosts v1.1.1 // indirect
github.com/spf13/afero v1.9.5 // indirect
Expand All @@ -82,6 +86,5 @@ require (
google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/utils v0.0.0-20230406110748-d93618cff8a2 // indirect
)
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/subosito/gotenv v1.4.2 h1:X1TuBLAMDFbaTAChgCBLu3DU3UPyELpnF2jjJ2cz/S8=
github.com/subosito/gotenv v1.4.2/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0=
github.com/trivago/tgo v1.0.7 h1:uaWH/XIy9aWYWpjm2CU3RpcqZXmX2ysQ9/Go+d9gyrM=
Expand Down
121 changes: 99 additions & 22 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
Expand All @@ -31,12 +30,17 @@

"github.com/dghubble/oauth1"
"github.com/fsnotify/fsnotify"
"github.com/mitchellh/mapstructure"
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/encoding"
"github.com/uwu-tools/gh-jira-issue-sync/internal/encoding/json"
"github.com/uwu-tools/gh-jira-issue-sync/internal/encoding/toml"
"github.com/uwu-tools/gh-jira-issue-sync/internal/encoding/yaml"
"github.com/uwu-tools/gh-jira-issue-sync/internal/github"
"github.com/uwu-tools/gh-jira-issue-sync/internal/options"
)
Expand All @@ -59,6 +63,9 @@
CustomFieldNameGitHubStatus = "github-status"
CustomFieldNameGitHubReporter = "github-reporter"
CustomFieldNameGitHubLastSync = "github-last-sync"

// Config file related constants.
DefaultConfigFileType = "json"
)

// fields represents the custom field IDs of the Jira custom fields we care about.
Expand All @@ -78,6 +85,9 @@
// cmdFile is the file Viper is using for its configuration.
cmdFile string

// cmdFileType is the extension of the config file.
cmdFileType string

// cmdConfig is the Viper configuration object created from the command line and config file.
cmdConfig viper.Viper

Expand All @@ -94,6 +104,9 @@
// project represents the Jira project the user has requested.
project *jira.Project

// encoderRegistry is used for encoding the config file to supported Viper types.
encoderRegistry *encoding.EncoderRegistry

// 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
Expand Down Expand Up @@ -132,7 +145,8 @@

log.Debugf("using config file: %s", cfgFilePath)
cfg.cmdFile = cfgFilePath
cfg.cmdConfig = *newViper(options.AppName, cfg.cmdFile)
cfg.cmdFileType = getConfigTypeFromName(cfgFilePath)
cfg.cmdConfig = *newViper(options.AppName, cfg.cmdFile, cfg.cmdFileType)

Check warning on line 149 in internal/config/config.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config.go#L148-L149

Added lines #L148 - L149 were not covered by tests
cfg.cmdConfig.BindPFlags(cmd.Flags()) //nolint:errcheck

cfg.cmdFile = cfg.cmdConfig.ConfigFileUsed()
Expand All @@ -143,6 +157,10 @@
return nil, err
}

if err := cfg.resetEncoding(); err != nil {
return nil, err
}

Check warning on line 162 in internal/config/config.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config.go#L160-L162

Added lines #L160 - L162 were not covered by tests

return &cfg, nil
}

Expand Down Expand Up @@ -272,24 +290,24 @@

// 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"`
Confirm bool `json:"confirm,omitempty" mapstructure:"confirm"`
Timeout time.Duration `json:"timeout,omitempty" mapstructure:"timeout"`
LogLevel string `mapstructure:"log-level,omitempty"`
GithubToken string `mapstructure:"github-token,omitempty"`
JiraUser string `mapstructure:"jira-user,omitempty"`
JiraPass string `mapstructure:"jira-pass,omitempty"`
JiraToken string `mapstructure:"jira-token,omitempty"`
JiraSecret string `mapstructure:"jira-secret,omitempty"`
JiraKey string `mapstructure:"jira-private-key-path,omitempty"`
JiraCKey string `mapstructure:"jira-consumer-key,omitempty"`
RepoName string `mapstructure:"repo-name,omitempty"`
JiraURI string `mapstructure:"jira-uri,omitempty"`
JiraProject string `mapstructure:"jira-project,omitempty"`
Since string `mapstructure:"since,omitempty"`
Confirm bool `mapstructure:"confirm,omitempty"`
Timeout time.Duration `mapstructure:"timeout,omitempty"`
}

// SaveConfig updates the `since` parameter to now, then saves the configuration file.
func (c *Config) SaveConfig() error {
// UpdateConfig updates the `since` parameter to now, then saves the configuration file.
func (c *Config) UpdateConfig() error {

Check warning on line 310 in internal/config/config.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config.go#L310

Added line #L310 was not covered by tests
c.cmdConfig.Set(
options.ConfigKeySince,
time.Now().Format(options.DateFormat),
Expand All @@ -300,9 +318,14 @@
return fmt.Errorf("unmarshalling config: %w", err)
}

b, err := json.MarshalIndent(cf, "", " ")
cfMap := make(map[string]interface{})
if err := mapstructure.Decode(cf, &cfMap); err != nil {
return fmt.Errorf("decoding configFile struct to map[string]interface{}: %w", err)
}

Check warning on line 324 in internal/config/config.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config.go#L321-L324

Added lines #L321 - L324 were not covered by tests

b, err := c.encoderRegistry.Encode(c.cmdFileType, cfMap)

Check warning on line 326 in internal/config/config.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config.go#L326

Added line #L326 was not covered by tests
if err != nil {
return fmt.Errorf("marshalling config: %w", err)
return fmt.Errorf("encoding config to %s format: %w", c.cmdFileType, err)

Check warning on line 328 in internal/config/config.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config.go#L328

Added line #L328 was not covered by tests
}

f, err := os.OpenFile(c.cmdConfig.ConfigFileUsed(), os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0o644)
Expand All @@ -324,7 +347,7 @@
// 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 {
func newViper(appName, cfgFile, cfgFileType string) *viper.Viper {

Check warning on line 350 in internal/config/config.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config.go#L350

Added line #L350 was not covered by tests
logger := log.New()
v := viper.New()

Expand All @@ -337,7 +360,7 @@
if cfgFile != "" {
v.SetConfigFile(cfgFile)
}
v.SetConfigType("json")
v.SetConfigType(cfgFileType)

Check warning on line 363 in internal/config/config.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config.go#L363

Added line #L363 was not covered by tests

if err := v.ReadInConfig(); err == nil {
log.WithField("file", v.ConfigFileUsed()).Infof("config file loaded")
Expand Down Expand Up @@ -517,6 +540,47 @@
return &fieldIDs, nil
}

// resetEncoding creates a new encoding registry with the currently supported file formats.
func (c *Config) resetEncoding() error {
encoderRegistry := encoding.NewEncoderRegistry()
registerEncoder := func(format string, codec encoding.Encoder) error {
if err := encoderRegistry.RegisterEncoder(format, codec); err != nil {
return fmt.Errorf("registering encoder for %s extension: %w", format, err)
}

Check warning on line 549 in internal/config/config.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config.go#L544-L549

Added lines #L544 - L549 were not covered by tests

return nil

Check warning on line 551 in internal/config/config.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config.go#L551

Added line #L551 was not covered by tests
}

{
codec := &yaml.Codec{}
if err := registerEncoder("yaml", codec); err != nil {
return err
}
if err := registerEncoder("yml", codec); err != nil {
return err
}

Check warning on line 561 in internal/config/config.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config.go#L554-L561

Added lines #L554 - L561 were not covered by tests
}

{
codec := &json.Codec{
Indent: " ",
}
if err := registerEncoder("json", codec); err != nil {
return err
}

Check warning on line 570 in internal/config/config.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config.go#L564-L570

Added lines #L564 - L570 were not covered by tests
}

{
codec := &toml.Codec{}
if err := registerEncoder("toml", codec); err != nil {
return err
}

Check warning on line 577 in internal/config/config.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config.go#L573-L577

Added lines #L573 - L577 were not covered by tests
}

c.encoderRegistry = encoderRegistry
return nil

Check warning on line 581 in internal/config/config.go

View check run for this annotation

Codecov / codecov/patch

internal/config/config.go#L580-L581

Added lines #L580 - L581 were not covered by tests
}

// Errors

var (
Expand All @@ -539,3 +603,16 @@
func errCustomFieldIDNotFound(field string) error {
return fmt.Errorf("could not find ID custom field '%s'; check that it is named correctly", field) //nolint:goerr113
}

// getConfigTypeFromName extracts the extension from the passed in filename,
// returns json if it's empty.
func getConfigTypeFromName(filename string) string {
// it's enough to rely on the type from the filename because
// viper will parse and validate the file's content
ext := filepath.Ext(filename)
if ext == "" {
return DefaultConfigFileType
}

return strings.TrimPrefix(ext, ".")
}
46 changes: 46 additions & 0 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package config

import (
"fmt"
"testing"

"github.com/stretchr/testify/assert"
)

func TestGetConfigTypeFromName(t *testing.T) {
tests := []*struct {
name, filename, expected string
}{
{
name: "empty name",
filename: "",
expected: "json",
},
{
name: "json",
filename: "config.json",
expected: "json",
},
{
name: "toml",
filename: "config.toml",
expected: "toml",
},
{
name: "yaml",
filename: "config.yaml",
expected: "yaml",
},
{
name: "any file type",
filename: "config.xyz",
expected: "xyz",
},
}

for _, test := range tests {
t.Run(fmt.Sprintf("Assert config type with %s", test.name), func(t *testing.T) {
assert.Equal(t, test.expected, getConfigTypeFromName(test.filename))
})
}
}
Loading