Skip to content

Commit

Permalink
feat(cli): add timetable sub-command, add error messages to GetTimetable
Browse files Browse the repository at this point in the history
  • Loading branch information
VaiTon committed Nov 7, 2024
1 parent 9da30ac commit f760641
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 5 deletions.
70 changes: 70 additions & 0 deletions cmd/unibo/timetable.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package main

import (
"fmt"
"strconv"
"time"

"github.com/cartabinaria/unibo-go/timetable"
"github.com/fatih/color"
"github.com/spf13/cobra"
)

var cmdTimetable = &cobra.Command{
Use: "timetable",
Short: "fetches the timetable of a degree course",
Args: cobra.RangeArgs(3, 4),
Aliases: []string{"t"},
Run: runTimetable,
}

func init() {
rootCmd.AddCommand(cmdTimetable)
}

var (
yellowFmt = color.New(color.FgYellow).SprintFunc()
greenFmt = color.New(color.FgGreen).SprintFunc()
redFmt = color.New(color.FgRed).SprintFunc()
grayFmt = color.New(color.Faint).SprintFunc()
)

func runTimetable(cmd *cobra.Command, args []string) {

courseType := args[0]
courseId := args[1]
yearStr := args[2]

year64, err := strconv.ParseInt(yearStr, 10, 32)
if err != nil {
cmd.PrintErrln(fmt.Errorf("year must be a number"))
return
}

year := int(year64)

var curriculum string
if len(args) == 4 {
curriculum = args[3]
}

today := time.Now().Truncate(24 * time.Hour)

interval := &timetable.Interval{Start: today, End: today}
tt, err := timetable.FetchTimetable(courseType, courseId, curriculum, year, interval)
if err != nil {
cmd.PrintErrln(fmt.Errorf("error fetching timetable: %v", err))
return
}

if len(tt) == 0 {
cmd.Println(yellowFmt("No lessons found"))
return
}

for _, e := range tt {
cmd.Printf("- %s -> %s: %-50s %-30s (%s)\n",
greenFmt(e.Start.Format("15:04")), redFmt(e.End.Format("15:04")),
e.Title, yellowFmt(e.Teacher), grayFmt(e.CodModulo))
}
}
11 changes: 6 additions & 5 deletions timetable/timetable.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,25 +137,26 @@ func FetchTimetable(
courseType, courseId, curriculum string,
year int,
interval *Interval,
) (timetable Timetable, err error) {
) (Timetable, error) {
url := GetTimetableUrl(courseType, courseId, curriculum, year, interval)

res, err := http.Get(url)
if err != nil {
return
return nil, fmt.Errorf("failed to fetch timetable: %w", err)
}

var timetable Timetable
err = json.NewDecoder(res.Body).Decode(&timetable)
if err != nil {
return
return nil, fmt.Errorf("failed to decode timetable: %w", err)
}

err = res.Body.Close()
if err != nil {
return
return nil, fmt.Errorf("failed to close response body: %w", err)
}

return
return timetable, nil
}

type SimpleSubject struct {
Expand Down

0 comments on commit f760641

Please sign in to comment.