Skip to content

Commit

Permalink
cobra cli
Browse files Browse the repository at this point in the history
  • Loading branch information
4rkal committed Mar 14, 2024
1 parent 7f80506 commit 4e57750
Show file tree
Hide file tree
Showing 12 changed files with 347 additions and 105 deletions.
Empty file added LICENSE
Empty file.
10 changes: 1 addition & 9 deletions forms.go → cmd/forms.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package main
package cmd

import (
"errors"
Expand All @@ -9,14 +9,6 @@ import (
"github.com/charmbracelet/huh"
)

type Routine struct {
Reps int `json:"reps"`
Rest int `json:"rest"`
Increase int `json:"increase"`
}

var routine Routine

func form1(tmp string) (Routine, error) {
accessible, _ := strconv.ParseBool(os.Getenv("ACCESSIBLE"))
form := huh.NewForm(
Expand Down
122 changes: 122 additions & 0 deletions cmd/go-pushups.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package cmd

import (
"fmt"
"os"
"os/exec"

"github.com/charmbracelet/bubbles/progress"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/martinlindhe/notify"
)

const (
padding = 2
maxWidth = 80
)

type Routine struct {
Reps int `json:"reps"`
Rest int `json:"rest"`
Increase int `json:"increase"`
}

var routine Routine

var helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#626262")).Render

var amount_done int = 0

func do(reps, rest, increase int) int {
if increase != 0 {
reps += reps * increase / 100
}
amount_done += reps
return reps
}

func alert(reps int) {
message := fmt.Sprintf("Do %v pushups", reps)
notify.Alert("go-pushups", "Pushup time!", message, "assets/logo.png")
}

func run(should_save bool) error {
var tmp string
var confirmation bool
routine, err := form1(tmp)
if err != nil {
fmt.Println("oh oh")
os.Exit(1)
}

confirmation, err2 := form2()
if err2 != nil {
fmt.Println("oh oh")
os.Exit(1)
}
if routine.Reps <= 0 || routine.Rest <= 0 {
fmt.Println("Not positive input")
os.Exit(1)
}

if confirmation == true && should_save == true {
save(routine)
}

m := model{
progress: progress.New(progress.WithDefaultGradient()),
}

for round := 1; ; round++ {
if _, err := tea.NewProgram(m).Run(); err != nil {
fmt.Println("Oh no!", err)
os.Exit(1)
}
reps := do(routine.Reps, routine.Rest, routine.Increase)
fmt.Printf("Round %d: Do %d pushups\n", round, reps)
alert(reps)
quit, err := form3()
if err != nil {
fmt.Println("oh oh %s", err)
os.Exit(1)
}
if quit == false {
fmt.Printf("You did %v pushups\n", amount_done)
os.Exit(0)
}
}
}

func run2(routinee Routine) error {
clearScreen()
routine = routinee
m := model{
progress: progress.New(progress.WithDefaultGradient()),
}

for round := 1; ; round++ {
if _, err := tea.NewProgram(m).Run(); err != nil {
fmt.Println("Oh no!", err)
os.Exit(1)
}
reps := do(routine.Reps, routine.Rest, routine.Increase)
fmt.Printf("Round %d: Do %d pushups\n", round, reps)
alert(reps)
quit, err := form3()
if err != nil {
fmt.Println("oh oh %s", err)
os.Exit(1)
}
if quit == false {
fmt.Printf("You did %v pushups\n", amount_done)
os.Exit(0)
}
}
}

func clearScreen() {
cmd := exec.Command("clear")
cmd.Stdout = os.Stdout
cmd.Run()
}
47 changes: 47 additions & 0 deletions cmd/load.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
"fmt"
"os"

"github.com/spf13/cobra"
)

// loadCmd represents the load command
var loadCmd = &cobra.Command{
Use: "load",
Short: "Loads an existing routine",
Long: `Load an existing pushup routine.
Example usage:
go-pushups load glorious-mindworm`,
Args: cobra.RangeArgs(0, 1),
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
show_files()
} else {
routine, error := loadRoutine(args[0])
if error != nil {
fmt.Println(error)
os.Exit(1)
}
run2(routine)
}
},
}

func init() {
rootCmd.AddCommand(loadCmd)

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

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

// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// loadCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
72 changes: 67 additions & 5 deletions load.go → cmd/loadHelper.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package main
package cmd

import (
"encoding/json"
Expand Down Expand Up @@ -36,6 +36,28 @@ func (m model2) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case tea.KeyMsg:
if msg.String() == "ctrl+c" {
return m, tea.Quit
} else if msg.String() == "enter" {
// Get the selected item and check if successful
selectedItem := m.list.SelectedItem()

// Access the selected item data (assuming `item` struct)
selectedRoutine := selectedItem.(item)

// Load the routine details from the file based on the filename
routine, err := loadRoutine(selectedRoutine.title)
if err != nil {
fmt.Println("Error loading routine:", err)
return m, nil
}
run2(routine)

// Handle the loaded routine data (e.g., display details, start workout)
fmt.Printf("Selected routine: %s\n", selectedRoutine.title)
fmt.Printf("Amount: %d, Rest: %d seconds, Increase: %d%%\n", routine.Reps, routine.Rest, routine.Increase)

// You can implement further actions based on the routine here

return m, nil
}
case tea.WindowSizeMsg:
h, v := docStyle.GetFrameSize()
Expand Down Expand Up @@ -73,9 +95,16 @@ func load(rootDir string) (error, []string) {
}

func show_files() {
configDir, err := os.UserConfigDir()
if err != nil {
fmt.Printf("failed to get user config directory: %w", err)
}

appDir := "go-pushups"
appDirPath := filepath.Join(configDir, appDir)
var routine Routine
items := []list.Item{}
_, files := load(".")
_, files := load(appDirPath)
for i := range files {
jsonFile, err := os.Open(files[i])
if err != nil {
Expand All @@ -84,10 +113,10 @@ func show_files() {
}
byteValue, _ := ioutil.ReadAll(jsonFile)
json.Unmarshal(byteValue, &routine)
fmt.Println(files[i])
fmt.Println(routine)
// fmt.Println(files[i])
// fmt.Println(routine)
r := fmt.Sprintf("Amount: %d, Rest %d (sec), Increase %d %%", routine.Reps, routine.Rest, routine.Increase)
name := strings.TrimSuffix(files[i], ".json")
name := strings.TrimSuffix(strings.TrimPrefix(files[i], appDirPath+"/"), ".json")
newItem := item{title: name, desc: r}
items = append(items, newItem)
}
Expand All @@ -102,3 +131,36 @@ func show_files() {
os.Exit(1)
}
}

func loadRoutine(file string) (Routine, error) {
configDir, err := os.UserConfigDir()
if err != nil {
fmt.Printf("failed to get user config directory: %w", err)
}

appDir := "go-pushups"
var routine Routine

// Append .json extension to the file name
filePath := filepath.Join(configDir, appDir, file+".json")

// Open the JSON file
jsonFile, err := os.Open(filePath)
if err != nil {
return routine, fmt.Errorf("error opening file %s: %v", filePath, err)
}
defer jsonFile.Close()

// Read the file contents
byteValue, err := ioutil.ReadAll(jsonFile)
if err != nil {
return routine, fmt.Errorf("error reading file %s: %v", filePath, err)
}

// Unmarshal JSON into Routine struct
err = json.Unmarshal(byteValue, &routine)
if err != nil {
return routine, fmt.Errorf("error unmarshalling JSON from file %s: %v", filePath, err)
}
return routine, nil
}
2 changes: 1 addition & 1 deletion models.go → cmd/models.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package main
package cmd

import (
"fmt"
Expand Down
41 changes: 41 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
"os"

"github.com/spf13/cobra"
)

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "go-pushups",
Short: "Your cli pushup companion",
Long: `go-pushups is a simple command-line application designed to help you stay active by reminding you to do pushups at regular intervals, with a percentage increase over time.`,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}

// 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() {
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.

// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.go-pushups.yaml)")

// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
32 changes: 32 additions & 0 deletions cmd/run.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
"github.com/spf13/cobra"
)

// runCmd represents the run command
var runCmd = &cobra.Command{
Use: "run",
Short: "Runs go-pushups",
Long: `Runs go-pushups`,
Run: func(cmd *cobra.Command, args []string) {
run(true)
},
}

func init() {
rootCmd.AddCommand(runCmd)

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

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

// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// runCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
Loading

0 comments on commit 4e57750

Please sign in to comment.