forked from jrnl-org/jrnl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.py
146 lines (131 loc) · 4.68 KB
/
util.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
#!/usr/bin/env python
# encoding: utf-8
import sys
import os
from tzlocal import get_localzone
import getpass as gp
import keyring
import pytz
try: import simplejson as json
except ImportError: import json
if "win32" in sys.platform:
import colorama
colorama.init()
import re
import tempfile
import subprocess
import codecs
PY3 = sys.version_info[0] == 3
PY2 = sys.version_info[0] == 2
STDIN = sys.stdin
STDERR = sys.stderr
STDOUT = sys.stdout
TEST = False
__cached_tz = None
def getpass(prompt="Password: "):
if not TEST:
return gp.getpass(prompt)
else:
return py23_input(prompt)
def get_password(validator, keychain=None, max_attempts=3):
pwd_from_keychain = keychain and get_keychain(keychain)
password = pwd_from_keychain or getpass()
result = validator(password)
# Password is bad:
if result is None and pwd_from_keychain:
set_keychain(keychain, None)
attempt = 1
while result is None and attempt < max_attempts:
prompt("Wrong password, try again.")
password = getpass()
result = validator(password)
attempt += 1
if result is not None:
return result
else:
prompt("Extremely wrong password.")
sys.exit(1)
def get_keychain(journal_name):
return keyring.get_password('jrnl', journal_name)
def set_keychain(journal_name, password):
if password is None:
try:
keyring.delete_password('jrnl', journal_name)
except:
pass
elif not TEST:
keyring.set_password('jrnl', journal_name, password)
def u(s):
"""Mock unicode function for python 2 and 3 compatibility."""
return s if PY3 or type(s) is unicode else unicode(s.encode('string-escape'), "unicode_escape")
def prompt(msg):
"""Prints a message to the std err stream defined in util."""
if not msg.endswith("\n"):
msg += "\n"
STDERR.write(u(msg))
def py23_input(msg=""):
STDERR.write(u(msg))
return STDIN.readline().strip()
def py23_read(msg=""):
STDERR.write(u(msg))
return STDIN.read()
def yesno(prompt, default=True):
prompt = prompt.strip() + (" [Y/n]" if default else " [y/N]")
raw = py23_input(prompt)
return {'y': True, 'n': False}.get(raw.lower(), default)
def get_local_timezone():
"""Returns the Olson identifier of the local timezone.
In a happy world, tzlocal.get_localzone would do this, but there's a bug on OS X
that prevents that right now: https://github.com/regebro/tzlocal/issues/6"""
global __cached_tz
if not __cached_tz and "darwin" in sys.platform:
__cached_tz = os.popen("systemsetup -gettimezone").read().replace("Time Zone: ", "").strip()
if not __cached_tz or __cached_tz not in pytz.all_timezones_set:
link = os.readlink("/etc/localtime")
# This is something like /usr/share/zoneinfo/America/Los_Angeles.
# Find second / from right and take the substring
__cached_tz = link[link.rfind('/', 0, link.rfind('/'))+1:]
elif not __cached_tz:
__cached_tz = str(get_localzone())
if not __cached_tz or __cached_tz not in pytz.all_timezones_set:
__cached_tz = "UTC"
return __cached_tz
def load_and_fix_json(json_path):
"""Tries to load a json object from a file.
If that fails, tries to fix common errors (no or extra , at end of the line).
"""
with open(json_path) as f:
json_str = f.read()
config = fixed = None
try:
return json.loads(json_str)
except ValueError as e:
# Attempt to fix extra ,
json_str = re.sub(r",[ \n]*}", "}", json_str)
# Attempt to fix missing ,
json_str = re.sub(r"([^{,]) *\n *(\")", r"\1,\n \2", json_str)
try:
config = json.loads(json_str)
with open(json_path, 'w') as f:
json.dump(config, f, indent=2)
prompt("[Some errors in your jrnl config have been fixed for you.]")
return config
except ValueError as e:
prompt("[There seems to be something wrong with your jrnl config at {0}: {1}]".format(json_path, e.message))
prompt("[Entry was NOT added to your journal]")
sys.exit(1)
def get_text_from_editor(config, template=""):
tmpfile = os.path.join(tempfile.gettempdir(), "jrnl")
with codecs.open(tmpfile, 'w', "utf-8") as f:
if template:
f.write(template)
subprocess.call(config['editor'].split() + [tmpfile])
with codecs.open(tmpfile, "r", "utf-8") as f:
raw = f.read()
os.remove(tmpfile)
if not raw:
prompt('[Nothing saved to file]')
return raw
def colorize(string):
"""Returns the string wrapped in cyan ANSI escape"""
return u"\033[36m{}\033[39m".format(string)