changeset 380:20fde79f8e12

Move all scripts in a common scripts directory Currently console scripts were kept in several directories. Now use a common directory for all scripts.
author Björn Ricks <bjoern.ricks@intevation.de>
date Mon, 05 Jan 2015 10:54:20 +0100
parents 47890f38e558
children 2f9acd073dd3
files contrib/convert-projects contrib/getan_report.py contrib/wochenbericht getan/contrib/__init__.py getan/contrib/getan-eval.py getan/contrib/zeiterfassung.py getan/contrib/zeitsort.py scripts/convert-projects scripts/getan-eval.py scripts/getan_report.py scripts/wochenbericht scripts/zeiterfassung.py scripts/zeitsort.py setup.py
diffstat 13 files changed, 475 insertions(+), 469 deletions(-) [+]
line wrap: on
line diff
--- a/contrib/convert-projects	Wed Mar 12 10:57:21 2014 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,11 +0,0 @@
-#!/usr/bin/awk -f
-
-# Convert classic worklog projects file to SQL statements for inseration in the getan database.
-# USAGE:
-# ./convert-projects </PATH/TO/projects | sqlite3 time.db
-
-BEGIN { FS=":"; }
-
-/[^# \t]/ {
-    printf "INSERT INTO projects (key, description) VALUES ('%s', '%s');\n", $1, $2;
-}
--- a/contrib/getan_report.py	Wed Mar 12 10:57:21 2014 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,159 +0,0 @@
-#!/usr/bin/env python3
-"""write a daily report accessing a database from http://hg.intevation.de/getan 1.1dev3."""
-# hastily done, written to learn the getan database format and its manipulation
-# Free Software under GNU GPL v>=3
-# 20130109 bernhard@intevation.de
-# 20140103 bernhard@intevation.de:
-#   started from 2013/getan-writeout-timesorted.py
-#   ported to python3. Removed the dependency for functions from worklog.py.
-#   the timesorted variant can be uncommented in the code for now
-# 20140109 bernhard@intevation.de:
-#   Total time output format improved.
-# 20140120 bernhard@intevation.de:
-#   added command line options, requires argparse module now (e.g. Python>=3.2)
-# 20141104 bernhard@intevation.de:
-#   migration to argparse complete, added -t option
-# TODO: 
-#  * use python v>=3.2 variants in the code where noted.
-
-import argparse
-import datetime
-import logging
-import sqlite3
-import sys
-
-factor = {'privat' : 0}
-
-l = logging
-l.basicConfig(level=logging.INFO,
-#l.basicConfig(level=logging.DEBUG,
-                    format='%(message)s')
-#                    format='%(asctime)s %(levelname)s %(message)s')
-
-def hhhmm_from_timedelta(td):
-    """Return a string '-HHH:MM' from the timedelta parameter.
-
-    Accounts for way the integer division works for negative numbers:
-        -2 // 60 == -1
-        -2 % 60 == 58
-    by first working on the positive number and then adding the minus 
-    to the string.
-
-    For python >=3.1. Successor of hhmm_from_timedelta() from
-    http://intevation.de/cgi-bin/viewcvs-misc.cgi/worklog.py/ .
-    """
-    total_minutes = abs(round(td.days*24*60 + td.seconds/60))
-    # variant for Python v>3.2:
-    #total_minutes = abs(round(td/datetime.timedelta(minutes=1)))
-
-    hours = total_minutes//60
-    minutes = total_minutes%60
-
-    h_string = "{}".format(hours)
-
-    if(td.days<0):
-        h_string = "-" + h_string
-
-    return "{:>3s}:{:02d}".format(h_string, minutes)
-
-def self_test():
-    """Run some simple tests on hhhmm_from_timedelta().
-
-    e.g. run like
-        python3 -c 'from getan_report_20140103 import *; self_test()'
-    """
-    l.info(hhhmm_from_timedelta(datetime.timedelta(minutes=1)))
-    l.info(hhhmm_from_timedelta(datetime.timedelta(minutes=-2)))
-
-def main():
-    parser = argparse.ArgumentParser(description=__doc__)
-    parser.add_argument("-t", action='store_true',
-        help="timesorted output and default reportday to today")
-    parser.add_argument("dbfilename")
-    parser.add_argument("reportday", nargs='?', 
-        help="day to report  yyyy-mm-dd")
-
-    args = parser.parse_args()
-    l.debug(args)
-
-    if args.reportday:
-        report_range_start = \
-            datetime.datetime.strptime(args.reportday, "%Y-%m-%d")
-    elif args.t:
-        # start with today 00:00
-        report_range_start = datetime.datetime.combine(
-                            datetime.date.today(), datetime.time())
-    else:
-        # start with yesterday 00:00
-        report_range_start = datetime.datetime.combine(
-                    datetime.date.today() - datetime.timedelta(days=1),
-                    datetime.time())
-    report_range_end = report_range_start + datetime.timedelta(days=1)
-
-
-    l.info("Opening sqlite3 database '%s'" % args.dbfilename)
-    conn = sqlite3.connect(args.dbfilename, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
-    c = conn.cursor()
-
-    tasks = {}
-    task_total = {}
-
-    c.execute('select * from projects')
-    for t in c:
-        l.debug(t)
-        tasks[t[0]] = t[2]
-        task_total[t[0]] = datetime.timedelta()
-
-# from getan 1.0 20130103
-#CREATE TABLE entries (
-#    id          INTEGER PRIMARY KEY AUTOINCREMENT,
-#    project_id  INTEGER REFERENCES projects(id),
-#    start_time  TIMESTAMP NOT NULL,
-#    stop_time   TIMESTAMP NOT NULL,
-#    description VARCHAR(256),
-#
-#    CHECK (strftime('%s', start_time) <= strftime('%s', stop_time))
-#);
-
-    total_time = datetime.timedelta()
-
-    if args.t:
-        c.execute('select * from entries order by start_time')
-    else:
-        c.execute('select * from entries order by project_id')
-    for e in c:
-        l.debug(e)
-        length = e[3]-e[2]
-
-        desc = tasks[e[1]]
-
-        if e[2] >= report_range_start and e[2] < report_range_end:
-            if args.t:
-                print("{2}: {3} {4}\n\t\t\t{0} {1}".
-                  format(e[2], e[3], desc, e[4],hhhmm_from_timedelta(length)))
-            else:
-                print("{0} {2}: {3} {4}".
-                  format(e[2], e[3], desc, e[4],hhhmm_from_timedelta(length)))
-            if desc in factor:
-                ##python3.1 does not allow timedelta division. 
-                ##TODO: Make python3.1 save or update to python3.2.
-                #l.info("applying factor %f to entry %s" % (factor[desc], e))
-                #length = (length * int(factor[desc]*1000))/1000
-                #Until python3.2 we only honor a factor of zero:
-                if factor[desc] == 0:
-                    length = datetime.timedelta(0)
-                    l.info("not counting {}".format(e))
-                else:
-                    l.info("ignoring factor {}".factor[desc])
-            total_time += length
-            task_total[e[1]] += length
-
-    print("(" + hhhmm_from_timedelta(total_time).strip() + ")")
-    for t in tasks:
-        if task_total[t] != datetime.timedelta(0):
-            print("\t" + tasks[t], hhhmm_from_timedelta(task_total[t]))
-
-    c.close()
-
-if __name__ == "__main__":
-    main()
--- a/contrib/wochenbericht	Wed Mar 12 10:57:21 2014 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,77 +0,0 @@
-#!/bin/bash
-#
-# wochenbericht
-# -------------
-# (c) 2008 by Sascha L. Teichmann
-
-# Little script to summarize times within a given week.
-# usage:
-# ./wochenbericht [<week of year>] [<getan database file>]
-# week defaults to current week, database to time.db
-#
-# This is Free Software in terms of GPLv3 or later. See
-# LICENSE coming with getan for details.
-#
-usage() {
-    cat <<EOF
-usage: ./wochenbericht [<week of year>] [<year>] [<getan database file>] 
-    <week of year>        defaults to current week
-    <year>                defaults to current year
-    <getan database file> defaults to time.db
-EOF
-    exit 1
-}
-
-if [ "$1" ==  "--help" -o "$1" == "-h" ]; then
-    usage
-fi
-
-
-if [[ "$1" -eq "" ]]; then
-    WEEK=`date +'%W'`
-    # remove hash below if you want previous week
-    #WEEK=`expr ${WEEK} '-' 1 '|' 52`
-else
-    WEEK=$1
-fi
-
-if [[ "$2" -eq "" ]]; then
-    YEAR=`date +'%Y'`
-else
-    YEAR=$2
-fi
-
-TIME_DB=${3:-time.db}
-
-if [ ! -f ${TIME_DB} ]; then
-    echo "error: Database file ${TIME_DB} does not exist."
-    usage
-fi
-
-sqlite3 ${TIME_DB} "
-SELECT coalesce(description, 'Verschiedenes'), total FROM projects 
-INNER JOIN (
-    SELECT 
-        project_id,
-        sum(strftime('%s', stop_time) - strftime('%s', start_time)) AS total
-    FROM entries
-    WHERE (strftime('%W', start_time) = '${WEEK}' AND
-        strftime('%Y', start_time) = '${YEAR}') OR 
-        (strftime('%W', stop_time)  = '${WEEK}' AND
-        strftime('%Y', stop_time) = '${YEAR}')
-    GROUP BY project_id
-) ON id = project_id
-WHERE active;
-" | awk '
-function human_time(t) {
-    h = int(t / 3600)
-    m = int((t % 3600)/60.0 + 0.5)
-    while (m >= 60) { ++h; m -= 60 }
-    return sprintf("%2d:%02dh", h, m)
-}
-BEGIN { FS="|"; sum = 0 }
-      { sum += $2 
-        printf("%s: %s\n", human_time($2), $1) 
-      }
-END   { printf("%s: Gesamt\n", human_time(sum)) } 
-'
--- a/getan/contrib/getan-eval.py	Wed Mar 12 10:57:21 2014 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-# (c) 2013, 2014 by Björn Ricks <bjoern.ricks@intevation.de>
-#
-# This is Free Software licensed under the terms of GPLv3 or later.
-# For details see LICENSE coming with the source of 'getan'.
-
-import codecs
-import locale
-import sys
-
-from datetime import date, datetime, timedelta
-from optparse import OptionParser
-
-from getan.template import render
-
-
-def main():
-    parser = OptionParser()
-    parser.add_option("-d", "--database", dest="database",
-                      help="getan database",  metavar="DATABASE")
-    parser.add_option("-t", "--template", dest="template", metavar="TEMPLATE",
-                      help="name of getan template")
-    parser.add_option("-u", "--user", dest="user", help="name of user")
-    parser.add_option("-p", "--project", dest="project",
-                      help="key of output project")
-    parser.add_option("-w", "--week", type="int", dest="week",
-                      help="week of year")
-    parser.add_option("-y", "--year", type="int", dest="year", help="year")
-    parser.add_option("-c", "--lastweek", dest="lastweek",
-                      help="entries of last working week",
-                      action="store_true")
-    parser.add_option("-m", "--empty", dest="empty",
-                      help="show projects without an entries",
-                      action="store_true")
-    parser.add_option("--encoding", dest="encoding",
-                      help="encoding of output", metavar="ENCODING")
-
-    (options, args) = parser.parse_args()
-
-    if options.lastweek:
-        week = (datetime.now() - timedelta(7)).isocalendar()[1]
-        year = int(date.today().strftime("%Y"))
-    else:
-        year = options.year
-        week = options.week
-
-    template_name = options.template or "wochenbericht"
-
-    if not options.encoding:
-        encoding = locale.getdefaultlocale()[1]
-
-    Writer = codecs.getwriter(encoding)
-    sys.stdout = Writer(sys.stdout)
-
-    print render(database=options.database, user=options.user,
-                 template=template_name, year=year, week=week,
-                 project=options.project, empty_projects=options.empty)
-
-
-if __name__ == '__main__':
-    main()
-
-# vim:set ts=4 sw=4 si et sta sts=4 :
--- a/getan/contrib/zeiterfassung.py	Wed Mar 12 10:57:21 2014 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,100 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-# zeiterfassung
-# -------------
-# (c) 2008 by Sascha L. Teichmann <sascha.teichmann@intevation.de>
-# (c) 2011, 2012 by Björn Ricks <bjoern.ricks@intevation.de>
-#
-# Simple script which generates lines for zeiterfassung.txt files.
-#
-# This is Free Software licensed under the terms of GPLv3 or later.
-# For details see LICENSE coming with the source of 'getan'.
-#
-import sys
-import getopt
-import codecs
-import locale
-
-from datetime import datetime, timedelta
-
-from getan.template import render
-
-DEFAULT_DATABASE = "time.db"
-
-ZEITERFASSUNG_TEMPLATE = "zeiterfassung"
-
-USAGE = '''usage: %s <options>
-    with <options>
-    [--user=|-u <user>]        : Name of user,          default: $USER
-    [--database=|-d <database>]: getan database,        default: time.db
-    [--project=|-p <key>]      : Key of output project, default: all
-    [--encoding=|-e encoding]  : encoding of output,    default: none
-    [--week=]|-w <week>]       : week of year
-    [--year=]|-y <year>]       : year
-    [--list|-l]                : list all projects
-    [--help|-h]                : This text
-    [--emtpy|-m]               : show empty projects
-    [--lastweek|-c]            : entries of last working week'''
-
-
-def usage(exit_code=0):
-    print USAGE % sys.argv[0]
-    sys.exit(exit_code)
-
-
-def main():
-
-    database = DEFAULT_DATABASE
-    user = None
-    list_projects = False
-    project = None
-    encoding = None
-    week = None
-    year = None
-    empty_proj = False
-    database = None
-    template = ZEITERFASSUNG_TEMPLATE
-
-    opts, args = getopt.getopt(
-        sys.argv[1:],
-        'd:u:p:e:hl:w:y:mc',
-        ['database=', 'user=', 'project=', 'encoding=', 'help', 'list', 'week=',
-            'year=', 'empty', 'lastweek'])
-
-    for opt, val in opts:
-        if opt in ("--database", "-d"):
-            database = val
-        elif opt in ("--user", "-u"):
-            user = val
-        elif opt in ("--project", "-p"):
-            project = val
-        elif opt in ("--encoding", "-e"):
-            encoding = val
-        elif opt in ("--help", "-h"):
-            usage()
-        elif opt in ("--list", "-l"):
-            list_projects = True
-        elif opt in ("--year", "-y"):
-            year = val
-        elif opt in ("--week", "-w"):
-            week = int(val)
-        elif opt in ("--lastweek", "-c") and not week:
-            week = (datetime.now() - timedelta(7)).isocalendar()[1]
-        elif opt in ("--empty", "-m"):
-            empty_proj = True
-
-    if not encoding:
-        encoding = locale.getdefaultlocale()[1]
-
-    Writer = codecs.getwriter(encoding)
-    sys.stdout = Writer(sys.stdout)
-
-    print render(user=user, database=database, week=week, year=year,
-                 template=template, project=project, empty_projects=empty_proj)
-
-
-if __name__ == '__main__':
-    main()
-
-# vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- a/getan/contrib/zeitsort.py	Wed Mar 12 10:57:21 2014 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,49 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-# zeitsort
-# --------
-# (c) 2008 by Sascha L. Teichmann <sascha.teichmann@intevation.de>
-#
-# Simple script which sorts lines of zeiterfassung.txt files by date.
-#
-# This is Free Software licensed under the terms of GPLv3 or later.
-# For details see LICENSE coming with the source of 'getan'.
-#
-
-import sys
-import re
-
-from datetime import date
-
-DATE = re.compile("(\d\d)\.(\d\d)\.(\d\d\d\d)")
-
-def date_cmp(a, b):
-    ma = DATE.search(a)
-    mb = DATE.search(b)
-    if not ma and not mb: return cmp(a, b)
-    if ma and not mb: return -1
-    if not ma and mb: return +1
-    da = date(int(ma.group(3)), int(ma.group(2)), int(ma.group(1)))
-    db = date(int(mb.group(3)), int(mb.group(2)), int(mb.group(1)))
-    return cmp(da, db)
-
-def main():
-    all = []
-    while True:
-        line = sys.stdin.readline()
-        if not line: break
-        if not DATE.search(line):
-            # handle multi lines
-            if not all: all.append(line)
-            else:       all[-1] += line
-        else:
-            all.append(line)
-    all.sort(date_cmp)
-    sys.stdout.write(''.join(all))
-    sys.stdout.flush()
-
-if __name__ == '__main__':
-    main()
-
-# vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/convert-projects	Mon Jan 05 10:54:20 2015 +0100
@@ -0,0 +1,11 @@
+#!/usr/bin/awk -f
+
+# Convert classic worklog projects file to SQL statements for inseration in the getan database.
+# USAGE:
+# ./convert-projects </PATH/TO/projects | sqlite3 time.db
+
+BEGIN { FS=":"; }
+
+/[^# \t]/ {
+    printf "INSERT INTO projects (key, description) VALUES ('%s', '%s');\n", $1, $2;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/getan-eval.py	Mon Jan 05 10:54:20 2015 +0100
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# (c) 2013, 2014 by Björn Ricks <bjoern.ricks@intevation.de>
+#
+# This is Free Software licensed under the terms of GPLv3 or later.
+# For details see LICENSE coming with the source of 'getan'.
+
+import codecs
+import locale
+import sys
+
+from datetime import date, datetime, timedelta
+from optparse import OptionParser
+
+from getan.template import render
+
+
+def main():
+    parser = OptionParser()
+    parser.add_option("-d", "--database", dest="database",
+                      help="getan database",  metavar="DATABASE")
+    parser.add_option("-t", "--template", dest="template", metavar="TEMPLATE",
+                      help="name of getan template")
+    parser.add_option("-u", "--user", dest="user", help="name of user")
+    parser.add_option("-p", "--project", dest="project",
+                      help="key of output project")
+    parser.add_option("-w", "--week", type="int", dest="week",
+                      help="week of year")
+    parser.add_option("-y", "--year", type="int", dest="year", help="year")
+    parser.add_option("-c", "--lastweek", dest="lastweek",
+                      help="entries of last working week",
+                      action="store_true")
+    parser.add_option("-m", "--empty", dest="empty",
+                      help="show projects without an entries",
+                      action="store_true")
+    parser.add_option("--encoding", dest="encoding",
+                      help="encoding of output", metavar="ENCODING")
+
+    (options, args) = parser.parse_args()
+
+    if options.lastweek:
+        week = (datetime.now() - timedelta(7)).isocalendar()[1]
+        year = int(date.today().strftime("%Y"))
+    else:
+        year = options.year
+        week = options.week
+
+    template_name = options.template or "wochenbericht"
+
+    if not options.encoding:
+        encoding = locale.getdefaultlocale()[1]
+
+    Writer = codecs.getwriter(encoding)
+    sys.stdout = Writer(sys.stdout)
+
+    print render(database=options.database, user=options.user,
+                 template=template_name, year=year, week=week,
+                 project=options.project, empty_projects=options.empty)
+
+
+if __name__ == '__main__':
+    main()
+
+# vim:set ts=4 sw=4 si et sta sts=4 :
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/getan_report.py	Mon Jan 05 10:54:20 2015 +0100
@@ -0,0 +1,159 @@
+#!/usr/bin/env python3
+"""write a daily report accessing a database from http://hg.intevation.de/getan 1.1dev3."""
+# hastily done, written to learn the getan database format and its manipulation
+# Free Software under GNU GPL v>=3
+# 20130109 bernhard@intevation.de
+# 20140103 bernhard@intevation.de:
+#   started from 2013/getan-writeout-timesorted.py
+#   ported to python3. Removed the dependency for functions from worklog.py.
+#   the timesorted variant can be uncommented in the code for now
+# 20140109 bernhard@intevation.de:
+#   Total time output format improved.
+# 20140120 bernhard@intevation.de:
+#   added command line options, requires argparse module now (e.g. Python>=3.2)
+# 20141104 bernhard@intevation.de:
+#   migration to argparse complete, added -t option
+# TODO: 
+#  * use python v>=3.2 variants in the code where noted.
+
+import argparse
+import datetime
+import logging
+import sqlite3
+import sys
+
+factor = {'privat' : 0}
+
+l = logging
+l.basicConfig(level=logging.INFO,
+#l.basicConfig(level=logging.DEBUG,
+                    format='%(message)s')
+#                    format='%(asctime)s %(levelname)s %(message)s')
+
+def hhhmm_from_timedelta(td):
+    """Return a string '-HHH:MM' from the timedelta parameter.
+
+    Accounts for way the integer division works for negative numbers:
+        -2 // 60 == -1
+        -2 % 60 == 58
+    by first working on the positive number and then adding the minus 
+    to the string.
+
+    For python >=3.1. Successor of hhmm_from_timedelta() from
+    http://intevation.de/cgi-bin/viewcvs-misc.cgi/worklog.py/ .
+    """
+    total_minutes = abs(round(td.days*24*60 + td.seconds/60))
+    # variant for Python v>3.2:
+    #total_minutes = abs(round(td/datetime.timedelta(minutes=1)))
+
+    hours = total_minutes//60
+    minutes = total_minutes%60
+
+    h_string = "{}".format(hours)
+
+    if(td.days<0):
+        h_string = "-" + h_string
+
+    return "{:>3s}:{:02d}".format(h_string, minutes)
+
+def self_test():
+    """Run some simple tests on hhhmm_from_timedelta().
+
+    e.g. run like
+        python3 -c 'from getan_report_20140103 import *; self_test()'
+    """
+    l.info(hhhmm_from_timedelta(datetime.timedelta(minutes=1)))
+    l.info(hhhmm_from_timedelta(datetime.timedelta(minutes=-2)))
+
+def main():
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument("-t", action='store_true',
+        help="timesorted output and default reportday to today")
+    parser.add_argument("dbfilename")
+    parser.add_argument("reportday", nargs='?', 
+        help="day to report  yyyy-mm-dd")
+
+    args = parser.parse_args()
+    l.debug(args)
+
+    if args.reportday:
+        report_range_start = \
+            datetime.datetime.strptime(args.reportday, "%Y-%m-%d")
+    elif args.t:
+        # start with today 00:00
+        report_range_start = datetime.datetime.combine(
+                            datetime.date.today(), datetime.time())
+    else:
+        # start with yesterday 00:00
+        report_range_start = datetime.datetime.combine(
+                    datetime.date.today() - datetime.timedelta(days=1),
+                    datetime.time())
+    report_range_end = report_range_start + datetime.timedelta(days=1)
+
+
+    l.info("Opening sqlite3 database '%s'" % args.dbfilename)
+    conn = sqlite3.connect(args.dbfilename, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
+    c = conn.cursor()
+
+    tasks = {}
+    task_total = {}
+
+    c.execute('select * from projects')
+    for t in c:
+        l.debug(t)
+        tasks[t[0]] = t[2]
+        task_total[t[0]] = datetime.timedelta()
+
+# from getan 1.0 20130103
+#CREATE TABLE entries (
+#    id          INTEGER PRIMARY KEY AUTOINCREMENT,
+#    project_id  INTEGER REFERENCES projects(id),
+#    start_time  TIMESTAMP NOT NULL,
+#    stop_time   TIMESTAMP NOT NULL,
+#    description VARCHAR(256),
+#
+#    CHECK (strftime('%s', start_time) <= strftime('%s', stop_time))
+#);
+
+    total_time = datetime.timedelta()
+
+    if args.t:
+        c.execute('select * from entries order by start_time')
+    else:
+        c.execute('select * from entries order by project_id')
+    for e in c:
+        l.debug(e)
+        length = e[3]-e[2]
+
+        desc = tasks[e[1]]
+
+        if e[2] >= report_range_start and e[2] < report_range_end:
+            if args.t:
+                print("{2}: {3} {4}\n\t\t\t{0} {1}".
+                  format(e[2], e[3], desc, e[4],hhhmm_from_timedelta(length)))
+            else:
+                print("{0} {2}: {3} {4}".
+                  format(e[2], e[3], desc, e[4],hhhmm_from_timedelta(length)))
+            if desc in factor:
+                ##python3.1 does not allow timedelta division. 
+                ##TODO: Make python3.1 save or update to python3.2.
+                #l.info("applying factor %f to entry %s" % (factor[desc], e))
+                #length = (length * int(factor[desc]*1000))/1000
+                #Until python3.2 we only honor a factor of zero:
+                if factor[desc] == 0:
+                    length = datetime.timedelta(0)
+                    l.info("not counting {}".format(e))
+                else:
+                    l.info("ignoring factor {}".factor[desc])
+            total_time += length
+            task_total[e[1]] += length
+
+    print("(" + hhhmm_from_timedelta(total_time).strip() + ")")
+    for t in tasks:
+        if task_total[t] != datetime.timedelta(0):
+            print("\t" + tasks[t], hhhmm_from_timedelta(task_total[t]))
+
+    c.close()
+
+if __name__ == "__main__":
+    main()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/wochenbericht	Mon Jan 05 10:54:20 2015 +0100
@@ -0,0 +1,77 @@
+#!/bin/bash
+#
+# wochenbericht
+# -------------
+# (c) 2008 by Sascha L. Teichmann
+
+# Little script to summarize times within a given week.
+# usage:
+# ./wochenbericht [<week of year>] [<getan database file>]
+# week defaults to current week, database to time.db
+#
+# This is Free Software in terms of GPLv3 or later. See
+# LICENSE coming with getan for details.
+#
+usage() {
+    cat <<EOF
+usage: ./wochenbericht [<week of year>] [<year>] [<getan database file>] 
+    <week of year>        defaults to current week
+    <year>                defaults to current year
+    <getan database file> defaults to time.db
+EOF
+    exit 1
+}
+
+if [ "$1" ==  "--help" -o "$1" == "-h" ]; then
+    usage
+fi
+
+
+if [[ "$1" -eq "" ]]; then
+    WEEK=`date +'%W'`
+    # remove hash below if you want previous week
+    #WEEK=`expr ${WEEK} '-' 1 '|' 52`
+else
+    WEEK=$1
+fi
+
+if [[ "$2" -eq "" ]]; then
+    YEAR=`date +'%Y'`
+else
+    YEAR=$2
+fi
+
+TIME_DB=${3:-time.db}
+
+if [ ! -f ${TIME_DB} ]; then
+    echo "error: Database file ${TIME_DB} does not exist."
+    usage
+fi
+
+sqlite3 ${TIME_DB} "
+SELECT coalesce(description, 'Verschiedenes'), total FROM projects 
+INNER JOIN (
+    SELECT 
+        project_id,
+        sum(strftime('%s', stop_time) - strftime('%s', start_time)) AS total
+    FROM entries
+    WHERE (strftime('%W', start_time) = '${WEEK}' AND
+        strftime('%Y', start_time) = '${YEAR}') OR 
+        (strftime('%W', stop_time)  = '${WEEK}' AND
+        strftime('%Y', stop_time) = '${YEAR}')
+    GROUP BY project_id
+) ON id = project_id
+WHERE active;
+" | awk '
+function human_time(t) {
+    h = int(t / 3600)
+    m = int((t % 3600)/60.0 + 0.5)
+    while (m >= 60) { ++h; m -= 60 }
+    return sprintf("%2d:%02dh", h, m)
+}
+BEGIN { FS="|"; sum = 0 }
+      { sum += $2 
+        printf("%s: %s\n", human_time($2), $1) 
+      }
+END   { printf("%s: Gesamt\n", human_time(sum)) } 
+'
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/zeiterfassung.py	Mon Jan 05 10:54:20 2015 +0100
@@ -0,0 +1,100 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# zeiterfassung
+# -------------
+# (c) 2008 by Sascha L. Teichmann <sascha.teichmann@intevation.de>
+# (c) 2011, 2012 by Björn Ricks <bjoern.ricks@intevation.de>
+#
+# Simple script which generates lines for zeiterfassung.txt files.
+#
+# This is Free Software licensed under the terms of GPLv3 or later.
+# For details see LICENSE coming with the source of 'getan'.
+#
+import sys
+import getopt
+import codecs
+import locale
+
+from datetime import datetime, timedelta
+
+from getan.template import render
+
+DEFAULT_DATABASE = "time.db"
+
+ZEITERFASSUNG_TEMPLATE = "zeiterfassung"
+
+USAGE = '''usage: %s <options>
+    with <options>
+    [--user=|-u <user>]        : Name of user,          default: $USER
+    [--database=|-d <database>]: getan database,        default: time.db
+    [--project=|-p <key>]      : Key of output project, default: all
+    [--encoding=|-e encoding]  : encoding of output,    default: none
+    [--week=]|-w <week>]       : week of year
+    [--year=]|-y <year>]       : year
+    [--list|-l]                : list all projects
+    [--help|-h]                : This text
+    [--emtpy|-m]               : show empty projects
+    [--lastweek|-c]            : entries of last working week'''
+
+
+def usage(exit_code=0):
+    print USAGE % sys.argv[0]
+    sys.exit(exit_code)
+
+
+def main():
+
+    database = DEFAULT_DATABASE
+    user = None
+    list_projects = False
+    project = None
+    encoding = None
+    week = None
+    year = None
+    empty_proj = False
+    database = None
+    template = ZEITERFASSUNG_TEMPLATE
+
+    opts, args = getopt.getopt(
+        sys.argv[1:],
+        'd:u:p:e:hl:w:y:mc',
+        ['database=', 'user=', 'project=', 'encoding=', 'help', 'list', 'week=',
+            'year=', 'empty', 'lastweek'])
+
+    for opt, val in opts:
+        if opt in ("--database", "-d"):
+            database = val
+        elif opt in ("--user", "-u"):
+            user = val
+        elif opt in ("--project", "-p"):
+            project = val
+        elif opt in ("--encoding", "-e"):
+            encoding = val
+        elif opt in ("--help", "-h"):
+            usage()
+        elif opt in ("--list", "-l"):
+            list_projects = True
+        elif opt in ("--year", "-y"):
+            year = val
+        elif opt in ("--week", "-w"):
+            week = int(val)
+        elif opt in ("--lastweek", "-c") and not week:
+            week = (datetime.now() - timedelta(7)).isocalendar()[1]
+        elif opt in ("--empty", "-m"):
+            empty_proj = True
+
+    if not encoding:
+        encoding = locale.getdefaultlocale()[1]
+
+    Writer = codecs.getwriter(encoding)
+    sys.stdout = Writer(sys.stdout)
+
+    print render(user=user, database=database, week=week, year=year,
+                 template=template, project=project, empty_projects=empty_proj)
+
+
+if __name__ == '__main__':
+    main()
+
+# vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/zeitsort.py	Mon Jan 05 10:54:20 2015 +0100
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# zeitsort
+# --------
+# (c) 2008 by Sascha L. Teichmann <sascha.teichmann@intevation.de>
+#
+# Simple script which sorts lines of zeiterfassung.txt files by date.
+#
+# This is Free Software licensed under the terms of GPLv3 or later.
+# For details see LICENSE coming with the source of 'getan'.
+#
+
+import sys
+import re
+
+from datetime import date
+
+DATE = re.compile("(\d\d)\.(\d\d)\.(\d\d\d\d)")
+
+def date_cmp(a, b):
+    ma = DATE.search(a)
+    mb = DATE.search(b)
+    if not ma and not mb: return cmp(a, b)
+    if ma and not mb: return -1
+    if not ma and mb: return +1
+    da = date(int(ma.group(3)), int(ma.group(2)), int(ma.group(1)))
+    db = date(int(mb.group(3)), int(mb.group(2)), int(mb.group(1)))
+    return cmp(da, db)
+
+def main():
+    all = []
+    while True:
+        line = sys.stdin.readline()
+        if not line: break
+        if not DATE.search(line):
+            # handle multi lines
+            if not all: all.append(line)
+            else:       all[-1] += line
+        else:
+            all.append(line)
+    all.sort(date_cmp)
+    sys.stdout.write(''.join(all))
+    sys.stdout.flush()
+
+if __name__ == '__main__':
+    main()
+
+# vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:
--- a/setup.py	Wed Mar 12 10:57:21 2014 +0100
+++ b/setup.py	Mon Jan 05 10:54:20 2015 +0100
@@ -9,15 +9,19 @@
 # For details see LICENSE coming with the source of 'getan'.
 #
 
+import glob
+import os.path
+
 from setuptools import setup, find_packages
 
-import os.path
-
 import getan
 
+cur_dir = os.path.dirname(__file__)
+scripts_dir = os.path.join(cur_dir, "scripts")
+
 
 def read(fname):
-    with open(os.path.join(os.path.dirname(__file__), fname)) as f:
+    with open(os.path.join(cur_dir, fname)) as f:
         return f.read()
 
 setup(name="getan",
@@ -27,13 +31,15 @@
       license="GPLv3+",
       long_description=read("README"),
       packages=find_packages(),
-      package_data={"": ["*.txt"], },
+      package_data={
+          "": ["*.txt"],
+      },
+      scripts=glob.glob(os.path.join(scripts_dir, "*.py")) +
+      [os.path.join(scripts_dir, "wochenbericht"),
+       os.path.join(scripts_dir, "convert-projects")],
       entry_points={"console_scripts":
                     ["getan=getan.main:main",
                      "getan-classic=getan.classic.getan:main",
-                     "zeiterfassung=getan.contrib.zeiterfassung:main",
-                     "getan-eval=getan.contrib.getan-eval:main",
-                     "zeitsort=getan.contrib.zeitsort:main",
                      ]},
       classifiers=[
           "Topic :: Utilities",
@@ -43,5 +49,5 @@
           "License :: OSI Approved :: GNU General Public License (GPL)",
           "Operating System :: POSIX",
           "Programming Language :: Python",
-      ]
+      ],
       )
This site is hosted by Intevation GmbH (Datenschutzerklärung und Impressum | Privacy Policy and Imprint)