diff --git a/src/Makefile b/src/Makefile index a9309c5..66760da 100644 --- a/src/Makefile +++ b/src/Makefile @@ -6,7 +6,7 @@ tag = v0.0.51-alpha build_release_alpine: rm -rf build && mkdir -p $(build) CGO_ENABLED=1 GOOS=linux CC=musl-gcc \ - go build -ldflags "-X main.ginMode=release" -o $(build) + go build -ldflags "-X expenses/cmd.ginMode=release" -o $(build) cp -r ./assets $(build) cp ./config.yaml $(build) mkdir $(build)/data/ diff --git a/src/TODO.md b/src/TODO.md index ab0b177..a7d0eb7 100644 --- a/src/TODO.md +++ b/src/TODO.md @@ -10,7 +10,17 @@ used - [ ] Migrate every column named "ExpenseSomething" to "ExpSomething" - [ ] Make the models just return errors and not do any handling themselves - [ ] Reduce the size of the font file -- [ ] Add some migration tool +- [X] Add some migration tool - [ ] Ownership on the image for the expenses webapp dir need to be changed - [ ] The button for deleting share rows isn't working at all unlike the payments - [ ] Use shopspring/decimal for money handling +- [ ] Rename this file + +### Stack +- Go +- golang-migrate +- sqlc +- sqlite + +### Patterns +- Service Pattern diff --git a/src/cmd/cmd.go b/src/cmd/cmd.go new file mode 100644 index 0000000..abbf172 --- /dev/null +++ b/src/cmd/cmd.go @@ -0,0 +1,27 @@ +package cmd + +import ( + "os" + + "github.com/spf13/cobra" +) + +// rootCmd represents the base command when called without any subcommands +var rootCmd = &cobra.Command{ + Use: "expenses", + Short: "CLI for the expenses application", + Long: `This will help me keep track of my many expenses`, +} + +// Execute adds all child commands to the root command and sets flags appropriately. +// This is called by main.main(). It only needs to happen once to the rootCmd. +func Execute() { + err := rootCmd.Execute() + if err != nil { + os.Exit(1) + } +} + +func init() { + // rootCmd.PersistentFlags().BoolP("dbstore", "s", false, "Store data in database") +} diff --git a/src/cmd/migrations.go b/src/cmd/migrations.go new file mode 100644 index 0000000..be5cc40 --- /dev/null +++ b/src/cmd/migrations.go @@ -0,0 +1,44 @@ +package cmd + +import ( + "expenses/expenses" + "fmt" + "log" + "strconv" + + "github.com/spf13/cobra" +) + +func verifyArgs(cmd *cobra.Command, args []string) error { + if len(args) != 1 { + return fmt.Errorf("requires at least two arguments: [source file] and dest") + } + + return nil +} + +func migrate(cmd *cobra.Command, args []string) { + migID, err := strconv.ParseUint(args[0], 10, 0) + + if err != nil { + log.Fatalf("%s is an invalid migration ID", args[1]) + } + + err = expenses.Serv.MigGoto(uint(migID)) + if err != nil { + log.Fatalf("Failed to apply migration: %v", err) + } +} + +// shelf +var migCmd = &cobra.Command{ + Use: "migrate", + Short: "", + Long: ``, + Args: verifyArgs, + Run: migrate, +} + +func init() { + rootCmd.AddCommand(migCmd) +} diff --git a/src/cmd/server.go b/src/cmd/server.go new file mode 100644 index 0000000..ff6b19e --- /dev/null +++ b/src/cmd/server.go @@ -0,0 +1,87 @@ +package cmd + +import ( + "expenses/config" + "expenses/pages" + "github.com/spf13/cobra" + + "fmt" + "html/template" + "log" + "net/http" + fp "path/filepath" + "time" + + "github.com/gin-gonic/gin" +) + +// This can be set in the compilation command - in the Makefile +var ( + ginMode = "debug" + tmplFuncMap = template.FuncMap{ + "formatDate": func(ts int64) string { + return time.Unix(ts, 0).Format("02-Jan-2006") + }, + "formatPrice": func(v float64) string { + return fmt.Sprintf("%.2f", v) + }, + } +) + +func configGin(cfg *config.Configuration) *gin.Engine { + gin.SetMode(ginMode) + templates := template.Must( + template.New(""). + Funcs(tmplFuncMap). + ParseGlob(fp.Join(cfg.AssetsDir, "htmx/*.html")), + ) + + router := gin.Default() + router.SetHTMLTemplate(templates) + + router.StaticFS("/assets", http.Dir(cfg.AssetsDir)) + router.StaticFile("/favicon.ico", fp.Join(cfg.AssetsDir, "img/favicon.webp")) + + return router +} + +func setRoutes(router *gin.Engine) { + pages.RouteHome(router) + pages.RouteExpenses(router) + pages.RouteCategories(router) + pages.RouteStores(router) + pages.RouteTypes(router) + pages.RoutePayments(router) + pages.RouteOverview(router) + pages.RouteNotFound(router) + pages.RouteServerError(router) +} + +func startWebserver() { + cfg := config.GetInstance() + + router := configGin(cfg) + setRoutes(router) + + err := router.Run(":" + cfg.Port) + if err != nil { + log.Printf("Failed to launch application: \n %s\n", err) + } +} + +func server(cmd *cobra.Command, args []string) { + startWebserver() +} + +// shelf +var serverCmd = &cobra.Command{ + Use: "server", + Short: "", + Long: ``, + Args: nil, + Run: server, +} + +func init() { + rootCmd.AddCommand(serverCmd) +} diff --git a/src/expenses/app.go b/src/expenses/app.go index 405cf0b..a425ce5 100644 --- a/src/expenses/app.go +++ b/src/expenses/app.go @@ -32,8 +32,6 @@ func StartApp() error { Serv = NewExpenseService(db) - log.Println(cfg) - err = mod.RunMigrations(db) if err != nil { log.Fatalf("Failed to apply migrations: %v", err) diff --git a/src/expenses/migrations.go b/src/expenses/migrations.go new file mode 100644 index 0000000..fde5c74 --- /dev/null +++ b/src/expenses/migrations.go @@ -0,0 +1,9 @@ +package expenses + +import ( + mod "expenses/expenses/models" +) + +func (s *Service) MigGoto(id uint) error { + return mod.Goto(s.DB, id) +} diff --git a/src/expenses/models/migrations.go b/src/expenses/models/migrations.go index 5daa8f0..10c0d96 100644 --- a/src/expenses/models/migrations.go +++ b/src/expenses/models/migrations.go @@ -11,12 +11,31 @@ import ( _ "github.com/golang-migrate/migrate/v4/source/file" ) -func RunMigrations(db *sql.DB) error { +func prepareMigrator(db *sql.DB) (*mig.Migrate, error) { cfg := config.GetInstance() driver, err := sqlite3.WithInstance(db, &sqlite3.Config{}) - m, err := mig.NewWithDatabaseInstance(cfg.MigrationsPath, "sqlite3", driver) + + return m, err +} + +func Goto(db *sql.DB, id uint) error { + m, err := prepareMigrator(db) + if err != nil { + return err + } + + err = m.Force(int(id)) + if err != nil && err != mig.ErrNoChange { + return err + } + + return nil +} + +func RunMigrations(db *sql.DB) error { + m, err := prepareMigrator(db) if err != nil { return err } diff --git a/src/go.mod b/src/go.mod index 47e614d..278da83 100644 --- a/src/go.mod +++ b/src/go.mod @@ -6,6 +6,7 @@ require ( github.com/gin-gonic/gin v1.10.1 github.com/golang-migrate/migrate/v4 v4.18.3 github.com/mattn/go-sqlite3 v1.14.28 + github.com/spf13/cobra v1.9.1 github.com/stretchr/testify v1.9.0 gopkg.in/yaml.v2 v2.4.0 ) @@ -24,6 +25,7 @@ require ( github.com/goccy/go-json v0.10.2 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.2.7 // indirect github.com/leodido/go-urn v1.4.0 // indirect @@ -32,6 +34,7 @@ require ( github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.2.2 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/spf13/pflag v1.0.6 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.12 // indirect go.uber.org/atomic v1.7.0 // indirect diff --git a/src/go.sum b/src/go.sum index 89f3124..6f9cf66 100644 --- a/src/go.sum +++ b/src/go.sum @@ -6,6 +6,7 @@ github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/ github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -35,6 +36,8 @@ github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= @@ -43,6 +46,8 @@ github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZY github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-sqlite3 v1.14.28 h1:ThEiQrnbtumT+QMknw63Befp/ce/nUPgBPMlRFEum7A= @@ -56,6 +61,11 @@ github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6 github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo= +github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0= +github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= +github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= diff --git a/src/main.go b/src/main.go index 09c2ab1..26493f9 100644 --- a/src/main.go +++ b/src/main.go @@ -1,72 +1,15 @@ package main import ( - "expenses/config" + "expenses/cmd" "expenses/expenses" - "expenses/pages" - - "fmt" - "html/template" "log" - "net/http" - fp "path/filepath" - "time" - - "github.com/gin-gonic/gin" ) -// This can be set in the compilation command - in the Makefile -var ginMode = "debug" - -var tmplFuncMap = template.FuncMap{ - "formatDate": func(ts int64) string { - return time.Unix(ts, 0).Format("02-Jan-2006") - }, - "formatPrice": func(v float64) string { - return fmt.Sprintf("%.2f", v) - }, -} - -func configGin(cfg *config.Configuration) *gin.Engine { - gin.SetMode(ginMode) - templates := template.Must( - template.New(""). - Funcs(tmplFuncMap). - ParseGlob(fp.Join(cfg.AssetsDir, "htmx/*.html")), - ) - - router := gin.Default() - router.SetHTMLTemplate(templates) - - router.StaticFS("/assets", http.Dir(cfg.AssetsDir)) - router.StaticFile("/favicon.ico", fp.Join(cfg.AssetsDir, "img/favicon.webp")) - - return router -} - -func setRoutes(router *gin.Engine) { - pages.RouteHome(router) - pages.RouteExpenses(router) - pages.RouteCategories(router) - pages.RouteStores(router) - pages.RouteTypes(router) - pages.RoutePayments(router) - pages.RouteOverview(router) - pages.RouteNotFound(router) - pages.RouteServerError(router) -} - func main() { if err := expenses.StartApp(); err != nil { log.Fatal("failed to start app:", err.Error()) } - cfg := config.GetInstance() - router := configGin(cfg) - setRoutes(router) - - err := router.Run(":" + cfg.Port) - if err != nil { - log.Printf("Failed to launch application: \n %s\n", err) - } + cmd.Execute() }