finish reporting

Signed-off-by: Nico Schottelius <nico@brief.schottelius.org>
This commit is contained in:
Nico Schottelius 2012-08-27 16:58:18 +02:00
parent 69bbdf80bd
commit cd733c73a8
4 changed files with 106 additions and 53 deletions

74
bin/ctt
View file

@ -21,16 +21,7 @@
#
import argparse
import calendar
import datetime
#import signal
import locale
import logging
import time
import os
import os.path
import sys
@ -42,30 +33,29 @@ log = logging.getLogger(__name__)
# Record tags
def cmd_track(args):
"""Command line handler for time tracking"""
tracker = Tracker(args.project[0])
tracker.track_time()
tracker.write_time()
print(tracker.delta())
def cmd_report(args):
"""Command line handler for time reporting"""
print(args)
report = Report(args.project[0], args.start, args.end)
print(Report.default_dates())
def parse_argv(argv):
def parse_argv(argv, version):
parser = {}
parser['main'] = argparse.ArgumentParser(description='ctt ' + VERSION)
parser['loglevel'] = argparse.ArgumentParser(add_help=False)
parser['loglevel'].add_argument('-d', '--debug',
help='Set log level to debug', action='store_true',
default=False)
parser['loglevel'].add_argument('-v', '--verbose',
help='Set log level to info, be more verbose',
action='store_true', default=False)
parser['main'] = argparse.ArgumentParser(description='ctt ' + version,
parents=[parser['loglevel']])
parser['sub'] = parser['main'].add_subparsers(title="Commands")
parser['track'] = parser['sub'].add_parser('track')
parser['track'].set_defaults(func=cmd_track)
parser['track'] = parser['sub'].add_parser('track',
parents=[parser['loglevel']])
parser['track'].set_defaults(func=Tracker.commandline)
parser['track'].add_argument("project", help="Project to track time for", nargs=1)
parser['report'] = parser['sub'].add_parser('report')
parser['report'].set_defaults(func=cmd_report)
parser['report'] = parser['sub'].add_parser('report',
parents=[parser['loglevel']])
parser['report'].set_defaults(func=Report.commandline)
parser['report'].add_argument("project", help="Project to report time for", nargs=1)
parser['report'].add_argument("-s", "--start", help="Start datetime (first of last month)",
nargs=1)
@ -76,24 +66,40 @@ def parse_argv(argv):
# action="store_true")
args = parser['main'].parse_args()
print(args)
args.func(args)
if args.verbose:
logging.root.setLevel(logging.INFO)
if args.debug:
logging.root.setLevel(logging.DEBUG)
log.debug(args)
try:
args.func(args)
except ctt.Error as e:
log.error(e)
sys.exit(1)
# Setup signal handler
# Start tracking
# Save stuff to our home directory
if __name__ == "__main__":
# Ensure our /lib/ is included into PYTHON_PATH
sys.path.insert(0, os.path.abspath(
os.path.join(os.path.dirname(os.path.realpath(__file__)), '../lib')))
#logging.basicConfig(format='%(levelname)s: %(message)s')
logging.basicConfig(format='%(message)s')
import ctt
from ctt.tracker import Tracker
from ctt.report import Report
parse_argv(sys.argv[1:])
parse_argv(sys.argv[1:], ctt.VERSION)
sys.exit(0)
# Setup signal handler
# Start tracking
# Save stuff to our home directory
# Create datetime from userinput
# Wed Aug 1 23:35:53 2012

View file

@ -18,11 +18,17 @@
# You should have received a copy of the GNU General Public License
# along with ctt. If not, see <http://www.gnu.org/licenses/>.
#
#
#
import os
import os.path
VERSION = "0.1"
FILE_DELTA = "delta"
DATEFORMAT = "%Y-%m-%d"
class Error(Exception):
pass
# Our output format
def user_datetime(when):

View file

@ -30,6 +30,8 @@ import os
import os.path
import sys
import ctt
log = logging.getLogger(__name__)
class Report(object):
@ -38,33 +40,69 @@ class Report(object):
def __init__(self, project, start_date, end_date):
# Setup default values
if not start_date and not end_date:
start_date, end_date = self.default_dates()
try:
if start_date:
start_date = datetime.datetime.strptime(start_date[0], ctt.DATEFORMAT)
else:
start_date = self.default_dates()[0]
self.start_seconds = start_date.strftime("%s")
self.end_seconds = end_date.strftime("%s")
if end_date:
end_date = datetime.datetime.strptime(end_date[0], ctt.DATEFORMAT)
else:
end_date = self.default_dates()[1]
except ValueError as e:
raise ctt.Error(e)
self.start_seconds = start_date.strftime("%s")
self.end_seconds = end_date.strftime("%s")
self.project = project
self.project_dir = project_dir(self.project)
self.project_dir = ctt.project_dir(self.project)
self._init_report_db()
@classmethod
def commandline(cls, args):
report = cls(args.project[0], args.start, args.end)
print("Total time in seconds: %s" % report.total_time())
def _init_report_db(self):
"""Read all contents from db"""
if not os.path.isdir(self.project_dir):
raise ctt.Error("Project does not exist: %s" % (self.project))
self._report_db = {}
for dirname in os.listdir(self.project_dir):
print("%s:%s:%s" % (self.start_seconds, dirname, self.end_seconds))
if dirname >= self.start_seconds and dirname <= self.end_seconds:
filename = os.path.join(self.project_dir, dirname, FILE_DELTA)
filename = os.path.join(self.project_dir, dirname, ctt.FILE_DELTA)
with open(filename, "r") as fd:
self._report_db[dirname] = fd.read().rstrip('\n')
print("%s: %s" % (dirname, self._report_db[dirname]))
log.debug("%s: %s" % (dirname, self._report_db[dirname]))
else:
log.debug("%s/%s" % (float(dirname) - float(self.start_seconds),
float(self.end_seconds) - float(dirname)))
def beautify_timedelta(self, timedelta):
"""Make it printable for the user"""
for times in self._report_db.values():
log.debug("Adding %s to %s time..." % (times, count))
count = count + float(times)
return count
def total_time(self):
"""Return total time tracked"""
pass
count = 0
for times in self._report_db.values():
log.debug("Adding %s to %s time..." % (times, count))
count = count + float(times)
return count
@staticmethod
def default_dates():

View file

@ -21,17 +21,14 @@
#
import datetime
#import signal
import locale
import logging
import time
import os
import os.path
import sys
import ctt
log = logging.getLogger(__name__)
class Tracker:
@ -39,10 +36,14 @@ class Tracker:
self.project = project
self.tracked_time = False
self._init_home()
self.project_dir = project_dir(project)
self.project_dir = ctt.project_dir(project)
@classmethod
def commandline(cls, args):
tracker = cls(args.project[0])
tracker.track_time()
tracker.write_time()
print(tracker.delta())
# Track time and return information from tracking
def track_time(self):
@ -74,12 +75,14 @@ class Tracker:
time_dir = os.path.join(self.project_dir, start_seconds)
os.makedirs(time_dir, mode=0o700, exist_ok=True)
filename = os.path.join(time_dir, FILE_DELTA)
filename = os.path.join(time_dir, ctt.FILE_DELTA)
with open(filename, "w") as fd:
fd.write("%s\n" % delta_seconds)
def delta(self, in_seconds=True):
"""Return time delta - empty (==0) if not tracked"""
if self.tracked_time:
delta = self.stop - self.start
else: