Skip to content

Commit

Permalink
refacto: big refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
alexisvisco committed May 17, 2024
1 parent 5ba6bf8 commit 566f159
Show file tree
Hide file tree
Showing 72 changed files with 1,533 additions and 896 deletions.
42 changes: 42 additions & 0 deletions .github/workflow.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: Go Test

on: [push, pull_request]

jobs:
test:
runs-on: ubuntu-latest

services:
postgres:
image: postgres:16-alpine
env:
POSTGRES_DB: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_USER: postgres
ports:
- 6666:5432
options: >-
--health-cmd="pg_isready -U postgres"
--health-interval=10s
--health-timeout=5s
--health-retries=5
steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: '1.20'

- name: Wait for PostgreSQL to be ready
run: |
while ! pg_isready -h 127.0.0.1 -p 5432 -U postgres; do
echo "Waiting for PostgreSQL..."
sleep 1
done
- name: Run tests
run: |
go test -v ./...
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
*.iml
.idea
migrations
.mig
.amigo
23 changes: 0 additions & 23 deletions .mig/main.go

This file was deleted.

20 changes: 5 additions & 15 deletions cmd/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,34 +11,24 @@ const contextFileName = "config.yml"
var contextCmd = &cobra.Command{
Use: "context",
Short: "save flags into a context",
Long: `A context is a file inside the .mig folder that contains the flags that you use in the command line.
Long: `A context is a file inside the .amigo folder that contains the flags that you use in the command line.
Example:
mig context --dsn "postgres://user:password@host:port/dbname?sslmode=disable"
amigo context --dsn "postgres://user:password@host:port/dbname?sslmode=disable"
This command will create a file .mig/context.yaml with the content:
This command will create a file .amigo/context.yaml with the content:
dsn: "postgres://user:password@host:port/dbname?sslmode=disable"
`,
RunE: func(cmd *cobra.Command, args []string) error {
Run: wrapCobraFunc(func(cmd *cobra.Command, args []string) error {
err := viper.WriteConfig()
if err != nil {
return err
}

return nil
},
}),
}

func init() {
rootCmd.AddCommand(contextCmd)

// Here you will define your flags and configuration settings.

// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// contextCmd.PersistentFlags().String("foo", "", "A help for foo")

// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// contextCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
82 changes: 32 additions & 50 deletions cmd/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,53 +2,44 @@ package cmd

import (
"fmt"
"github.com/alexisvisco/mig/pkg/mig"
"github.com/alexisvisco/mig/pkg/types"
"github.com/alexisvisco/mig/pkg/utils"
"github.com/alexisvisco/mig/pkg/utils/tracker"
"github.com/alexisvisco/amigo/pkg/amigo"
"github.com/alexisvisco/amigo/pkg/types"
"github.com/alexisvisco/amigo/pkg/utils/events"
"github.com/alexisvisco/amigo/pkg/utils/logger"
"github.com/spf13/cobra"
"path/filepath"
)

var (
createMigrationTypeFlag string
createDumpFlag bool
createDumpSchema string
createSkipDump bool
)

// createCmd represents the create command
var createCmd = &cobra.Command{
Use: "create <name>",
Short: "Create a new migration in the migration folder",
RunE: func(cmd *cobra.Command, args []string) error {
Run: wrapCobraFunc(func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return fmt.Errorf("name is required: mig create <name>")
return fmt.Errorf("name is required: amigo create <name>")
}

if err := validateDSN(); err != nil {
if err := cmdCtx.ValidateDSN(); err != nil {
return err
}

migFileType := types.MigrationFileType(createMigrationTypeFlag)

if !migFileType.IsValid() {
return fmt.Errorf("invalid migration file type: %s, can be: %s", createMigrationTypeFlag,
utils.StringJoin(types.MigrationFileTypeValues, ", "))
if err := cmdCtx.Create.ValidateType(); err != nil {
return err
}

printer := tracker.NewLogger(jsonFlag, cmd.OutOrStdout())
migFileType := types.MigrationFileType(cmdCtx.Create.Type)

inUp := ""

if createDumpFlag {
if cmdCtx.Create.Dump {
migFileType = types.MigrationFileTypeClassic
dump, err := mig.DumpSchema(&mig.DumpSchemaOptions{
DSN: dsnFlag,
MigrationTableName: schemaVersionTableFlag,
PGDumpPath: pgDumpPathFlag,
Schema: createDumpSchema,
Shell: shellPathFlag,

dump, err := amigo.DumpSchema(&amigo.DumpSchemaOptions{
DSN: cmdCtx.DSN,
MigrationTableName: cmdCtx.SchemaVersionTable,
PGDumpPath: cmdCtx.PGDumpPath,
Schema: cmdCtx.Create.Schema,
Shell: cmdCtx.ShellPath,
})
if err != nil {
return err
Expand All @@ -57,56 +48,47 @@ var createCmd = &cobra.Command{
inUp += fmt.Sprintf("s.Exec(`%s`)\n", dump)
}

filePath, version, err := mig.GenerateMigrationFile(mig.GenerateMigrationFileOptions{
filePath, version, err := amigo.GenerateMigrationFile(amigo.GenerateMigrationFileOptions{
Name: args[0],
Folder: migrationFolderFlag,
Driver: getDriver(),
Package: packageFlag,
Folder: cmdCtx.MigrationFolder,
Driver: getDriver(cmdCtx.DSN),
Package: cmdCtx.PackagePath,
MigType: migFileType,
InUp: inUp,
})
if err != nil {
return err
}

printer.AddEvent(tracker.FileAddedEvent{FileName: filePath})
logger.Info(events.FileAddedEvent{FileName: filePath})

if createSkipDump {
connection, err := mig.GetConnection(dsnFlag, verboseFlag)
if cmdCtx.Create.Skip {
connection, _, err := amigo.GetConnection(cmdCtx.DSN)
if err != nil {
return err
}

_, err = connection.Exec("INSERT INTO "+schemaVersionTableFlag+" (version) VALUES ($1)", version)
_, err = connection.Exec("INSERT INTO "+cmdCtx.SchemaVersionTable+" (version) VALUES ($1)", version)
if err != nil {
return fmt.Errorf("unable to set migration as applied: %w", err)
}

printer.AddEvent(tracker.SkipMigrationEvent{MigrationVersion: version})
logger.Info(events.SkipMigrationEvent{MigrationVersion: version})
}

err = mig.GenerateMigrationsFile(migrationFolderFlag, packageFlag,
filepath.Join(migrationFolderFlag, migrationsFile))
err = amigo.GenerateMigrationsFile(cmdCtx.MigrationFolder, cmdCtx.PackagePath,
filepath.Join(cmdCtx.MigrationFolder, migrationsFile))
if err != nil {
return err
}

printer.AddEvent(tracker.FileModifiedEvent{FileName: filepath.Join(migrationFolderFlag, migrationsFile)})
logger.Info(events.FileModifiedEvent{FileName: filepath.Join(cmdCtx.MigrationFolder, migrationsFile)})

return nil
},
}),
}

func init() {
rootCmd.AddCommand(createCmd)
createCmd.Flags().StringVar(&createMigrationTypeFlag, "type", "change",
"The type of migration to create, possible values are [classic, change]")

createCmd.Flags().BoolVarP(&createDumpFlag, "dump", "d", false,
"dump with pg_dump the current schema and add it to the current migration")

createCmd.Flags().StringVarP(&createDumpSchema, "dump-schema", "s", "public", "the schema to dump if --dump is set")

createCmd.Flags().BoolVar(&createSkipDump, "skip", false,
"skip will set the migration as applied without executing it")
cmdCtx.Create.Register(createCmd)
}
46 changes: 23 additions & 23 deletions cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package cmd

import (
"fmt"
"github.com/alexisvisco/mig/pkg/mig"
"github.com/alexisvisco/mig/pkg/templates"
"github.com/alexisvisco/mig/pkg/utils/tracker"
"github.com/alexisvisco/amigo/pkg/amigo"
"github.com/alexisvisco/amigo/pkg/templates"
"github.com/alexisvisco/amigo/pkg/utils/events"
"github.com/alexisvisco/amigo/pkg/utils/logger"
"github.com/spf13/cobra"
"os"
"path"
Expand All @@ -14,37 +15,38 @@ import (
var initCmd = &cobra.Command{
Use: "init",
Short: "Initialize migrations folder and add the first migration file",
RunE: func(cmd *cobra.Command, args []string) error {
fmt.Println("DSN", dsnFlag)
t := tracker.NewLogger(jsonFlag, cmd.OutOrStdout())
Run: wrapCobraFunc(func(cmd *cobra.Command, args []string) error {
if err := cmdCtx.ValidateDSN(); err != nil {
return err
}

err := os.MkdirAll(migrationFolderFlag, 0755)
err := os.MkdirAll(cmdCtx.MigrationFolder, 0755)
if err != nil {
return fmt.Errorf("unable to create migration folder: %w", err)
}

t.AddEvent(tracker.FolderAddedEvent{FolderName: migrationFolderFlag})
logger.Info(events.FolderAddedEvent{FolderName: cmdCtx.MigrationFolder})

err = os.MkdirAll(migFolderPathFlag, 0755)
err = os.MkdirAll(cmdCtx.AmigoFolderPath, 0755)
if err != nil {
return fmt.Errorf("unable to create main folder: %w", err)
}

err = mig.GenerateMainFile(migFolderPathFlag, migrationFolderFlag)
err = amigo.GenerateMainFile(cmdCtx.AmigoFolderPath, cmdCtx.MigrationFolder)
if err != nil {
return err
}

template, err := templates.GetInitCreateTableTemplate(templates.CreateTableData{Name: schemaVersionTableFlag})
template, err := templates.GetInitCreateTableTemplate(templates.CreateTableData{Name: cmdCtx.SchemaVersionTable})
if err != nil {
return err
}

file, _, err := mig.GenerateMigrationFile(mig.GenerateMigrationFileOptions{
file, _, err := amigo.GenerateMigrationFile(amigo.GenerateMigrationFileOptions{
Name: "schema_version",
Folder: migrationFolderFlag,
Driver: getDriver(),
Package: packageFlag,
Folder: cmdCtx.MigrationFolder,
Driver: getDriver(cmdCtx.DSN),
Package: cmdCtx.PackagePath,
MigType: "change",
InUp: template,
InDown: "",
Expand All @@ -53,21 +55,19 @@ var initCmd = &cobra.Command{
return err
}

t.AddEvent(tracker.FileAddedEvent{FileName: file})
logger.Info(events.FileAddedEvent{FileName: file})

err = mig.GenerateMigrationsFile(migrationFolderFlag, packageFlag,
path.Join(migrationFolderFlag, migrationsFile))
err = amigo.GenerateMigrationsFile(cmdCtx.MigrationFolder, cmdCtx.PackagePath,
path.Join(cmdCtx.MigrationFolder, migrationsFile))
if err != nil {
return err
}

t.
AddEvent(tracker.FileAddedEvent{FileName: path.Join(migFolderPathFlag, "main.go")}).
AddEvent(tracker.FileAddedEvent{FileName: path.Join(migrationFolderFlag, migrationsFile)}).
Measure()
logger.Info(events.FileAddedEvent{FileName: path.Join(cmdCtx.AmigoFolderPath, "main.go")})
logger.Info(events.FileAddedEvent{FileName: path.Join(cmdCtx.MigrationFolder, migrationsFile)})

return nil
},
}),
}

func init() {
Expand Down
Loading

0 comments on commit 566f159

Please sign in to comment.