import atexit
try:
from http.client import HTTPConnection
except ImportError:
from httplib import HTTPConnection
import os
import signal
import stat
import subprocess
import sys
import tempfile
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
def GetPlatformName():
if IsWindows():
return 'win'
if IsMac():
return 'mac'
if IsLinux():
return 'linux'
raise NotImplementedError('Unknown platform "%s".' % sys.platform)
def IsWindows():
return sys.platform == 'cygwin' or sys.platform.startswith('win')
def IsLinux():
return sys.platform.startswith('linux')
def IsMac():
return sys.platform.startswith('darwin')
def _DeleteDir(path):
for root, dirs, files in os.walk(path, topdown=False):
for name in files:
filename = os.path.join(root, name)
os.chmod(filename, stat.S_IWRITE)
os.remove(filename)
for name in dirs:
os.rmdir(os.path.join(root, name))
os.rmdir(path)
def Delete(path):
if os.path.isdir(path):
_DeleteDir(path)
else:
os.remove(path)
def MaybeDelete(path):
if os.path.exists(path):
Delete(path)
def MakeTempDir(parent_dir=None):
path = tempfile.mkdtemp(dir=parent_dir)
atexit.register(MaybeDelete, path)
return path
def Unzip(zip_path, output_dir):
if IsWindows():
unzip_cmd = ['C:\\Program Files\\7-Zip\\7z.exe', 'x', '-y']
else:
unzip_cmd = ['unzip', '-o']
unzip_cmd += [zip_path]
if RunCommand(unzip_cmd, output_dir) != 0:
raise RuntimeError('Unable to unzip %s to %s' % (zip_path, output_dir))
def Kill(pid):
if IsWindows():
subprocess.call(['taskkill.exe', '/T', '/F', '/PID', str(pid)])
else:
os.kill(pid, signal.SIGTERM)
def RunCommand(cmd, cwd=None):
process = subprocess.Popen(cmd, cwd=cwd)
process.wait()
return process.returncode
def DoesUrlExist(url):
parsed = urlparse(url)
try:
conn = HTTPConnection(parsed.netloc)
conn.request('HEAD', parsed.path)
response = conn.getresponse()
except (socket.gaierror, socket.error):
return False
finally:
conn.close()
if response.status == 302 or response.status == 301:
return DoesUrlExist(response.getheader('location'))
return response.status == 200