Skip to content

Commit

Permalink
Command and config improvements (#3)
Browse files Browse the repository at this point in the history
* refactor commands and config to use cobra and viper

* use git version number

* show version in intro

* updated readme

* fix broken link in readme
  • Loading branch information
KarnerTh authored Mar 12, 2022
1 parent e45c32f commit 7076781
Show file tree
Hide file tree
Showing 16 changed files with 384 additions and 198 deletions.
11 changes: 4 additions & 7 deletions .github/workflows/release_build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,21 @@ name: goreleaser
on:
push:
tags:
- "*"
- "*"

jobs:
goreleaser:
runs-on: ubuntu-latest
steps:
-
name: Checkout
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
-
name: Set up Go
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17
-
name: Run GoReleaser
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v2
with:
distribution: goreleaser
Expand Down
7 changes: 7 additions & 0 deletions .mermerd.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
showAllConstraints: true
outputFileName: "my-db.mmd"

# These connection strings are available as suggestions in the cli (use tab to access)
connectionStringSuggestions:
- postgresql://user:password@localhost:5432/yourDb
- mysql://root:password@tcp(127.0.0.1:3306)/yourDb
24 changes: 13 additions & 11 deletions analyzer/analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,12 @@ func Analyze() (*database.Result, error) {
return nil, err
}

var connectionString string
if config.ConnectionString == "" {
connectionString := config.ConnectionString()
if config.ConnectionString() == "" {
err = survey.AskOne(ConnectionQuestion(), &connectionString, survey.WithValidator(survey.Required))
if err != nil {
return nil, err
}
} else {
connectionString = config.ConnectionString
}

loading.Start("Connecting to database and getting schemas")
Expand All @@ -36,8 +34,8 @@ func Analyze() (*database.Result, error) {
}
defer db.Close()

var selectedSchema string
if config.Schema == "" {
selectedSchema := config.Schema()
if selectedSchema == "" {
schemas, err := db.GetSchemas()
if err != nil {
return nil, err
Expand All @@ -56,8 +54,6 @@ func Analyze() (*database.Result, error) {
return nil, err
}
}
} else {
selectedSchema = config.Schema
}

// get tables
Expand All @@ -69,9 +65,15 @@ func Analyze() (*database.Result, error) {
}
loading.Stop()

err = survey.AskOne(TableQuestion(tables), &selectedTables, survey.WithValidator(survey.MinItems(1)))
if err != nil {
return nil, err
if config.UseAllTables() {
selectedTables = tables
} else if len(config.SelectedTables()) > 0 {
selectedTables = config.SelectedTables()
} else {
err = survey.AskOne(TableQuestion(tables), &selectedTables, survey.WithValidator(survey.MinItems(1)))
if err != nil {
return nil, err
}
}

// get columns and constraints
Expand Down
4 changes: 2 additions & 2 deletions analyzer/questions.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import (

func ConnectionQuestion() survey.Prompt {
return &survey.Input{
Message: "Connection string",
Message: "Connection string:",
Suggest: func(toComplete string) []string {
return config.ConnectionStringSuggestions
return config.ConnectionStringSuggestions()
},
}
}
Expand Down
84 changes: 84 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package cmd

import (
"fmt"
"github.com/fatih/color"
"mermerd/analyzer"
"mermerd/config"
"mermerd/diagram"
"mermerd/util"
"os"

"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var runConfig string

var rootCmd = &cobra.Command{
Use: "mermerd",
Short: "Create Mermaid ERD diagrams from existing tables",
Long: "Create Mermaid ERD diagrams from existing tables",
Run: func(cmd *cobra.Command, args []string) {
util.ShowIntro()
result, err := analyzer.Analyze()
if err != nil {
fmt.Println(err.Error())
util.ShowError()
os.Exit(1)
}

err = diagram.Create(result)
if err != nil {
fmt.Println(err.Error())
util.ShowError()
os.Exit(1)
}

util.ShowSuccess()
},
}

func Execute() {
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
}

func init() {
cobra.OnInitialize(initConfig)

rootCmd.Flags().StringVar(&runConfig, "runConfig", "", "run configuration (replaces global configuration)")
rootCmd.Flags().Bool(config.ShowAllConstraintsKey, false, "show all constraints, even though the table of the resulting constraint was not selected")
rootCmd.Flags().Bool(config.UseAllTablesKey, false, "use all available tables")
rootCmd.Flags().StringP(config.ConnectionStringKey, "c", "", "connection string that should be used")
rootCmd.Flags().StringP(config.SchemaKey, "s", "", "schema that should be used")
rootCmd.Flags().StringP(config.OutputFileNameKey, "o", "result.mmd", "output file name")

bindFlagToViper(config.ShowAllConstraintsKey)
bindFlagToViper(config.UseAllTablesKey)
bindFlagToViper(config.ConnectionStringKey)
bindFlagToViper(config.SchemaKey)
bindFlagToViper(config.OutputFileNameKey)
}

func bindFlagToViper(key string) {
_ = viper.BindPFlag(key, rootCmd.Flags().Lookup(key))
}

func initConfig() {
if runConfig != "" {
color.Blue(fmt.Sprintf("Using run configuration (from %s)", runConfig))
viper.SetConfigFile(runConfig)
} else {
home, err := os.UserHomeDir()
cobra.CheckErr(err)

viper.AddConfigPath(home)
viper.SetConfigType("yaml")
viper.SetConfigName(".mermerd")
}

err := viper.ReadInConfig()
cobra.CheckErr(err)
}
21 changes: 21 additions & 0 deletions cmd/version.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package cmd

import (
"fmt"
"github.com/spf13/viper"

"github.com/spf13/cobra"
)

var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version number of mermerd",
Long: "All software has versions. This is mermerd's",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("mermerd %s %s\n", viper.Get("version"), viper.Get("commit"))
},
}

func init() {
rootCmd.AddCommand(versionCmd)
}
43 changes: 39 additions & 4 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,41 @@
package config

var ShowAllConstraints bool
var Schema string
var ConnectionString string
var ConnectionStringSuggestions []string
import "github.com/spf13/viper"

const (
ShowAllConstraintsKey = "showAllConstraints"
UseAllTablesKey = "useAllTables"
SelectedTablesKey = "selectedTables"
SchemaKey = "schema"
ConnectionStringKey = "connectionString"
ConnectionStringSuggestionsKey = "connectionStringSuggestions"
OutputFileNameKey = "outputFileName"
)

func ShowAllConstraints() bool {
return viper.GetBool(ShowAllConstraintsKey)
}

func UseAllTables() bool {
return viper.GetBool(UseAllTablesKey)
}

func Schema() string {
return viper.GetString(SchemaKey)
}

func ConnectionString() string {
return viper.GetString(ConnectionStringKey)
}

func OutputFileName() string {
return viper.GetString(OutputFileNameKey)
}

func ConnectionStringSuggestions() []string {
return viper.GetStringSlice(ConnectionStringSuggestionsKey)
}

func SelectedTables() []string {
return viper.GetStringSlice(SelectedTablesKey)
}
85 changes: 0 additions & 85 deletions config/config_file.go

This file was deleted.

4 changes: 2 additions & 2 deletions diagram/diagram.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
)

func Create(result *database.Result) error {
f, err := os.Create("result.mmd")
f, err := os.Create(config.OutputFileName())
if err != nil {
return err
}
Expand Down Expand Up @@ -52,7 +52,7 @@ func Create(result *database.Result) error {

constraints := strings.Builder{}
for _, constraint := range allConstraints {
if (!sliceContainsItem(tableNames, constraint.PKTable) || !sliceContainsItem(tableNames, constraint.FkTable)) && !config.ShowAllConstraints {
if (!sliceContainsItem(tableNames, constraint.PKTable) || !sliceContainsItem(tableNames, constraint.FkTable)) && !config.ShowAllConstraints() {
continue
}

Expand Down
13 changes: 13 additions & 0 deletions exampleRunConfig.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Connection properties
connectionString: "postgresql://user:password@localhost:5432/dvdrental"
schema: "public"

# Define what tables should be used
#useAllTables: true
selectedTables:
- city
- customer

# Additional flags
showAllConstraints: true
outputFileName: "my-db.mmd"
Loading

0 comments on commit 7076781

Please sign in to comment.