Jordan Bayles | 82a5b2d | 2020-11-09 11:00:51 -0800 | [diff] [blame] | 1 | # Copyright 2020 The Chromium Authors. All rights reserved. |
| 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | """ |
| 5 | This file contains curlish(), a CURL-ish method that downloads things without |
| 6 | needing CURL installed. |
| 7 | """ |
| 8 | |
| 9 | import os |
mark a. foltz | 3ea2102 | 2021-10-29 11:09:28 -0700 | [diff] [blame] | 10 | from urllib.error import HTTPError, URLError |
| 11 | from urllib.request import urlopen |
Jordan Bayles | 82a5b2d | 2020-11-09 11:00:51 -0800 | [diff] [blame] | 12 | |
| 13 | |
| 14 | def curlish(download_url, output_path): |
| 15 | """Basically curl, but doesn't require the developer to have curl installed |
| 16 | locally. Returns True if succeeded at downloading file.""" |
| 17 | |
| 18 | if not output_path or not download_url: |
| 19 | print('need both output path and download URL to download, exiting.') |
| 20 | return False |
| 21 | |
| 22 | print('downloading from "{}" to "{}"'.format(download_url, output_path)) |
| 23 | script_contents = '' |
| 24 | try: |
| 25 | response = urlopen(download_url) |
| 26 | script_contents = response.read() |
| 27 | except HTTPError as e: |
| 28 | print(e.code) |
| 29 | print(e.read()) |
| 30 | return False |
| 31 | except URLError as e: |
| 32 | print('Download failed. Reason: ', e.reason) |
| 33 | return False |
| 34 | |
| 35 | directory = os.path.dirname(output_path) |
| 36 | if not os.path.exists(directory): |
| 37 | os.makedirs(directory) |
| 38 | |
mark a. foltz | 3ea2102 | 2021-10-29 11:09:28 -0700 | [diff] [blame] | 39 | with open(output_path, 'wb') as script_file: |
| 40 | script_file.write(script_contents) |
Jordan Bayles | 82a5b2d | 2020-11-09 11:00:51 -0800 | [diff] [blame] | 41 | |
| 42 | return True |