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 all 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.12.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
123 changes: 100 additions & 23 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package config

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

"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 @@ const (
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 @@ type Config struct {
// 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 @@ type Config struct {
// 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

// 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.
Expand Down Expand Up @@ -137,7 +150,8 @@ func New(ctx context.Context, cmd *cobra.Command) (*Config, error) {

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)
cfg.cmdConfig.BindPFlags(cmd.Flags()) //nolint:errcheck

cfg.cmdFile = cfg.cmdConfig.ConfigFileUsed()
Expand All @@ -148,6 +162,10 @@ func New(ctx context.Context, cmd *cobra.Command) (*Config, error) {
return nil, err
}

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

return &cfg, nil
}

Expand Down Expand Up @@ -287,25 +305,25 @@ func (c *Config) SetJiraToken(token *oauth1.Token) {

// 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"`
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"`
JiraComponents []string `mapstructure:"jira-components"`
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 {
c.cmdConfig.Set(
options.ConfigKeySince,
time.Now().Format(options.DateFormat),
Expand All @@ -316,9 +334,14 @@ func (c *Config) SaveConfig() error {
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)
}

b, err := c.encoderRegistry.Encode(c.cmdFileType, cfMap)
if err != nil {
return fmt.Errorf("marshalling config: %w", err)
return fmt.Errorf("encoding config to %s format: %w", c.cmdFileType, err)
}

f, err := os.OpenFile(c.cmdConfig.ConfigFileUsed(), os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0o644)
Expand All @@ -340,7 +363,7 @@ func (c *Config) SaveConfig() error {
// 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 {
logger := log.New()
v := viper.New()

Expand All @@ -353,7 +376,7 @@ func newViper(appName, cfgFile string) *viper.Viper {
if cfgFile != "" {
v.SetConfigFile(cfgFile)
}
v.SetConfigType("json")
v.SetConfigType(cfgFileType)

if err := v.ReadInConfig(); err == nil {
log.WithField("file", v.ConfigFileUsed()).Infof("config file loaded")
Expand Down Expand Up @@ -533,6 +556,47 @@ func (c *Config) getFieldIDs(client *jira.Client) (*fields, error) {
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)
}

return nil
}

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

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

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

c.encoderRegistry = encoderRegistry
return 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) {
Expand Down Expand Up @@ -589,6 +653,19 @@ 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, ".")
}

type ReadingJiraComponentError string

func (r ReadingJiraComponentError) Error() string {
Expand Down
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