-
Notifications
You must be signed in to change notification settings - Fork 2
/
wp
executable file
·314 lines (284 loc) · 11.4 KB
/
wp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#!/usr/bin/env python
import sys
import os
import re
import datetime
import collections
import termcolor
from prettytable import PrettyTable
action = sys.argv[ 1 ]
homeDir = os.getenv( 'HOME' )
allocationsConf = os.path.join(
homeDir, '.todo.actions.d/wp/allocations.conf' )
todoFile = os.getenv( 'TODO_FILE' )
doneFile = os.getenv( 'DONE_FILE' )
MAX_TOLERANCE = 15
def timeStr( timeMins ):
return "%s mins (%.1f hrs)" % ( timeMins, int( timeMins ) / 60.0 )
def doAddTask( newTask ):
estimate = re.search( "est:(\d+)", newTask )
newTaskIndex = len( getTasksForProject( '' ) ) + 1
if not estimate:
print "Task is missing estimate !!"
return
with open( todoFile, "a" ) as f:
f.write( newTask + "\n" )
print "%s %s" % ( newTaskIndex, newTask )
print "TODO: %s added." % newTaskIndex
def projectsInAlloc():
lines = None
allocations = { }
with open( allocationsConf, "r" ) as f:
for line in f.readlines():
project, timeMins = line.strip().split( ":" )
allocations[ project ] = int( timeMins )
return allocations
def getSundayOfTheWeek( anyDayOfWeek ):
dayOfWeek = datetime.date( *tuple(
[ int( x ) for x in anyDayOfWeek.split( "-" ) ] ) )
dayIndex = dayOfWeek.isoweekday() % 7
sundayOfTheWeek = dayOfWeek - datetime.timedelta( days=dayIndex )
return sundayOfTheWeek
def getMinorEst( line ):
match = re.search( "min:(\d+)", line )
if match:
return int( match.group( 1 ) )
else:
match = re.search( "est:(\d+)", line )
assert match
return int( match.group( 1 ) )
def timeSpentOnWeek( anyDayOfWeek=None, projects=None ):
if not projects:
projects = projectsInAlloc().keys()
if not anyDayOfWeek:
anyDayOfWeek = datetime.date.today().isoformat()
sundayOfTheWeek = getSundayOfTheWeek( anyDayOfWeek )
daysOfWeek = [
( sundayOfTheWeek + datetime.timedelta( days=x ) ).isoformat()
for x in range( 7 ) ]
searchRegex = (
r"^x (%s).*(%s)" %
( "|".join( daysOfWeek ),
"|".join( [ x.replace( "+", "\+" ) for x in projects ] ) ) )
timeSpent = collections.defaultdict( lambda: 0 )
with open( doneFile, "r" ) as f:
for line in f.readlines():
match = re.search( searchRegex, line )
if match:
project = match.group( 2 )
timeSpent[ project ] = (
timeSpent[ project ] + getMinorEst( line ) )
return timeSpent
def summaryForWeek( anyDayOfWeek, projects=None ):
printTotal = False
if not projects:
projects = projectsInAlloc().keys()
printTotal = True
sundayOfThisWeek = getSundayOfTheWeek(
datetime.date.today().isoformat() )
sundayOfGivenDay = getSundayOfTheWeek( anyDayOfWeek )
allocations = projectsInAlloc()
timeSpent = timeSpentOnWeek( anyDayOfWeek, projects=projects )
totalAllocated = 0
totalCompleted = 0
color = None
prettyTable = PrettyTable(
[ 'Project', 'Time allocated', 'Time completed',
'Time left', 'Time tasks available', 'Percent complete' ] )
emptyRow = [ "", "", "", "", "", "" ]
def colored_string( string ):
return termcolor.colored( string, color )
# This week
for project in projects:
timeAllocated = allocations[ project ]
timeCompleted = timeSpent[ project ]
totalAllocated += timeAllocated
totalCompleted += timeCompleted
color = getColorForGraphLine( timeCompleted, timeAllocated )
percentComplete = (
timeSpent[ project ] * 100.0 / timeAllocated )
timeAvailableTasks = sum(
getMinorEst( x ) for x in getTasksForProject( project ) )
row = [ colored_string( project ) ]
row.append( colored_string( timeStr( timeAllocated ) ) )
row.append( colored_string( timeStr( timeCompleted ) ) )
row.append( colored_string(
timeStr( max( 0, timeAllocated - timeCompleted ) ) ) )
row.append( colored_string( timeStr( timeAvailableTasks ) ) )
row.append( colored_string( "%.01f %%" % percentComplete ) )
prettyTable.add_row( row )
prettyTable.add_row( emptyRow )
if printTotal:
color = getColorForGraphLine( totalCompleted, totalAllocated )
row = [ colored_string( "Total" ) ]
row.append( colored_string( timeStr( totalAllocated ) ) )
row.append( colored_string( timeStr( totalCompleted ) ) )
row.append( colored_string(
timeStr( max( 0, totalAllocated - totalCompleted ) ) ) )
percentComplete = ( totalCompleted * 100.0 / totalAllocated )
row.append( "" )
row.append( colored_string( "%.01f %%" % percentComplete ) )
prettyTable.add_row( row )
print prettyTable
def getConvertedNumberForGraph( number, maxNumber, reference ):
return ( number * reference ) / maxNumber
def getColorForGraphLine( timeCompleted, timeAllocated ):
percentComplete = ( timeCompleted * 100 ) / timeAllocated
if percentComplete >= 80:
return "green"
elif percentComplete >= 50:
return "cyan"
else:
return "red"
def printGraph( projectsInput ):
allocations = projectsInAlloc()
projects = projectsInput
if not projects:
projects = allocations.keys()
timeSpent = timeSpentOnWeek( None, projects=projects)
if not projectsInput:
maxNumberRef = max( sum(timeSpent.values()), sum(allocations.values()) )
else:
maxNumberRef = max( sum(timeSpent.values()), allocations[projectsInput[0]])
_, columns = os.popen('stty size', 'r').read().split()
convertedMaxNumberRef = ( int( columns ) * 4 ) / 5
sundayOfThisWeek = getSundayOfTheWeek( datetime.date.today().isoformat() )
midnightOfSundayThisWeek = datetime.datetime(
sundayOfThisWeek.year, sundayOfThisWeek.month,
sundayOfThisWeek.day, 0, 0, 0, 0 )
difference = ( datetime.datetime.now() -
midnightOfSundayThisWeek).total_seconds()
totalSecondsInAWeek = 604800
percentTimeElapsed = float( difference ) / totalSecondsInAWeek
def _printGraph( project, timeAllocated, timeCompleted, timeExpected ):
percentComplete = (
timeSpent[ project ] * 100.0 / timeAllocated )
print "%s ( %.1f%% )" % ( project, percentComplete )
color = getColorForGraphLine( timeCompleted, timeAllocated )
lineForCompleted = (
"=" * ( getConvertedNumberForGraph(
timeCompleted, maxNumberRef, convertedMaxNumberRef )
- 1 ) +
"|" )
lineForAllocated = "=" * getConvertedNumberForGraph(
timeAllocated, maxNumberRef, convertedMaxNumberRef )
convertedNumberForExpected = getConvertedNumberForGraph(
timeExpected, maxNumberRef, convertedMaxNumberRef )
lineForExpected = (
" " * ( convertedNumberForExpected - 1 ) +
"| " +
timeStr( timeExpected ) )
print termcolor.colored( lineForCompleted, color ), \
timeStr( timeCompleted )
print termcolor.colored( lineForAllocated, color ), \
timeStr( timeAllocated )
print lineForExpected
print ""
totalAllocated = 0
totalCompleted = 0
totalExpected = 0
for project in projects:
timeAllocated = allocations[ project ]
timeCompleted = timeSpent[ project ]
timeExpected = int( timeAllocated * percentTimeElapsed )
totalAllocated += timeAllocated
totalCompleted += timeCompleted
totalExpected += timeExpected
_printGraph( project, timeAllocated, timeCompleted, timeExpected )
if not projectsInput:
_printGraph( "Total", totalAllocated, totalCompleted, totalExpected )
def getTasksForProject( project ):
with open( todoFile, "r" ) as f:
return [ str( i + 1 ) + " " + x.strip()
for i, x in enumerate( f.readlines() )
if project in x ]
def getPriority( task ):
match = re.search( "^\d+\s+\((\w)\)", task )
priority = 0
if match:
priority = 92 - ord( match.group( 1 ) )
return priority
def taskComparator( task1, task2 ):
return getPriority( task1 ) - getPriority( task2 )
def coloredTaskPrint( task ):
priority = getPriority( task )
if priority:
colorMap = { 27: "yellow", 26: "green", 25: "blue",
24: "cyan", 23: "magenta" }
print termcolor.colored(
task, colorMap.get( priority, "white" ) )
else:
print task
def doLs( projects=None ):
allocations = projectsInAlloc()
timeSpent = timeSpentOnWeek( None, projects=allocations.keys())
selectedTasksForProject = collections.defaultdict( list )
if not projects:
projects = allocations.keys()
for project in projects:
timeAllocated = allocations.get( project, 10000 )
timeCompleted = timeSpent[ project ]
if timeCompleted >= timeAllocated:
continue
tasksForProject = sorted(
getTasksForProject( project ), cmp=taskComparator,
reverse=True )
notAddedTasks = [ ]
for task in tasksForProject:
time = getMinorEst( task )
if timeCompleted + time <= timeAllocated:
selectedTasksForProject[ project ].append( task )
timeCompleted += time
else:
notAddedTasks.append( task )
# Get the minimum of notAddedTasks
if notAddedTasks:
minTask = sorted(
[ ( getMinorEst( x ), x )
for x in notAddedTasks ] )[ 0 ][ 1 ]
if timeCompleted + getMinorEst( minTask ) <= MAX_TOLERANCE:
selectedTasksForProject[ project ].append( minTask )
for project, tasks in selectedTasksForProject.items():
print termcolor.colored( project, "cyan" )
for task in tasks:
coloredTaskPrint( task )
print ""
def main():
if action == "usage":
print "todo.sh wp alloc[ations] ==> Display the current allocation"
print "todo.sh wp sum[mary] ==> Display the summary for this week"
print "todo.sh wp ls ==> Display the tasks for this week"
print "todo.sh wp graph ==> Display the graph"
return
flag = sys.argv[ 2 ]
if flag.startswith( "alloc" ):
total = 0
for project, timeMins in sorted( projectsInAlloc().items() ):
total += timeMins
print "%s:%s" % ( project, timeStr( timeMins ) )
print "Total:%s" % ( timeStr( total ) )
elif flag == "ls":
projects = None
if len( sys.argv ) > 3 and sys.argv[ 3 ]:
projects = [ sys.argv[ 3 ] ]
doLs( projects )
elif flag == "graph":
projects = None
if len( sys.argv ) > 3 and sys.argv[ 3 ]:
projects = [ sys.argv[ 3 ] ]
printGraph( projects )
elif flag.startswith( "sum" ):
dayOfWeek = datetime.date.today().isoformat()
projects = None
if len( sys.argv ) > 3 and sys.argv[ 3 ]:
projects = [ sys.argv[ 3 ] ]
if len( sys.argv ) > 4 and sys.argv[ 4 ]:
dayOfWeek = sys.argv[ 4 ]
summaryForWeek( dayOfWeek, projects )
elif flag == "add":
if len( sys.argv ) < 4:
print "Missing task !!"
else:
newTask = sys.argv[ 3 ]
doAddTask( newTask )
main()