-
Notifications
You must be signed in to change notification settings - Fork 6
/
utils.py
415 lines (366 loc) · 13.5 KB
/
utils.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
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import os, sys
from ltk.locales import default_locales, locale_list
from ltk.logger import logger
import time
import logging
import traceback
from ltk import exceptions
try:
from blessings import Terminal
term = Terminal()
except ImportError:
term = False
# from constants import APP_ID
class Enum(set):
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
# def get_access_token(host, username, password):
# auth_uri = host + '/auth/authorize.html'
# auth_params = {'client_id': APP_ID, 'redirect_uri': '', 'response_type': 'token'}
# todo possibly put dictionary outside so not built with every function call
def detect_format(file_name, get_mapper=False):
format_mapper = {
'.csv': 'CSV',
'.dita': 'DITA',
'.ditamap': 'DITAMAP',
'.docx': 'DOCX_OKAPI',
'.doc' : 'WORD_OKAPI',
'.dtd': 'DTD',
'.xlsx': 'XLSX_OKAPI',
'.idml': 'IDML',
'.properties': 'JAVA_PROPERTIES_OKAPI',
'.json': 'JSON',
'.pdf': 'PDF',
'.txt': 'PLAINTEXT_OKAPI',
'.po': 'PO',
'.ppt': 'PPT_OKAPI',
'.pptx': 'PPTX_OKAPI',
'.resx': 'RESX',
'.regex': 'REGEX',
'.rtf': 'RTF_OKAPI',
'.srt': 'SUBTITLE_RIP',
'.strings': 'APPLE_STRINGS',
'.tsv': 'TABLE', # catkeys?
'.ts': 'TS',
'.xml': 'XML_OKAPI'
}
format_mapper.update(dict.fromkeys(['.dox', '.c', '.h', '.cpp'], 'DOXYGEN'))
format_mapper.update(dict.fromkeys(['.html', '.htm'], 'HTML_OKAPI'))
format_mapper.update(dict.fromkeys(['.odp', '.otp'], 'ODP'))
format_mapper.update(dict.fromkeys(['.ods', '.ots'], 'ODS'))
format_mapper.update(dict.fromkeys(['.odt', '.ott'], 'ODT'))
format_mapper.update(dict.fromkeys(['.yaml', '.yml'], 'RAILS_YAML'))
format_mapper.update(dict.fromkeys(['.xliff', '.xlf'], 'XLIFF_OKAPI'))
if get_mapper:
return format_mapper
name, extension = os.path.splitext(file_name)
return format_mapper.get(extension.lower(), 'PLAINTEXT_OKAPI')
def map_locale(locale):
"""
maps incorrectly formatted locales to valid locales for use with Lingotek API
:param locale: incorrectly formatted locale
:return: valid locale
"""
# import json
# valid_locales = []
# unsupported_locales = []
# with open('data/language-default-locales.json') as json_file:
# default_locales = json.load(json_file)
try:
return default_locales[locale]
except KeyError:
return None
# for locale in locales:
# try:
# valid_locales.append(default_locales[locale])
# except KeyError:
# unsupported_locales.append(locale)
# return valid_locales, unsupported_locales
def restart(message="Restarting watch", interval=5):
"""Restarts the program. Used after exceptions. Otherwise, watch doesn't work anymore."""
time.sleep(interval)
print(message)
cmd = "ltk"
for arg in sys.argv[1:]:
cmd = cmd + " " + arg
os.system(cmd)
''' This way (below) works for Linux, but does not work on Windows '''
#python = sys.executable
#os.execl(python, python, * sys.argv)
def is_valid_locale(api, locale):
"""Returns true if the locale is found in Lingotek's remote list of locales or, if the api call fails, if the locale is found in the local list of locales."""
valid_locales = []
response = api.list_locales()
remote_check = False
if response.status_code == 200:
remote_check = True
locale_json = response.json()
for entry in locale_json:
valid_locales.append(locale_json[entry]['locale'])
locales = []
check_locale = locale.replace("-","_")
if remote_check and check_locale not in valid_locales or not remote_check and not check_locale in locale_list:
return False
else:
return True
def get_valid_locales(api, entered_locales, operation_text):
"""Return the list of valid locales, checking locales either remotely or using a local list of locales."""
valid_locales = []
response = api.list_locales()
remote_check = False
if response.status_code == 200:
remote_check = True
locale_json = response.json()
for entry in locale_json:
valid_locales.append(locale_json[entry]['locale'])
locales = []
if(len(entered_locales) == 0 or (len(entered_locales) == 1 and entered_locales[0] == "[]")):
logger.warning('No locales have been assigned to this document. Please add them using \'ltk request\'.')
else:
for locale in entered_locales:
check_locale = locale.replace("-","_")
if remote_check and check_locale not in valid_locales or not remote_check and not check_locale in locale_list:
logger.warning('The locale code "'+str(locale)+'" failed to be '+operation_text+' since it is invalid (see "ltk list -l" for the list of valid codes).')
else:
locales.append(locale)
return locales
def get_translation_files(file_name, path, download_option, doc_manager):
translation_files = []
if download_option == "same":
downloads = doc_manager.get_doc_downloads(file_name)
translation_files = find_translations(file_name, path, downloads)
elif download_option == "folder" :
downloads = doc_manager.get_doc_downloads(file_name)
entry = doc_manager.get_doc_by_prop("file_name", file_name)
if entry:
file_name = entry['name']
translation_files = find_translations(file_name, path, downloads)
elif download_option == "clone":
entry = doc_manager.get_doc_by_prop("file_name", file_name)
if entry:
file_name = entry['name']
if os.path.isfile(os.path.join(path, file_name)):
translation_files.append(os.path.join(path, file_name))
return translation_files
def find_translations(file_name, path, downloads):
translation_files = []
trans_file_name = ""
for d in downloads:
temp = file_name.split(".")
trans_file_name = ""
for idx, val in enumerate(temp):
if idx == len(temp)-2:
trans_file_name = trans_file_name +val+"."
trans_file_name = trans_file_name+d+"."
else:
trans_file_name += val
if idx != len(temp)-1:
trans_file_name += "."
if os.path.isfile(os.path.join(path, trans_file_name)):
translation_files.append(os.path.join(path, trans_file_name))
return translation_files
def raise_error(json, error_message, is_warning=False, doc_id=None, file_name=None):
try:
error = ""
if json:
error = json['messages'][0]
if file_name:
file_name = file_name.replace("Status of ", "")
if file_name is not None and doc_id is not None:
error = error.replace(doc_id, file_name+" ("+doc_id+")")
# Sometimes api returns vague errors like 'Unknown error'
if error == 'Unknown error':
error = error_message
if not is_warning:
raise exceptions.RequestFailedError(error)
# warnings.warn(error)
if error:
error = error+"\n"
logger.error(error+error_message)
except (AttributeError, IndexError):
if not is_warning:
raise exceptions.RequestFailedError(error_message)
# warnings.warn(error_message)
logger.error(error_message)
def error(error_message):
logger.error(error_message+"\n")
def underline(text):
if term:
print(term.underline(text))
else:
# print("Recommended to install blessings module for better formatting")
print(text)
def format_commit_message():
pass
def check_response(response):
try:
if response and response.text:
if response.json():
return True
except ValueError:
logger.warning("Could not connect to Lingotek")
return
# Python 3
# except json.decoder.JSONDecodeError:
# logger.warning("Could not connect to Lingotek")
# return
# End Python 3
def remove_begin_slashes(path):
index = 0
for letter in path:
if letter != os.sep:
break
index += 1
if len(path) > index + 1:
return path[index:]
else:
return ''
return path
def remove_end_slashes(path):
index = len(path) - 1
for letter in reversed(path):
if letter != os.sep:
break
index -= 1
if index > 0:
return path[:index - 1]
else:
return ''
return path
def remove_last_folder_in_path(path):
if len(path):
split_path = path.split(os.sep)
split_path = split_path[:len(split_path) - 1]
return os.path.join(*split_path)
else:
return path
# Takes a path normalized relative to the project root (path) and returns the path relative to the current directory.
def get_relative_path(path_to_project_root, path):
abs_path = os.path.dirname(os.path.join(path_to_project_root,path))
# print("abs_path: "+abs_path)
relative_path = os.path.relpath(abs_path,os.getcwd())
# print("relative path: "+relative_path)
if relative_path == '..' and os.path.join(path_to_project_root,path) == os.getcwd():
return '.'
relative_file_path = os.path.join(relative_path,os.path.basename(path))
split_path = relative_file_path.split(os.sep)
# print("cwd: "+os.getcwd())
# print("joined path: "+os.path.join(abs_path,os.path.basename(path)))
if len(split_path) and split_path[0] == '.' or os.path.join(abs_path,os.path.basename(path)) in os.getcwd():
relative_file_path = os.path.join(*split_path[1:])
return relative_file_path
def log_traceback(ex, ex_traceback=None):
# Python 2
try:
exc_type, exc_value, exc_traceback = sys.exc_info()
tb_str = ""
tb_lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
for line in tb_lines:
tb_str += line+"\n"
finally:
"""Assigning the traceback return value to a local variable in a function that is handling an exception will cause a circular reference,
preventing anything referenced by a local variable in the same function or by the traceback from being garbage collected.
Must explicitly delete. """
del exc_traceback
return tb_str
# End Python 2
# Python 3
# if ex_traceback is None:
# ex_traceback = ex.__traceback__
# tb_str = ""
# tb_lines = traceback.format_exception(ex.__class__, ex, ex_traceback)
# for line in tb_lines:
# tb_str += line+"\n"
# return tb_str
# End Python 3
def log_error(error_file_name, e):
try:
with open(error_file_name, 'a') as error_file:
error_file.write(str(time.strftime("%Y-%m-%d %H:%M:%S") + ": "+str(log_traceback(e))))
except IOError as e:
print(e.errno)
print(e)
return
def remove_powershell_formatting(args):
if args != None:
if isinstance(args, tuple):
myTuple = ()
if len(args) > 1:
if isinstance(args, tuple):
for k in args:
k = remove_formatting(k)
myTuple = myTuple+(k,)
return myTuple
else:
for k,v in args:
k = (remove_formatting(k),)
v = remove_formatting(v)
tup1 = k+(v,)
return myTuple+(tup1,)
return myTuple+(tup1,)
else:
for tup in args:
if isinstance(tup, tuple):
for k in tup:
k = remove_formatting(k)
myTuple = myTuple+(k,)
myTuple = (myTuple),
return myTuple
else:
for k in args:
k = remove_formatting(k)
myTuple = (k,)
return myTuple
return args
elif isinstance(args, list):
temp = []
for k in args:
k = remove_formatting(k)
temp.append(k)
return tuple(temp)
elif isinstance(args, str):
temp = remove_formatting(args)
return temp
# Python 2
elif isinstance(args, bool):
return args
# End Python 2
else:
# Python 2
temp = remove_formatting(args)
return temp
# End Python 2
# Python 3
# return args
# End Python 3
def remove_formatting(f):
if f.startswith(".\\"):
f = f[2:]
if f.endswith("\\"):
f = f[:-1]
if f.endswith("\""):
f = f[:-1]
return f
else:
return f
def yes_no_prompt(prompt, default_yes=False):
try:
confirm = 'none'
prompt_message = prompt + (" [Y/n]: " if default_yes else " [y/N]: ")
while confirm not in ['y', 'Y', 'n', 'N', '']:
# Python 2
confirm = raw_input(prompt_message)
# End Python 2
# Python 3
# confirm = input(prompt_message)
# End Python 3
if confirm in ['y', 'Y']:
return True
elif confirm in ['n', 'N']:
return False
else:
return default_yes
except KeyboardInterrupt:
raise