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