Made some great progress

This commit is contained in:
2018-01-11 10:52:44 -06:00
parent 3d420d20ba
commit 655c052f38
6 changed files with 412 additions and 124 deletions

View File

@@ -2,11 +2,36 @@ package main
import (
"errors"
"fmt"
"strconv"
"time"
"git.bullercodeworks.com/brian/gime"
)
// filterTimerCollection takes a collection and a function that it runs every entry through
// If the function returns true for the entry, it adds it to a new collection to be returned
func filterTimerCollection(c *gime.TimeEntryCollection, fn func(t *gime.TimeEntry) bool) *gime.TimeEntryCollection {
ret := new(gime.TimeEntryCollection)
for i := 0; i < c.Length(); i++ {
if fn(c.Get(i)) {
ret.Push(c.Get(i))
}
}
return ret
}
func TimerCollectionToString(c *gime.TimeEntryCollection) string {
var ret string
for i := 0; i < c.Length(); i++ {
ret += TimerToString(c.Get(i))
if i < c.Length()-1 {
ret += "\n"
}
}
return ret
}
// TimerToString takes a TimeEntry and gives a nicely formatted string
func TimerToString(t *gime.TimeEntry) string {
var ret string
@@ -37,10 +62,62 @@ func TimerToString(t *gime.TimeEntry) string {
return ret
}
func InferTimerDetailString(t *gime.TimeEntry) string {
diffEnd := time.Now()
if !t.GetEnd().IsZero() {
diffEnd = t.GetEnd()
}
if int(diffEnd.Sub(t.GetStart())) >= (int(time.Hour) * diffEnd.Hour()) {
return TimerDetailToLongString(t)
}
return TimerDetailToString(t)
}
func TimerDetailToString(t *gime.TimeEntry) string {
ret := t.GetStart().Format("15:04")
if t.GetEnd().IsZero() {
ret += " (" + padLeft(sinceToString(t.GetStart()), len("00h 00m 00s")) + ") "
} else {
ret += " (" + padLeft(diffToString(t.GetStart(), t.GetEnd()), len("00h 00m 00s")) + ") "
}
if t.GetTags().Length() > 0 {
ret += " [ "
for j := 0; j < t.GetTags().Length(); j++ {
ret += t.GetTags().Get(j)
if j < t.GetTags().Length()-1 {
ret += ", "
}
}
ret += " ] "
}
return ret
}
// ...ToLongString includes year/month/day
func TimerDetailToLongString(t *gime.TimeEntry) string {
ret := t.GetStart().Format(time.Stamp)
if t.GetEnd().IsZero() {
ret += " (" + padLeft(sinceToString(t.GetStart()), len("0000y 00m 00d 00h 00m 00s")) + ") "
} else {
ret += " (" + padLeft(diffToString(t.GetStart(), t.GetEnd()), len("0000y 00m 00d 00h 00m 00s")) + ") "
}
if t.GetTags().Length() > 0 {
ret += " [ "
for j := 0; j < t.GetTags().Length(); j++ {
ret += t.GetTags().Get(j)
if j < t.GetTags().Length()-1 {
ret += ", "
}
}
ret += " ] "
}
return ret
}
// findTimerById takes a timer id and returns the TimeEntry and the type string
// of the entry corresponding to that id
// It searches TypeCurrent -> TypeRecent -> TypeArchive
func findTimerById(tmrId int) (*gime.TimeEntry, string, error) {
func findTimerById(tmrId int) (*gime.TimeEntry, int, error) {
// Find the timer for this tmrId
var prevNum, numLoaded int
for i := range gdb.AllTypes {
@@ -52,5 +129,123 @@ func findTimerById(tmrId int) (*gime.TimeEntry, string, error) {
}
prevNum = numLoaded
}
return nil, gime.TypeUnknown, errors.New("Unable to find timer with id: " + strconv.Itoa(tmrId))
return nil, gime.TypeAll, errors.New("Unable to find timer with id: " + strconv.Itoa(tmrId))
}
func parseFuzzyTime(t string) (time.Time, error) {
var ret time.Time
var err error
for i := range fuzzyFormats {
ret, err = time.Parse(fuzzyFormats[i], t)
if err == nil {
// Make sure it's in the local timezone
tz := time.Now().Format("Z07:00")
t = ret.Format("2006-01-02T15:04:05") + tz
if ret, err = time.Parse(time.RFC3339, t); err != nil {
return ret, err
}
// Check for zero on year/mo/day
if ret.Year() == 0 && ret.Month() == time.January && ret.Day() == 1 {
ret = ret.AddDate(time.Now().Year(), int(time.Now().Month())-1, time.Now().Day()-1)
}
return ret, nil
}
}
return time.Time{}, errors.New("Unable to parse time: " + t)
}
func sinceToString(tm time.Time) string {
return diffToString(tm, time.Now())
}
func diffToString(tm1, tm2 time.Time) string {
ret := ""
yr, mo, dy, hr, mn, sc := diff(tm1, tm2)
higher := false
if yr > 0 {
ret += fmt.Sprintf("%4dy ", yr)
higher = true
}
if mo > 0 || higher {
ret += fmt.Sprintf("%2dm ", mo)
higher = true
}
if dy > 0 || higher {
ret += fmt.Sprintf("%2dd ", dy)
higher = true
}
if hr > 0 || higher {
ret += fmt.Sprintf("%2dh ", hr)
higher = true
}
if mn > 0 || higher {
ret += fmt.Sprintf("%2dm ", mn)
higher = true
}
if sc > 0 || higher {
ret += fmt.Sprintf("%2ds", sc)
}
return ret
}
func padRight(st string, l int) string {
for len(st) < l {
st = st + " "
}
return st
}
func padLeft(st string, l int) string {
for len(st) < l {
st = " " + st
}
return st
}
func diff(a, b time.Time) (year, month, day, hour, min, sec int) {
if a.Location() != b.Location() {
b = b.In(a.Location())
}
if a.After(b) {
a, b = b, a
}
y1, M1, d1 := a.Date()
y2, M2, d2 := b.Date()
h1, m1, s1 := a.Clock()
h2, m2, s2 := b.Clock()
year = int(y2 - y1)
month = int(M2 - M1)
day = int(d2 - d1)
hour = int(h2 - h1)
min = int(m2 - m1)
sec = int(s2 - s1)
// Normalize negative values
if sec < 0 {
sec += 60
min--
}
if min < 0 {
min += 60
hour--
}
if hour < 0 {
hour += 24
day--
}
if day < 0 {
// days in month:
t := time.Date(y1, M1, 32, 0, 0, 0, 0, time.UTC)
day += 32 - t.Day()
month--
}
if month < 0 {
month += 12
year--
}
return
}

View File

@@ -3,7 +3,6 @@ package main
import (
"fmt"
"os"
"strconv"
"strings"
"time"
@@ -19,10 +18,13 @@ const (
)
var validOperations map[string][]string
var activeTimeEntries *gime.TimeEntryCollection
var opFuncs map[string]func([]string) int
var timeEntries *gime.TimeEntryCollection
var gdb *gime.GimeDB
var cfg *userConfig.Config
var fuzzyFormats []string
func main() {
var ret int
initialize()
@@ -36,30 +38,20 @@ func main() {
parms = append(parms, "status")
}
switch parms[0] {
case "config":
ret = cmdDoConfig(parms[1:])
case "delete", "remove":
ret = cmdDeleteTimer(parms[1:])
case "help":
ret = cmdPrintHelp()
case "status":
ret = cmdPrintStatus()
case "start":
ret = cmdStartTimer(parms[1:])
case "switch":
ret = cmdSwitchTimer(parms[1:])
case "end", "stop":
ret = cmdStopTimer(parms[1:])
case "list", "ls":
ret = cmdPrintList(parms[1:])
default:
if fn, ok := opFuncs[parms[0]]; ok {
ret = fn(parms[1:])
} else {
fmt.Println("Unknown command")
ret = 1
}
os.Exit(ret)
}
func cmdDoArchive(args []string) int {
fmt.Println("Not implemented yet.")
return 1
}
func cmdDoConfig(args []string) int {
if len(args) == 0 {
fmt.Println("Invalid configuration options passed")
@@ -103,12 +95,28 @@ func cmdDoConfig(args []string) int {
return 0
}
func cmdPrintHelp() int {
fmt.Println("gime - A simple timekeeping application\n")
fmt.Println("Usage: gime [@timerID] [operation] [tags...]")
for _, v := range validOperations {
for vi := range v {
fmt.Println(" ", v[vi])
func cmdPrintDetail(args []string) int {
fmt.Println("Not implemented yet.")
return 1
}
func cmdPrintHelp(args []string) int {
if len(args) == 0 {
fmt.Println("gime - A simple timekeeping application\n")
fmt.Println("Usage: gime [@timerID] [operation] [tags...]")
for _, v := range validOperations {
for vi := range v {
fmt.Println(" ", v[vi])
}
fmt.Println("")
}
} else {
switch args[0] {
case "formats":
fmt.Println("Supported date/time formats:")
for i := range fuzzyFormats {
fmt.Println(" ", fuzzyFormats[i])
}
}
fmt.Println("")
}
@@ -116,51 +124,48 @@ func cmdPrintHelp() int {
}
func loadActiveTimeEntries() {
activeTimeEntries = gdb.LoadTimeEntryCollection(gime.TypeCurrent)
timeEntries = gdb.LoadTimeEntryCollection(gime.TypeCurrent)
}
func loadActiveAndRecentTimeEntries() {
timeEntries = gdb.LoadTimeEntryCollection(gime.TypeNoArchive)
}
func cmdPrintList(args []string) int {
var err error
loadActiveTimeEntries()
// By default, list all entries for today
currTime := time.Now()
dur := currTime.Hour()*time.Hour + currTime.Minute()*time.Minute
if len(args) < 1 {
loadActiveAndRecentTimeEntries()
// By default, list all entries ending today or still running
filter := func(t *gime.TimeEntry) bool {
return t.EndsToday() || t.IsRunning()
}
fmt.Println(TimerCollectionToString(filterTimerCollection(timeEntries, filter)))
return 0
}
func cmdPrintStatus() int {
func cmdPrintStatus(args []string) int {
loadActiveTimeEntries()
curr := time.Now()
fmt.Println("Current Time:", curr.Format(time.Stamp))
if activeTimeEntries.Length() == 0 {
if timeEntries.Length() == 0 {
fmt.Println("No timer running")
} else {
fmt.Print("Active Timers (", activeTimeEntries.Length(), ")\n")
for i := 0; i < activeTimeEntries.Length(); i++ {
v := activeTimeEntries.Get(i)
if v.GetStart().Day() == curr.Day() {
fmt.Print(" @"+strconv.Itoa(i)+" ", v.GetStart().Format("15:04"), " ")
fmt.Print("Active Timers (", timeEntries.Length(), ")\n")
// Find the longest start time & longest duration
short := true
for i := 0; i < timeEntries.Length(); i++ {
v := timeEntries.Get(i)
if v.GetStart().Day() != curr.Day() {
short = false
break
}
}
for i := 0; i < timeEntries.Length(); i++ {
v := timeEntries.Get(i)
if short {
fmt.Printf(" @%d %s\n", i, TimerDetailToString(v))
} else {
fmt.Print(" @"+strconv.Itoa(i)+" ", v.GetStart().Format(time.Stamp), " ")
fmt.Printf(" @%d %s\n", i, TimerDetailToLongString(v))
}
since := time.Since(v.GetStart()).String()
since = strings.Split(since, ".")[0]
fmt.Print("(" + since + "s) ")
fmt.Print(v.GetTags().Length())
if v.GetTags().Length() > 0 {
fmt.Print(" [ ")
for j := 0; j < v.GetTags().Length(); j++ {
fmt.Print(v.GetTags().Get(j))
if j < v.GetTags().Length()-1 {
fmt.Print(", ")
}
}
fmt.Print(" ] ")
}
fmt.Println("")
}
}
return 0
@@ -169,6 +174,9 @@ func cmdPrintStatus() int {
func initialize() {
var err error
validOperations = make(map[string][]string)
opFuncs = make(map[string]func([]string) int)
opFuncs["config"] = cmdDoConfig
validOperations["config"] = []string{
"config [command] - Perform configuration",
" list - List current configuration",
@@ -178,18 +186,28 @@ func initialize() {
" dbname=[database filename]",
" dbarchname=[archive database filename]",
}
opFuncs["detail"] = cmdPrintDetail
validOperations["detail"] = []string{
"detail @id - Print details about a timer",
}
opFuncs["delete"] = cmdDeleteTimer
validOperations["delete"] = []string{
"delete @id - Delete a timer",
}
opFuncs["end"] = cmdStopTimer
validOperations["end"] = []string{
"end - The same as stop",
}
opFuncs["help"] = cmdPrintHelp
validOperations["help"] = []string{
"help - Print this",
}
opFuncs["list"] = cmdPrintList
validOperations["list"] = []string{
"list [duration] [+tags] - List time entries",
" valid values of [duration] include:",
@@ -199,28 +217,48 @@ func initialize() {
" year - List all entries for the current year",
" To list entries by tag, preceed the tags with a +",
}
opFuncs["ls"] = cmdPrintList
validOperations["ls"] = []string{
"ls [duration] [+tags] - The same as list",
}
opFuncs["remove"] = cmdDeleteTimer
validOperations["remove"] = []string{
"remove @id - See 'delete'",
}
opFuncs["status"] = cmdPrintStatus
validOperations["status"] = []string{
"status - Print the status of all active timers",
}
opFuncs["start"] = cmdStartTimer
validOperations["start"] = []string{
"start [time] [tags ...] - Start a timer with the given tags (space separated)",
" If the first sub-argument given looks like a time,",
" the timer will be started then (past or future).",
" If a timer is already running it'll be stopped",
}
opFuncs["stop"] = cmdStopTimer
validOperations["stop"] = []string{
"stop [time] - Stops the current timer",
" If the first sub-argument given looks like a time,",
" the timer will be stopped then (past or future).",
}
opFuncs["switch"] = cmdSwitchTimer
validOperations["switch"] = []string{
"switch [tags ...] - Stop all currently running timers and start a new",
" one with the given tags",
}
opFuncs["archive"] = cmdDoArchive
validOperations["archive"] = []string{
"archive - Archive all entries older than the archive date",
}
// Load the Config
cfg, err = userConfig.NewConfig(AppName)
if err != nil {
@@ -244,6 +282,21 @@ func initialize() {
fmt.Println("Error loading the database")
os.Exit(1)
}
fuzzyFormats = []string{
"15:04", // Kitchen, 24hr
time.Kitchen,
time.RFC3339,
"2006-01-02T15:04:05", // RFC3339 without timezone
"2006-01-02T15:04", // RFC3339 without seconds or timezone
time.Stamp,
"02 Jan 06 15:04:05", // RFC822 with second
time.RFC822,
"01/02/2006 15:04", // U.S. Format
"01/02/2006 15:04:05", // U.S. Format with seconds
"01/02/06 15:04", // U.S. Format, short year
"01/02/06 15:04:05", // U.S. Format, short year, with seconds
}
}
func matchParameter(in string) string {

View File

@@ -13,11 +13,11 @@ import (
func cmdSwitchTimer(args []string) int {
loadActiveTimeEntries()
tm := time.Now()
if activeTimeEntries.Length() > 0 {
if timeEntries.Length() > 0 {
fmt.Println("Stopped Timers:")
}
for i := 0; i < activeTimeEntries.Length(); i++ {
tmr := activeTimeEntries.Get(i)
for i := 0; i < timeEntries.Length(); i++ {
tmr := timeEntries.Get(i)
tmr.SetEnd(tm)
if err := gdb.UpdateTimeEntry(tmr); err != nil {
fmt.Println(err.Error())
@@ -33,16 +33,14 @@ func cmdSwitchTimer(args []string) int {
// to be passed along to os.Exit
func cmdStartTimer(args []string) int {
var err error
tm := time.Now()
var tm time.Time
tagStart := 0
if len(args) > 0 {
// Check if the first argument looks like a date/time
tm, err = time.Parse("15:04", args[0])
if err != nil {
tm, err = time.Parse(time.Kitchen, args[0])
}
tm, err = parseFuzzyTime(args[0])
}
if err != nil {
if len(args) == 0 || err != nil {
// Just start it now
tm = time.Now()
} else {
@@ -72,46 +70,65 @@ func cmdStartTimer(args []string) int {
// cmdStopTimer takes parameters that describe which times to stop
func cmdStopTimer(args []string) int {
// args[0] should either be a timer id (starting with '@') or 'all'
var err error
tm := time.Now()
actTimers := gdb.LoadTimeEntryCollection(gime.TypeCurrent)
if actTimers.Length() != 1 && (len(args) < 1 || args[0][0] != '@') {
fmt.Println("Couldn't determine which timer(s) to stop")
return 1
}
var tmr *gime.TimeEntry
if actTimers.Length() == 1 {
// only one timer running
tmr = actTimers.Get(0)
} else {
// We've got a timer id to delete
timerId, err := strconv.Atoi(args[0][1:])
if err != nil {
fmt.Println("Error parsing timer id: " + err.Error())
stopAll := len(args) > 0 && args[0] == "all"
if !stopAll {
if actTimers.Length() != 1 && (len(args) < 1 || args[0][0] != '@') {
fmt.Println("Couldn't determine which timer(s) to stop")
return 1
}
tmr, _, err = findTimerById(timerId)
if actTimers.Length() == 1 {
// only one timer running
tmr = actTimers.Get(0)
} else {
// We've got a timer id to delete
timerId, err := strconv.Atoi(args[0][1:])
if err != nil {
fmt.Println("Error parsing timer id: " + err.Error())
return 1
}
tmr, _, err = findTimerById(timerId)
if err != nil {
fmt.Println(err.Error())
return 1
}
}
}
if len(args) > 1 {
// Check if the next argument looks like a date/time
tm, err = parseFuzzyTime(args[1])
if err != nil {
fmt.Println(err.Error())
return 1
}
}
if len(args) > 0 {
// Check if the first argument looks like a date/time
tm, err = time.Parse("15:04", args[0])
if err != nil {
tm, err = time.Parse(time.Kitchen, args[0])
stopTimer := func(tmr *gime.TimeEntry, at time.Time) int {
tmr.SetEnd(at)
if err = gdb.UpdateTimeEntry(tmr); err != nil {
fmt.Println(err.Error())
return 1
}
fmt.Println("Stopped:", InferTimerDetailString(tmr))
return 0
}
tmr.SetEnd(tm)
if err = gdb.UpdateTimeEntry(tmr); err != nil {
fmt.Println(err.Error())
return 1
if stopAll {
var ret int
for i := 0; i < actTimers.Length(); i++ {
ret += stopTimer(actTimers.Get(i), tm)
}
if ret > 0 {
return 1 // One or more stop operations failed
}
return 0
}
fmt.Println(TimerToString(tmr))
return 0
return stopTimer(tmr, tm)
}
// cmdDeleteTimer takes parameters that describe the timers to be deleted.
@@ -134,7 +151,7 @@ func cmdDeleteTimer(args []string) int {
return 1
}
if gdb.RemoveTimeEntry(tmr.GetUUID()) != nil {
fmt.Println("Error removing entry " + tp + "." + tmr.GetUUID())
fmt.Println("Error removing entry " + gime.TypeToString(tp) + "." + tmr.GetUUID())
return 1
}
fmt.Println("Deleted Time Entry: " + TimerToString(tmr))