Skip to content

Commit

Permalink
chore: extract format from api
Browse files Browse the repository at this point in the history
Signed-off-by: Sebastian Webber <[email protected]>
  • Loading branch information
sebastianwebber committed Apr 23, 2022
1 parent 54b5e1b commit ef8ec62
Show file tree
Hide file tree
Showing 5 changed files with 97 additions and 108 deletions.
66 changes: 11 additions & 55 deletions cmd/api/handlers/v1/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import (
"github.com/pgconfig/api/pkg/defaults"
"github.com/pgconfig/api/pkg/docs"
"github.com/pgconfig/api/pkg/format"
"github.com/pgconfig/api/pkg/profile"
"github.com/pgconfig/api/pkg/rules"
"github.com/pgconfig/api/pkg/version"
)

// GetConfig is a function to that computes the input and suggests a tuning configuration
Expand Down Expand Up @@ -51,16 +51,11 @@ func GetConfig(c *fiber.Ctx) error {
return fmt.Errorf("could not process config: %w", err)
}

switch args.outFormat {
case "alter_system", "sql":
if args.outFormat != format.JSON {
return c.SendString(formatConf(c, args.outFormat, finalData, args.pgVersion))
case "conf", "config":
return c.SendString(formatConf(c, args.outFormat, finalData, args.pgVersion))
case "stackgres", "sg", "sgpostgresconfig":
return c.SendString(formatConf(c, args.outFormat, finalData, args.pgVersion))
default:
return c.JSON(v1Reponse(c, finalData))
}

return c.JSON(v1Reponse(c, finalData))
}

func processConfig(c *fiber.Ctx, args *configArgs) ([]category.SliceOutput, error) {
Expand Down Expand Up @@ -138,12 +133,12 @@ func parseConfigArgs(c *fiber.Ctx) (*configArgs, error) {
pgVersion: float32(pgVersion),
totalRAM: parseRAM(strings.ToUpper(c.Query("total_ram", "2GB"))),
maxConn: maxConn,
envName: c.Query("environment_name", "WEB"),
envName: profile.Profile(c.Query("environment_name", "WEB")),
osType: c.Query("os_type", "linux"),
arch: c.Query("arch", "amd64"),
driveType: c.Query("drive_type", "HDD"),
cpuCount: cpuCount,
outFormat: c.Query("format", "json"),
outFormat: format.ExportFormat(c.Query("format", "json")),
showDoc: c.Query("show_doc", "false") == "true",
includePgbadger: c.Query("include_pgbadger", "false") == "true",
logFormat: c.Query("log_format", "stderr"),
Expand All @@ -154,60 +149,21 @@ type configArgs struct {
pgVersion float32
totalRAM config.Byte
maxConn int
envName string
envName profile.Profile
osType string
arch string
driveType string
cpuCount int
outFormat string
outFormat format.ExportFormat
showDoc bool
includePgbadger bool
logFormat string
}

func formatConf(c *fiber.Ctx, f string, output []category.SliceOutput, pgVersion float32) string {

var comment string

switch f {
case "alter_system":
comment = "--"
default:
comment = "#"
}

var b bytes.Buffer

switch f {
case "stackgres", "sg", "sgpostgresconfig":
b.WriteString("---\n")
}
b.WriteString(fmt.Sprintf("%s Generated by PGConfig %s\n", fillComment(1, comment), version.Pretty()))
b.WriteString(fmt.Sprintf("%s %s%s\n", fillComment(1, comment), c.BaseURL(), c.OriginalURL()))
b.WriteString("\n")

switch f {
case "alter_system", "sql":
b.WriteString(format.AlterSystem(output))
return b.String()
case "stackgres", "sg", "sgpostgresconfig":
b.WriteString(format.SGConfigFile(output, fmt.Sprintf("%.f", pgVersion)))
return b.String()
default:
b.WriteString(format.ConfigFile(output))
return b.String()
}

}

func fillComment(qtd int, comment string) string {
var b bytes.Buffer

for i := 0; i < qtd; i++ {
b.WriteString(comment)
}
func formatConf(c *fiber.Ctx, f format.ExportFormat, output []category.SliceOutput, pgVersion float32) string {
extra := fmt.Sprintf("%s%s\n", c.BaseURL(), c.OriginalURL())

return b.String()
return format.ExportConf(f, output, pgVersion, extra)
}

func parseRAM(compared string) config.Byte {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,16 @@ func GetConfigEnvs(c *fiber.Ctx) error {

var out []allEnvsOutput

for _, env := range profile.AllProfiles {
args.envName = env
for _, profile := range profile.AllProfiles {
args.envName = profile
finalData, err := processConfig(c, args)

if err != nil {
return fmt.Errorf("could not process config: %w", err)
}

out = append(out, allEnvsOutput{
EnvName: env,
EnvName: profile,
Config: finalData,
})
}
Expand All @@ -54,6 +54,6 @@ func GetConfigEnvs(c *fiber.Ctx) error {
}

type allEnvsOutput struct {
EnvName string `json:"environment"`
EnvName profile.Profile `json:"environment"`
Config []category.SliceOutput `json:"configuration"`
}
40 changes: 1 addition & 39 deletions cmd/pgconfigctl/cmd/tune.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,15 @@ THE SOFTWARE.
*/

import (
"encoding/json"
"fmt"
"os"
"runtime"

"github.com/pgconfig/api/pkg/category"
"github.com/pgconfig/api/pkg/config"
"github.com/pgconfig/api/pkg/defaults"
"github.com/pgconfig/api/pkg/format"
"github.com/pgconfig/api/pkg/profile"
"github.com/pgconfig/api/pkg/rules"
"github.com/pgconfig/api/pkg/version"
"github.com/spf13/cobra"

"github.com/mackerelio/go-osstat/memory"
Expand Down Expand Up @@ -77,25 +74,7 @@ var tuneCmd = &cobra.Command{
}

data := out.ToSlice(pgVersion, includePgbadger, logFormat)

switch outputFormat {
case format.JSON:
b, err := json.MarshalIndent(data, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(b))
case format.Config, format.UNIX:
export("config", data)
case format.SQL, format.AlterSystemFormat:
export("sql", data)
case format.StackGres, format.StackGresShort, format.SGPGConfig, format.YAML:
exportStackgres("stackgres", data)
default:
fmt.Println("Invalid export format")
os.Exit(1)
}

fmt.Println(format.ExportConf(outputFormat, data, pgVersion, ""))
},
}

Expand Down Expand Up @@ -131,20 +110,3 @@ func init() {
tuneCmd.PersistentFlags().Lookup("format").DefValue = outputFormat.String()
tuneCmd.PersistentFlags().Parse(os.Args[1:])
}

func export(f string, report []category.SliceOutput) {

if f == "config" {
fmt.Printf("## Generated by pgconfigctl-%s\n\n", version.Pretty())
fmt.Println(format.ConfigFile(report))
return
}

fmt.Printf("-- Generated by pgconfigctl-%s\n\n", version.Pretty())
fmt.Println(format.AlterSystem(report))
}

func exportStackgres(c string, report []category.SliceOutput) {
fmt.Printf("---\n")
fmt.Println(format.SGConfigFile(report, fmt.Sprintf("%.f", pgVersion)))
}
76 changes: 66 additions & 10 deletions pkg/format/format.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
package format

import (
"bytes"
"fmt"
"strings"

"github.com/pgconfig/api/pkg/category"
"github.com/pgconfig/api/pkg/version"
)

type ExportFormat string

const (
JSON ExportFormat = "JSON"
Config ExportFormat = "CONF"
UNIX ExportFormat = "UNIX"
AlterSystemFormat ExportFormat = "ALTER-SYSTEM"
SQL ExportFormat = "SQL"
StackGres ExportFormat = "STACKGRES"
StackGresShort ExportFormat = "SG"
SGPGConfig ExportFormat = "SGPOSTGRESCONFIG"
YAML ExportFormat = "YAML"
JSON ExportFormat = "json"
Config ExportFormat = "conf"
UNIX ExportFormat = "unix"
AlterSystemFormat ExportFormat = "alter_system"
SQL ExportFormat = "sql"
StackGres ExportFormat = "stackgres"
StackGresShort ExportFormat = "sg"
SGPGConfig ExportFormat = "sgpostgresconfig"
YAML ExportFormat = "yaml"
)

// AllExportFormats Lists all of the export options available
Expand All @@ -30,7 +34,7 @@ func (e *ExportFormat) String() string {
// Set must have pointer receiver so it doesn't change the value of a copy
func (e *ExportFormat) Set(v string) error {

newV := ExportFormat(strings.ToUpper(v))
newV := ExportFormat(strings.ToLower(v))

switch newV {
case JSON, Config, UNIX, AlterSystemFormat, SQL, StackGres, StackGresShort, SGPGConfig, YAML:
Expand All @@ -45,3 +49,55 @@ func (e *ExportFormat) Set(v string) error {
func (e *ExportFormat) Type() string {
return "ExportFormat"
}

func ExportConf(f ExportFormat, output []category.SliceOutput, pgVersion float32, extra string) string {

var comment string

switch f {
case AlterSystemFormat, SQL:
comment = "--"
default:
comment = "#"
}

var b bytes.Buffer

switch f {
case StackGres, StackGresShort, SGPGConfig, YAML:
b.WriteString("---\n")
}

if f != JSON {
b.WriteString(fmt.Sprintf("%s Generated by PGConfig %s\n", fillComment(1, comment), version.Pretty()))
if extra != "" {
b.WriteString((fmt.Sprintf("%s %s", fillComment(1, comment), extra)))
}
b.WriteString("\n")
}

switch f {
case SQL, AlterSystemFormat:
b.WriteString(AlterSystem(output))
return b.String()
case StackGres, StackGresShort, SGPGConfig, YAML:
b.WriteString(SGConfigFile(output, fmt.Sprintf("%.f", pgVersion)))
return b.String()
case JSON:
b.WriteString(JSONFile(output))
return b.String()
default:
b.WriteString(ConfigFile(output))
return b.String()
}
}

func fillComment(qtd int, comment string) string {
var b bytes.Buffer

for i := 0; i < qtd; i++ {
b.WriteString(comment)
}

return b.String()
}
15 changes: 15 additions & 0 deletions pkg/format/json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package format

import (
"encoding/json"

"github.com/pgconfig/api/pkg/category"
)

// JSONFile generates a string with the JSON file contents of
// the tuning report in the Slice format
func JSONFile(report []category.SliceOutput) string {
b, _ := json.MarshalIndent(report, "", " ")

return string(b)
}

0 comments on commit ef8ec62

Please sign in to comment.