blob: 55845af7e6feec092d2ce41719ecbb3636247441 [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
Mike Frysinger64477332023-08-21 21:20:32 -040021
Jason Changf9aacd42023-08-03 14:38:00 -070022from error import RepoExitError
23
24
25class FetchFileError(RepoExitError):
26 """Exit error when fetch_file fails."""
Matt Story11b30b92021-10-26 10:56:13 -040027
Jack Neusc474c9c2021-07-26 23:08:54 +000028
Jack Neus19883852021-10-25 22:38:44 +000029def fetch_file(url, verbose=False):
Gavin Makea2e3302023-03-11 06:46:20 +000030 """Fetch a file from the specified source using the appropriate protocol.
Jack Neusc474c9c2021-07-26 23:08:54 +000031
Gavin Makea2e3302023-03-11 06:46:20 +000032 Returns:
33 The contents of the file as bytes.
34 """
35 scheme = urlparse(url).scheme
36 if scheme == "gs":
37 cmd = ["gsutil", "cat", url]
Jason Changf9aacd42023-08-03 14:38:00 -070038 errors = []
Gavin Makea2e3302023-03-11 06:46:20 +000039 try:
40 result = subprocess.run(
41 cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True
42 )
43 if result.stderr and verbose:
44 print(
45 'warning: non-fatal error running "gsutil": %s'
46 % result.stderr,
47 file=sys.stderr,
48 )
49 return result.stdout
50 except subprocess.CalledProcessError as e:
Jason Changf9aacd42023-08-03 14:38:00 -070051 errors.append(e)
Gavin Makea2e3302023-03-11 06:46:20 +000052 print(
53 'fatal: error running "gsutil": %s' % e.stderr, file=sys.stderr
54 )
Jason Changf9aacd42023-08-03 14:38:00 -070055 raise FetchFileError(aggregate_errors=errors)
Gavin Makea2e3302023-03-11 06:46:20 +000056 with urlopen(url) as f:
57 return f.read()