gime-lib/cmd/gime/main.go
2017-08-02 14:14:53 -05:00

274 lines
7.2 KiB
Go

package main
import (
"fmt"
"os"
"strconv"
"strings"
"time"
"git.bullercodeworks.com/brian/gime"
userConfig "github.com/br0xen/user-config"
)
const (
AppName = "gime"
AppVersion = 1
DefDBName = "gime.db"
DefArchDBName = "gimearch.db"
)
var validOperations map[string][]string
var activeTimeEntries *gime.TimeEntryCollection
var gdb *gime.GimeDB
var cfg *userConfig.Config
func main() {
var ret int
initialize()
var parms []string
if len(os.Args) > 1 {
parms = os.Args[1:]
parms[0] = matchParameter(parms[0])
} else {
// If no parameters were passed, just print the status
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:
fmt.Println("Unknown command")
ret = 1
}
os.Exit(ret)
}
func cmdDoConfig(args []string) int {
if len(args) == 0 {
fmt.Println("Invalid configuration options passed")
return 1
}
for _, opt := range args {
if strings.Index(opt, "=") == -1 {
// Single word triggers
switch opt {
case "reset":
fmt.Println("Resetting Configuration...")
cfg.Set("dbdir", cfg.GetConfigPath()+"/")
cfg.Set("dbname", DefDBName)
cfg.Set("dbarchname", DefArchDBName)
case "list":
fmt.Println("Current " + AppName + " config")
for _, v := range cfg.GetKeyList() {
fmt.Println(" " + v + ": " + cfg.Get(v))
}
}
} else {
// Key=Value options
pts := strings.Split(opt, "=")
if len(pts) == 2 {
switch pts[0] {
case "dbdir":
val := pts[1]
if val[len(val)-1] != '/' {
val = val + "/"
}
cfg.Set("dbdir", val)
case "dbname":
cfg.Set("dbname", pts[1])
case "dbarchname":
cfg.Set("dbarchname", pts[1])
}
}
}
}
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])
}
fmt.Println("")
}
return 0
}
func loadActiveTimeEntries() {
activeTimeEntries = gdb.LoadTimeEntryCollection(gime.TypeCurrent)
}
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 {
}
return 0
}
func cmdPrintStatus() int {
loadActiveTimeEntries()
curr := time.Now()
fmt.Println("Current Time:", curr.Format(time.Stamp))
if activeTimeEntries.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"), " ")
} else {
fmt.Print(" @"+strconv.Itoa(i)+" ", v.GetStart().Format(time.Stamp), " ")
}
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
}
func initialize() {
var err error
validOperations = make(map[string][]string)
validOperations["config"] = []string{
"config [command] - Perform configuration",
" list - List current configuration",
" reset - Reset current configuration",
" Configuration Options:",
" dbdir=[database directory]",
" dbname=[database filename]",
" dbarchname=[archive database filename]",
}
validOperations["detail"] = []string{
"detail @id - Print details about a timer",
}
validOperations["delete"] = []string{
"delete @id - Delete a timer",
}
validOperations["end"] = []string{
"end - The same as stop",
}
validOperations["help"] = []string{
"help - Print this",
}
validOperations["list"] = []string{
"list [duration] [+tags] - List time entries",
" valid values of [duration] include:",
" day - List all entries for the current day",
" week - List all entries for the current week",
" month - List all entries for the current month",
" year - List all entries for the current year",
" To list entries by tag, preceed the tags with a +",
}
validOperations["ls"] = []string{
"ls [duration] [+tags] - The same as list",
}
validOperations["status"] = []string{
"status - Print the status of all active timers",
}
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",
}
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).",
}
validOperations["switch"] = []string{
"switch [tags ...] - Stop all currently running timers and start a new",
" one with the given tags",
}
// Load the Config
cfg, err = userConfig.NewConfig(AppName)
if err != nil {
fmt.Println(err.Error())
fmt.Println("Creating new config")
cfg.Save()
}
// If dbdir isn't set, set it to the config directory
if cfg.Get("dbdir") == "" {
cfg.Set("dbdir", cfg.GetConfigPath()+"/")
}
// If dbname isn't set, set it to the default database filename
if cfg.Get("dbname") == "" {
cfg.Set("dbname", DefDBName)
}
// If dbarchivename isn't set, set it to the default archive database filename
if cfg.Get("dbarchname") == "" {
cfg.Set("dbarchname", DefArchDBName)
}
if gdb, err = gime.LoadDatabase(cfg.Get("dbdir"), cfg.Get("dbname"), cfg.Get("dbarchname")); err != nil {
fmt.Println("Error loading the database")
os.Exit(1)
}
}
func matchParameter(in string) string {
var chkParms []string
for k := range validOperations {
chkParms = append(chkParms, k)
}
var nextParms []string
for i := range in {
for _, p := range chkParms {
if p[i] == in[i] {
nextParms = append(nextParms, p)
}
}
// If we get here and there is only one parameter left, return it
chkParms = nextParms
if len(nextParms) == 1 {
break
}
// Otherwise, loop
nextParms = []string{}
}
if len(chkParms) == 0 {
return ""
}
return chkParms[0]
}