blob: 31f8152f91c42e4d7b2fbc293974a72f93cdc4d2 [file] [log] [blame]
Jack Neusc474c9c2021-07-26 23:08:54 +00001# Copyright (C) 2021 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""This module contains functions used to fetch files from various sources."""
16
17import subprocess
18import sys
19from urllib.parse import urlparse
Matt Story11b30b92021-10-26 10:56:13 -040020from urllib.request import urlopen
21
Jack Neusc474c9c2021-07-26 23:08:54 +000022
Jack Neus19883852021-10-25 22:38:44 +000023def fetch_file(url, verbose=False):
Gavin Makea2e3302023-03-11 06:46:20 +000024 """Fetch a file from the specified source using the appropriate protocol.
Jack Neusc474c9c2021-07-26 23:08:54 +000025
Gavin Makea2e3302023-03-11 06:46:20 +000026 Returns:
27 The contents of the file as bytes.
28 """
29 scheme = urlparse(url).scheme
30 if scheme == "gs":
31 cmd = ["gsutil", "cat", url]
32 try:
33 result = subprocess.run(
34 cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True
35 )
36 if result.stderr and verbose:
37 print(
38 'warning: non-fatal error running "gsutil": %s'
39 % result.stderr,
40 file=sys.stderr,
41 )
42 return result.stdout
43 except subprocess.CalledProcessError as e:
44 print(
45 'fatal: error running "gsutil": %s' % e.stderr, file=sys.stderr
46 )
47 sys.exit(1)
48 with urlopen(url) as f:
49 return f.read()