• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2# Copyright 2020 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5"""
6This file contains curlish(), a CURL-ish method that downloads things without
7needing CURL installed.
8"""
9
10import os
11
12try:
13    from urllib2 import HTTPError, URLError, urlopen
14except ImportError:  # For Py3 compatibility
15    from urllib.error import HTTPError, URLError
16    from urllib.request import urlopen
17
18
19def curlish(download_url, output_path):
20    """Basically curl, but doesn't require the developer to have curl installed
21    locally. Returns True if succeeded at downloading file."""
22
23    if not output_path or not download_url:
24        print('need both output path and download URL to download, exiting.')
25        return False
26
27    print('downloading from "{}" to "{}"'.format(download_url, output_path))
28    script_contents = ''
29    try:
30        response = urlopen(download_url)
31        script_contents = response.read()
32    except HTTPError as e:
33        print(e.code)
34        print(e.read())
35        return False
36    except URLError as e:
37        print('Download failed. Reason: ', e.reason)
38        return False
39
40    directory = os.path.dirname(output_path)
41    if not os.path.exists(directory):
42        os.makedirs(directory)
43
44    script_file = open(output_path, 'w')
45    script_file.write(script_contents)
46    script_file.close()
47
48    return True
49