blob: 2f1d32158c0a327ce038a6469f369b10a49659fe [file] [log] [blame]
Jordan Bayles82a5b2d2020-11-09 11:00:51 -08001# 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"""
5This file contains curlish(), a CURL-ish method that downloads things without
6needing CURL installed.
7"""
8
9import os
mark a. foltz3ea21022021-10-29 11:09:28 -070010from urllib.error import HTTPError, URLError
11from urllib.request import urlopen
Jordan Bayles82a5b2d2020-11-09 11:00:51 -080012
13
14def 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. foltz3ea21022021-10-29 11:09:28 -070039 with open(output_path, 'wb') as script_file:
40 script_file.write(script_contents)
Jordan Bayles82a5b2d2020-11-09 11:00:51 -080041
42 return True