blob: d79f9479ca6153affaa0f8b4675e3937071f8752 [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
20
Jack Neus19883852021-10-25 22:38:44 +000021def fetch_file(url, verbose=False):
Jack Neusc474c9c2021-07-26 23:08:54 +000022 """Fetch a file from the specified source using the appropriate protocol.
23
24 Returns:
25 The contents of the file as bytes.
26 """
27 scheme = urlparse(url).scheme
28 if scheme == 'gs':
29 cmd = ['gsutil', 'cat', url]
30 try:
31 result = subprocess.run(
Jack Neus19883852021-10-25 22:38:44 +000032 cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
33 check=True)
34 if result.stderr and verbose:
35 print('warning: non-fatal error running "gsutil": %s' % result.stderr,
36 file=sys.stderr)
Jack Neusc474c9c2021-07-26 23:08:54 +000037 return result.stdout
38 except subprocess.CalledProcessError as e:
Jack Neus19883852021-10-25 22:38:44 +000039 print('fatal: error running "gsutil": %s' % e.stderr,
Jack Neusc474c9c2021-07-26 23:08:54 +000040 file=sys.stderr)
41 sys.exit(1)
Jack Neus7a1e7e72021-09-23 13:59:58 +000042 if scheme == 'file':
43 with open(url[len('file://'):], 'rb') as f:
44 return f.read()
Jack Neusc474c9c2021-07-26 23:08:54 +000045 raise ValueError('unsupported url %s' % url)