-
Notifications
You must be signed in to change notification settings - Fork 18
/
_internal.py
74 lines (55 loc) · 1.79 KB
/
_internal.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
from __future__ import print_function, unicode_literals
import errno
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
from contextlib import contextmanager
if sys.platform.startswith("linux"):
sys.platform = "linux"
# From https://stackoverflow.com/a/19445241/262432
if sys.platform in ["cygwin", "win32"]:
_bltn_open = tarfile.bltn_open
def safe_path(path):
if not os.path.isabs(path):
path = os.path.join(os.getcwd(), path)
# http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx#maxpath
if len(path) >= 200:
path = "\\\\?\\" + os.path.normpath(path)
return path
def long_bltn_open(name, *args, **kwargs):
return _bltn_open(safe_path(name), *args, **kwargs)
tarfile.bltn_open = long_bltn_open
@contextmanager
def cd(path):
cwd = os.getcwd()
os.chdir(path)
print("cd " + path)
try:
yield path
finally:
os.chdir(cwd)
def sed_inplace(path, pattern, sub, regex=False):
"""Replaces all occurences of ``pattern`` in a file with ``sub``.
A file is modified **in-place**.
"""
print("s/{}/{}/ in file {}".format(pattern, sub, path))
with open(path, "r") as input:
with tempfile.NamedTemporaryFile("w", delete=False) as output:
for line in input:
output.write(line.replace(pattern, sub) if not regex else
re.sub(pattern, sub, line))
shutil.copyfile(output.name, path)
def run(command, **kwargs):
print(command)
return subprocess.check_call(command, shell=True, **kwargs)
def maybe_makedirs(path):
print("mkdir -p " + path)
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise