diff --git a/scripts/get-platformio.py b/scripts/get-platformio.py index 988f6054..192421b1 100644 --- a/scripts/get-platformio.py +++ b/scripts/get-platformio.py @@ -12,173 +12,94 @@ # See the License for the specific language governing permissions and # limitations under the License. -import os -import subprocess -import site +import tempfile +import io import sys -from platform import system -from tempfile import NamedTemporaryFile +import subprocess -CURINTERPRETER_PATH = os.path.normpath(sys.executable) -IS_WINDOWS = system().lower() == "windows" +NEW_SCRIPT_URL = "https://raw.githubusercontent.com/platformio/platformio-core-installer/develop/get-platformio.py" -def fix_winpython_pathenv(): - """ - Add Python & Python Scripts to the search path on Windows - """ - try: - import _winreg as winreg - except ImportError: - import winreg +def download_with_requests(url, dst): + import requests - # took these lines from the native "win_add2path.py" - pythonpath = os.path.dirname(os.path.normpath(sys.executable)) - scripts = os.path.join(pythonpath, "Scripts") - appdata = os.environ["APPDATA"] - if hasattr(site, "USER_SITE"): - userpath = site.USER_SITE.replace(appdata, "%APPDATA%") - userscripts = os.path.join(userpath, "Scripts") - else: - userscripts = None - - with winreg.CreateKey(winreg.HKEY_CURRENT_USER, "Environment") as key: - try: - envpath = winreg.QueryValueEx(key, "PATH")[0] - except WindowsError: - envpath = u"%PATH%" - - paths = [envpath] - for path in (pythonpath, scripts, userscripts): - if path and path not in envpath and os.path.isdir(path): - paths.append(path) - - envpath = os.pathsep.join(paths) - winreg.SetValueEx(key, "PATH", 0, winreg.REG_EXPAND_SZ, envpath) - return True + resp = requests.get(url, stream=True) + itercontent = resp.iter_content(chunk_size=io.DEFAULT_BUFFER_SIZE) + with open(dst, "wb") as fp: + for chunk in itercontent: + fp.write(chunk) + return dst -def exec_command(*args, **kwargs): - result = {"out": None, "err": None, "returncode": None} +def download_with_urllib3(url, dst): + import urllib3 + http = urllib3.PoolManager() + r = http.request('GET', url, preload_content=False) - kwargs['stdout'] = subprocess.PIPE - kwargs['stderr'] = subprocess.PIPE - kwargs['shell'] = IS_WINDOWS + with open(dst, 'wb') as out: + while True: + data = r.read(io.DEFAULT_BUFFER_SIZE) + if not data: + break + out.write(data) - p = subprocess.Popen(*args, **kwargs) - result['out'], result['err'] = p.communicate() - result['returncode'] = p.returncode - - for k, v in result.items(): - if v and isinstance(v, str): - result[k].strip() - - return result + r.release_conn() + return dst -def print_exec_result(result): - if result['returncode'] == 0: - print(result['out']) - else: - raise Exception("\n".join([result['out'], result['err']])) - - -def exec_python_cmd(args): - return exec_command([CURINTERPRETER_PATH] + args) - - -def install_pip(): - r = exec_python_cmd(["-m", "pip", "--version"]) - if r['returncode'] == 0: - print(r['out']) - return - try: - from urllib2 import urlopen - except ImportError: +def download_with_urllib(url, dst): + if sys.version_info[0] == 3: from urllib.request import urlopen + else: + from urllib import urlopen - f = NamedTemporaryFile(delete=False) - response = urlopen("https://bootstrap.pypa.io/get-pip.py") - f.write(response.read()) - f.close() + response = urlopen(url) + CHUNK = 16 * 1024 + with open(dst, 'wb') as f: + while True: + chunk = response.read(CHUNK) + if not chunk: + break + f.write(chunk) - try: - r = exec_python_cmd([f.name]) - finally: - os.unlink(f.name) - - print_exec_result(r) + return dst -def install_platformio(): - r = None - cmd = ["-m", "pip", "install", "-U", "platformio"] - # cmd = [ - # "-m", "pip", "install", "-U", - # "https://github.com/platformio/platformio-core/archive/develop.zip" - # ] - try: - r = exec_python_cmd(cmd) - assert r['returncode'] == 0 - except AssertionError: - cmd.insert(2, "--no-cache-dir") - r = exec_python_cmd(cmd) - if r: - print_exec_result(r) +def download_with_curl(url, dst): + subprocess.check_output(["curl", "-o", dst, url]) + return dst + + +def download_with_wget(url, dst): + subprocess.check_output(["wget", "-O", dst, url]) + return dst + + +def download_file(url, dst): + methods = [ + download_with_requests, + download_with_urllib3, + download_with_urllib, + download_with_curl, + download_with_wget + ] + for method in methods: + try: + method(url, dst) + return dst + except: + pass + raise Exception("Could not download file '%s' to '%s' "%(url, dst)) def main(): - steps = [("Fixing Windows %PATH% Environment", fix_winpython_pathenv), - ("Installing Python Package Manager", install_pip), - ("Installing PlatformIO and dependencies", install_platformio)] - - if not IS_WINDOWS: - del steps[0] - - is_error = False - for s in steps: - if is_error: - break - print("\n==> %s ..." % s[0]) - try: - s[1]() - print("[SUCCESS]") - except Exception as e: - is_error = True - print(str(e)) - print("[FAILURE]") - - permission_errors = ("permission denied", "not permitted") - if (any([m in str(e).lower() for m in permission_errors]) and - not IS_WINDOWS): - print(""" ------------------ -Permission denied ------------------ - -You need the `sudo` permission to install Python packages. Try - -$ sudo python -c "$(curl -fsSL -https://raw.githubusercontent.com/platformio/platformio/develop/scripts/get-platformio.py)" -""") - - if is_error: - print("The installation process has been FAILED!\n" - "Please report about this problem here\n" - "< https://github.com/platformio/platformio-core/issues >") - return - else: - print("\n ==> Installation process has been " - "successfully FINISHED! <==\n") - print(""" - ----------------------------------------- -Please RESTART your Terminal Application ----------------------------------------- - -Then run `platformio --help` command. - -""") + print("This installer script is deprecated and will be removed in the next release. Please use %s" % + NEW_SCRIPT_URL) + with tempfile.NamedTemporaryFile() as tmp_file: + dst = download_file(NEW_SCRIPT_URL, str(tmp_file.name)) + command = [sys.executable, dst] + command.extend(sys.argv[1:]) + subprocess.check_call(command) if __name__ == "__main__":