/usr/lib/python2.7/dist-packages/txclib/utils.py is in transifex-client 0.10-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | import os, sys, re, errno
import ssl
try:
from json import loads as parse_json, dumps as compile_json
except ImportError:
from simplejson import loads as parse_json, dumps as compile_json
from txclib.packages import urllib3
from txclib.urls import API_URLS
from txclib.exceptions import UnknownCommandError
from txclib.paths import posix_path, native_path, posix_sep
from txclib.web import user_agent_identifier
from txclib.log import logger
def find_dot_tx(path=os.path.curdir, previous=None):
"""Return the path where .tx folder is found.
The 'path' should be a DIRECTORY.
This process is functioning recursively from the current directory to each
one of the ancestors dirs.
"""
path = os.path.abspath(path)
if path == previous:
return None
joined = os.path.join(path, ".tx")
if os.path.isdir(joined):
return path
else:
return find_dot_tx(os.path.dirname(path), path)
#################################################
# Parse file filter expressions and create regex
def regex_from_filefilter(file_filter, root_path = os.path.curdir):
"""Create proper regex from <lang> expression."""
# Force expr to be a valid regex expr (escaped) but keep <lang> intact
expr_re = re.escape(
posix_path(os.path.join(root_path, native_path(file_filter)))
)
expr_re = expr_re.replace("\\<lang\\>", '<lang>').replace(
'<lang>', '([^%(sep)s]+)' % { 'sep': re.escape(posix_sep)})
return "^%s$" % expr_re
TX_URLS = {
'resource': '(?P<hostname>https?://(\w|\.|:|-)+)/projects/p/(?P<project>(\w|-)+)/resource/(?P<resource>(\w|-)+)/?$',
'release': '(?P<hostname>https?://(\w|\.|:|-)+)/projects/p/(?P<project>(\w|-)+)/r/(?P<release>(\w|-)+)/?$',
'project': '(?P<hostname>https?://(\w|\.|:|-)+)/projects/p/(?P<project>(\w|-)+)/?$',
}
def parse_tx_url(url):
"""
Try to match given url to any of the valid url patterns specified in
TX_URLS. If not match is found, we raise exception
"""
for type_ in TX_URLS.keys():
pattern = TX_URLS[type_]
m = re.match(pattern, url)
if m:
return type_, m.groupdict()
raise Exception(
"tx: Malformed url given. Please refer to our docs: http://bit.ly/txautor"
)
def get_details(api_call, username, password, *args, **kwargs):
"""
Get the tx project info through the API.
This function can also be used to check the existence of a project.
"""
url = (API_URLS[api_call] % (kwargs)).encode('UTF-8')
conn = urllib3.connection_from_url(kwargs['hostname'])
headers = urllib3.util.make_headers(
basic_auth='{0}:{1}'.format(username, password),
accept_encoding=True,
user_agent=user_agent_identifier(),
)
try:
r = conn.request('GET', url, headers=headers)
remote_project = parse_json(r.data)
r.close()
return remote_project
except ssl.SSLError:
logger.error("Invalid SSL certificate")
raise
except Exception, e:
logger.debug(unicode(e))
raise
def valid_slug(slug):
"""
Check if a slug contains only valid characters.
Valid chars include [-_\w]
"""
try:
a, b = slug.split('.')
except ValueError:
return False
else:
if re.match("^[A-Za-z0-9_-]*$", a) and re.match("^[A-Za-z0-9_-]*$", b):
return True
return False
def discover_commands():
"""
Inspect commands.py and find all available commands
"""
import inspect
from txclib import commands
command_table = {}
fns = inspect.getmembers(commands, inspect.isfunction)
for name, fn in fns:
if name.startswith("cmd_"):
command_table.update({
name.split("cmd_")[1]:fn
})
return command_table
def exec_command(command, *args, **kwargs):
"""
Execute given command
"""
commands = discover_commands()
try:
cmd_fn = commands[command]
except KeyError:
raise UnknownCommandError
cmd_fn(*args,**kwargs)
def mkdir_p(path):
try:
if path:
os.makedirs(path)
except OSError, exc: # Python >2.5
if exc.errno == errno.EEXIST:
pass
else:
raise
def confirm(prompt='Continue?', default=True):
"""
Prompt the user for a Yes/No answer.
Args:
prompt: The text displayed to the user ([Y/n] will be appended)
default: If the default value will be yes or no
"""
valid_yes = ['Y', 'y', 'Yes', 'yes', ]
valid_no = ['N', 'n', 'No', 'no', ]
if default:
prompt = prompt + '[Y/n]'
valid_yes.append('')
else:
prompt = prompt + '[y/N]'
valid_no.append('')
ans = raw_input(prompt)
while (ans not in valid_yes and ans not in valid_no):
ans = raw_input(prompt)
return ans in valid_yes
# Stuff for command line colored output
COLORS = [
'BLACK', 'RED', 'GREEN', 'YELLOW',
'BLUE', 'MAGENTA', 'CYAN', 'WHITE'
]
DISABLE_COLORS = False
def color_text(text, color_name, bold=False):
"""
This command can be used to colorify command line output. If the shell
doesn't support this or the --disable-colors options has been set, it just
returns the plain text.
Usage:
print "%s" % color_text("This text is red", "RED")
"""
if color_name in COLORS and not DISABLE_COLORS:
return '\033[%s;%sm%s\033[0m' % (
int(bold), COLORS.index(color_name) + 30, text)
else:
return text
def files_in_project(curpath):
"""
Iterate over the files in the project.
Return each file under ``curpath`` with its absolute name.
"""
for root, dirs, files in os.walk(curpath, followlinks=True):
for f in files:
yield os.path.abspath(os.path.join(root, f))
|