-
Notifications
You must be signed in to change notification settings - Fork 4
/
tmsa
executable file
·193 lines (174 loc) · 6.6 KB
/
tmsa
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
#!/usr/bin/env python3
# Time Management for Systems Administrators helper scripts
#
# Copyright (C) 2013 Mark Harrison
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import datetime
import glob
import os
import re
import sys
commands = {
'bringforward': ["Bring forward any unmanaged tasks to today"],
'bump': ["Bump a task to the next day", "For example, bump 2"],
'bumpall': ["Bump all tasks to the next day"],
'verify': ["Print out to do files that have unmanaged active tasks"],
'tmsa': [
"Time management for systems administrators helper script.",
"Provides a set of commands to help with the Cycle, which",
"makes use of daily to do lists.",
"This command will create symlinks for the other commands"
]
}
def make_symlinks():
"Makes symlinks for the various tmsa commands"
os.chdir(os.environ["TODO_ACTIONS_DIR"])
for command in commands:
if command == 'tmsa':
continue
try:
os.symlink('tmsa', command)
print("Created symlink for %s" % command)
except OSError as e:
if e.errno == 17:
print("Symlink for %s already created" % command)
else:
raise
def strip_priority(line):
"Removes the priority, if any, from a todo item"
return re.sub('^\([A-Z]\) ', '', line)
def undone_lines(fh):
"Internal function to return lines in a file handle not marked as done."
content = fh.readlines()
undone_lines = [l for l in content if re.match('^(?!x \d{4}-\d{2}-\d{2})',l)]
return undone_lines;
def find_unmanaged():
"Find files with unmanaged active tasks"
unmanaged = []
os.chdir(os.environ["TODO_DIR"])
now = datetime.datetime.now().replace(hour=0, minute=0, second=0,
microsecond=0)
for f in glob.glob("????-??-??.txt"):
d, e = f.split(".")
size = os.stat(f).st_size
# Find the date-based files before today that contain any non-done items
if datetime.datetime.strptime(d, "%Y-%m-%d") < now and size > 0:
with open(f) as fh:
if undone_lines(fh):
unmanaged.append(f)
return unmanaged
def bump(from_file, to_file, line_num=None):
"Bumps a task, or all if no line is provided"
auto_archive = "TODOTXT_AUTO_ARCHIVE" in os.environ and \
os.environ["TODOTXT_AUTO_ARCHIVE"] == "1"
preserve_line_numbers = "TODOTXT_PRESERVE_LINE_NUMBERS" in \
os.environ and os.environ["TODOTXT_PRESERVE_LINE_NUMBERS"] == "1"
os.chdir(os.environ["TODO_DIR"])
now = datetime.datetime.now()
today = now.strftime("%Y-%m-%d")
ifh = open(from_file) # File to bump from
ofh = open(to_file, "a") # File to bump to
tfh = open("%s.tmp" % from_file, "w") # Temporary file
if auto_archive:
dfh = open("%s-done.txt" % from_file[:-4], "a") # Done file
else:
dfh = tfh
bumped = []
for n, line in enumerate(undone_lines(ifh)):
n += 1 # 1-indexed lines
if not line_num or line_num == n:
## Bump the item
# Copy line to today's file
ofh.write(line)
# Mark as done (and bumped) in the done file
dfh.write("x %s %s bumped:%s\n" % (today,
strip_priority(line).rstrip(),
to_file[:-4]))
if auto_archive and preserve_line_numbers and line_num:
tfh.write("\n")
bumped.append(line.rstrip())
else:
# Don't bump the item
tfh.write(line)
ifh.close()
if auto_archive:
dfh.close()
ofh.close()
tfh.close()
# Now move the temp file (with the bumped entries remove) to the original
# from file
os.remove(from_file)
os.rename("%s.tmp" % from_file, from_file)
# Status message
print("\n".join(bumped))
if line_num:
print("TODO: %s bumped from %s to %s" % (line_num, from_file, to_file))
else:
print("TODO: all items bumped from %s to %s" % (from_file, to_file))
def usage(command):
if command in commands:
print(" %s" % command)
print("\n".join(" %s" % i for i in commands[command]))
if __name__ == '__main__':
action = sys.argv[1]
if action == 'usage':
prog = os.path.basename(sys.argv[0]) # Identify command
usage(prog)
sys.exit(0)
if action == 'verify':
unmanaged = find_unmanaged()
if unmanaged:
print('\n'.join(sorted(find_unmanaged())))
sys.exit(0)
if action == 'bump' or action == 'bumpall':
to_bump = None
now = datetime.datetime.now()
weekday = now.weekday()
if weekday == '5':
# Today is friday, skip to monday
days = 3
else:
days = 1
if action == 'bump':
if len(sys.argv) < 3:
usage('bump')
sys.exit(1)
try:
to_bump = int(sys.argv[2])
if len(sys.argv) == 4:
days = int(sys.argv[3])
except ValueError:
usage('bump')
sys.exit(1)
next_day = now + datetime.timedelta(days=days)
today = now.strftime("%Y-%m-%d.txt")
next_file = next_day.strftime("%Y-%m-%d.txt")
bump(today, next_file, to_bump)
sys.exit(0)
if action == 'bringforward':
now = datetime.datetime.now()
unmanaged = find_unmanaged()
today = now.strftime("%Y-%m-%d.txt")
for f in unmanaged:
bump(f, today)
sys.exit(0)
if action == 'tmsa':
make_symlinks()
sys.exit(0)