-
Notifications
You must be signed in to change notification settings - Fork 3
/
addTask.py
executable file
·238 lines (229 loc) · 9.63 KB
/
addTask.py
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
#!/usr/bin/python
import sys, datetime, os, subprocess, io
sys.path.append('database/')
sys.path.append('logic/')
import DiaryDatabaseWrapper, newTag, newAuthor, commonDiaryFunctions
def addTask(argv):
"""
Generate a new task file.
"""
taskTitle, tagListString, templateFilename, authorInitialsList, \
year, month, day = validateInputsAndSetDefaults(argv)
taskDir = createFolders(year, month, day)
taskFilename = createTaskFilename(year, month, day, taskDir, \
authorInitialsList)
createFile(taskDir,taskFilename,taskTitle, tagListString, templateFilename, \
authorInitialsList)
openTask(taskDir + '/' + taskFilename)
# Input validation
def validateInputsAndSetDefaults(argv):
"""
Validate the provided input and set the defaults values for
the optional parameters if not specified or empty.
"""
nInputs = len(argv)
# Validate that 2 to 5 input variables are given
if nInputs<2 or nInputs>5:
print("Error: You must specify 2 to 5 input parameters.")
print("addTask.py \"tagA tagB\" \"Task Title\" authorInitials " + \
"template YYYY-MM-DD")
sys.exit(2)
tagListString = argv[0]
taskTitle = argv[1]
# Validate the tag
# The provided tag(s) must be compared to the tag database. If not
# found, it must be generated by calling the newTag function.
tagListString = checkTags(tagListString)[0]
# Set or validate author initials
if nInputs<3 or not argv[2]:
authorInitialsList = ""
else:
# The provided author initials must be compared to the author database.
# If not found, it must be generated by calling the newAuthor function.
authorInitialsList = checkAuthors(argv[2])
# Set or validate the template
if nInputs<4 or not argv[3]:
templateFilename = 'default.tpl.tex'
else:
templateFilename = argv[3] + '.tpl.tex'
templateDir = \
commonDiaryFunctions.unicodeDir(os.path.abspath(__file__)) + \
'/templates'
if not os.path.isfile(templateDir + '/' + templateFilename):
print("Error: The specified template file does not exist in " + \
"the template folder. Please create it.")
# Set or validate the date
if nInputs<5 or not argv[4]:
now = datetime.datetime.now()
year = commonDiaryFunctions.unicodeStr(now.year)
month = commonDiaryFunctions.unicodeStr(now.month).zfill(2)
day = commonDiaryFunctions.unicodeStr(now.day).zfill(2)
else:
try:
datetime.datetime.strptime(argv[4], '%Y-%m-%d')
except ValueError:
raise ValueError("Incorrect date or date format." + \
"Should be YYYY-MM-DD")
year, month, day = argv[4].split('-')
return taskTitle, tagListString, templateFilename, authorInitialsList, \
year, month, day
# See if the provided tags are in the diary database
def checkTags(tagListString):
"""
See if the provided tags are in the diary database.
"""
# Create a diary database object.
db = DiaryDatabaseWrapper.DiaryDatabaseWrapper()
# Create a list of the tags
tagList = tagListString.split(',')
newTagList = list()
for tag in tagList:
# Remove leading and trailing spaces
tag = tag.strip()
# If an empty tag has been provided, ignore it
if tag == '':
print("An empty tag has been provided and is ignored.")
else:
# Is the tag in the database
tagRows = db.selectFromTable('tags',('name',),\
'WHERE name=\'' + tag + '\'')
if len(tagRows)==0:
# Ask the user to add it
print("The tag '%s' does not exist in the diary database." % tag)
sys.stdout.write("Do you want to add it (Y/n)? ")
choice = commonDiaryFunctions.getUserInput().lower()
if choice in ('','y','yes'):
tagTitle = ''
sys.stdout.write("Please provide a tag title: ")
while tagTitle=='':
tagTitle = commonDiaryFunctions.getUserInput()
newTag.addTag2database((tag,tagTitle))
newTagList.append(tag)
else:
print("Ignoring the tag '%s'." % tag)
else:
newTagList.append(tag)
db.close()
if len(newTagList)==0:
print("No valid tags have been provided. Aborting.")
sys.exit(2)
return ','.join(newTagList), newTagList
# See if the provided authors are in the author database
def checkAuthors(authorInitialsListString):
"""
See if the provided authors are in the diary database.
"""
# Create a diary database object.
db = DiaryDatabaseWrapper.DiaryDatabaseWrapper()
# Create a list of the tags
authorInitialsList = authorInitialsListString.split(',')
newAuthorInitialsList = list()
for authorInitials in authorInitialsList:
# Remove leading and trailing spaces
authorInitials = authorInitials.strip()
# If an empty author has been provided, ignore it
if authorInitials == '':
print("An empty author initials string has been provided "\
"and is ignored.")
else:
# Is the author in the database
authorInitialsRows = db.selectFromTable('authors',('initials',),\
'WHERE initials=\'' + authorInitials + '\'')
if len(authorInitialsRows)==0:
# Ask the user to add it
print("The author initials '%s' does not exist in the diary "\
"database." % authorInitials)
sys.stdout.write("Do you want to add it (Y/n)? ")
choice = commonDiaryFunctions.getUserInput().lower()
if choice in ('','y','yes'):
authorName = ''
sys.stdout.write("Please provide a name: ")
while authorName=='':
authorName = commonDiaryFunctions.getUserInput()
authorEmail = ''
sys.stdout.write("Please provide an email address: ")
while authorEmail=='':
authorEmail = commonDiaryFunctions.getUserInput()
newAuthor.addAuthor2database((authorInitials,\
authorName,authorEmail))
newAuthorInitialsList.append(authorInitials)
else:
print("Ignoring the author initials '%s'." % authorInitials)
else:
newAuthorInitialsList.append(authorInitials)
db.close()
if len(authorInitialsList)==0:
print("No valid author initials have been provided. Aborting.")
sys.exit(2)
return authorInitialsList
# Create folders if needed
def createFolders(year, month, day):
"""
Create the year, month, and day folders if needed.
"""
entriesDir = \
commonDiaryFunctions.unicodeDir(os.path.abspath(__file__)) + '/entries'
if not os.path.isdir(entriesDir + '/' + year):
os.makedirs(entriesDir + '/' + year)
if not os.path.isdir(entriesDir + '/' + year + '/' + month):
os.makedirs(entriesDir + '/' + year + '/' + month)
if not os.path.isdir(entriesDir + '/' + year + '/' + month + '/' + day):
os.makedirs(entriesDir + '/' + year + '/' + month + '/' + day)
return entriesDir + '/' + year + '/' + month + '/' + day
# Create the file name
def createTaskFilename(year, month, day, taskDir, authorInitialsList):
"""
Create the file name for the current task.
"""
taskIndex = 0
if len(authorInitialsList) > 0:
baseFilename = year + month + day + '_' + authorInitialsList[0]
else:
baseFilename = year + month + day + '_'
taskFilename = baseFilename + str(taskIndex) + '.tex'
while os.path.isfile(taskDir + '/' + taskFilename):
taskIndex = taskIndex+1
taskFilename = baseFilename + str(taskIndex) + '.tex'
return taskFilename
# Create the file containing the task
def createFile(taskDir,taskFilename,taskTitle, tagListString, templateFilename, \
authorInitialsList):
"""
Create the task file from the provided template.
"""
templatePath = commonDiaryFunctions.unicodeDir(os.path.abspath(__file__)) \
+ '/templates/' + templateFilename
taskPath = taskDir + '/' + taskFilename
# Set the task title, the tags, and possibly also the author
templateFile = io.open(templatePath, 'r', encoding='utf-8')
taskFile = io.open(taskPath,'w', encoding='utf-8')
for line in templateFile:
# the task title
line = line.replace('@taskTitle',taskTitle)
# the task label
root,ext = os.path.splitext(taskFilename)
line = line.replace('@label', root)
# the tags
line = line.replace('@tags', tagListString)
# If not empty, also set the author initials
if authorInitialsList:
line = line.replace('%\\authors{}', \
'\\authors{'+ ','.join(authorInitialsList) +'}')
taskFile.write(line)
templateFile.close()
taskFile.close()
# Open the task in the default latex editor
def openTask(taskPath):
"""
Open the task in the default latex editor.
"""
if sys.platform.startswith('darwin'):
subprocess.call(('open', taskPath))
elif os.name == 'nt':
os.startfile(taskPath)
elif os.name == 'posix':
subprocess.call(('xdg-open', taskPath))
if __name__ == '__main__':
unicodedInputList = \
commonDiaryFunctions.convertTerminalInputs2Unicode(sys.argv[1:])
addTask(unicodedInputList)