dwtt/Command.py

95 lines
3.3 KiB
Python

from datetime import datetime, timedelta
import re
class Command:
def __init__(self, default_time, cmdline):
self.time = default_time
self.command = 'start'
self.argstr = ''
self.parseCommandLine(cmdline)
def __str__(self):
return "{'time' => '%s', 'command' => '%s', 'argstr' => '%s'}" % \
(self.time, self.command, self.argstr)
def parseCommandLine(self, cmdline):
COMMANDS = {
'out' : 1,
'report' : 1,
'status' : 1,
'fill' : 1,
'adjust' : 1,
'start' : 1
}
ALIASES = {
'rpt' : 'report',
'adj' : 'adjust',
'end' : 'out',
'st' : 'status',
'f' : 'fill'
}
parts = cmdline.split(None, 1)
if len(parts) > 1:
timespec = parts[0].strip()
if self.parseTimeSpec(timespec):
parts = parts[1].split(None, 1)
if len(parts) == 1:
command = parts[0].strip()
rest = ''
else:
command, rest = parts
if command in COMMANDS:
self.command = command
self.argstr = rest.strip()
else:
self.argstr = ' '.join([command, rest]).strip()
def parseTimeSpec(self, timespec):
the_time = self.time
matched = False
m = re.match('^(?:(\d{4})[-/])?(\d{1,2})[-/](\d{1,2}),(.+)$', timespec)
if m is not None:
# a date was given
if m.group(1) is not None:
the_time = the_time.replace(year = int(m.group(1)))
the_time = the_time.replace(month = int(m.group(2)),
day = int(m.group(3)))
timespec = m.group(4)
m = re.match('^(\d{1,2}):?(\d{2})?(am?|pm?)?$', timespec, re.I)
if m is not None:
# an absolute time was given
h = int(m.group(1))
mins = 0 if m.group(2) is None else int(m.group(2))
am_pm = '' if m.group(3) is None else m.group(3).lower()
if am_pm == '' and h < 7:
h += 12
elif len(am_pm) >= 1 and am_pm[0] == 'p' and h < 12:
h += 12
elif len(am_pm) >= 1 and am_pm[0] == 'a' and h == 12:
h = 0
the_time = the_time.replace(hour = h, minute = mins, second = 0)
matched = True
else:
m = re.match('^([-+])(\d+(?:\.\d+)?)([hms])?$', timespec, re.I)
if m is not None:
# a relative time was given
plus_minus = m.group(1)
hms = m.group(3)
count = int(m.group(2))
if hms == 'm':
seconds = count * 60
elif hms == 's':
seconds = count
else: # hours
seconds = count * 60 * 60
delta = timedelta(seconds = seconds)
if plus_minus == '-':
the_time -= delta
else:
the_time += delta
matched = True
if matched:
self.time = the_time
return matched