Merge branch '8784-dir-listings'
[arvados.git] / sdk / python / arvados / commands / _util.py
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: Apache-2.0
4
5 import argparse
6 import errno
7 import os
8
9 def _pos_int(s):
10     num = int(s)
11     if num < 0:
12         raise ValueError("can't accept negative value: %s" % (num,))
13     return num
14
15 retry_opt = argparse.ArgumentParser(add_help=False)
16 retry_opt.add_argument('--retries', type=_pos_int, default=3, help="""
17 Maximum number of times to retry server requests that encounter temporary
18 failures (e.g., server down).  Default 3.""")
19
20 def _ignore_error(error):
21     return None
22
23 def _raise_error(error):
24     raise error
25
26 def make_home_conf_dir(path, mode=None, errors='ignore'):
27     # Make the directory path under the user's home directory, making parent
28     # directories as needed.
29     # If the directory is newly created, and a mode is specified, chmod it
30     # with those permissions.
31     # If there's an error, return None if errors is 'ignore', else raise an
32     # exception.
33     error_handler = _ignore_error if (errors == 'ignore') else _raise_error
34     tilde_path = os.path.join('~', path)
35     abs_path = os.path.expanduser(tilde_path)
36     if abs_path == tilde_path:
37         return error_handler(ValueError("no home directory available"))
38     try:
39         os.makedirs(abs_path)
40     except OSError as error:
41         if error.errno != errno.EEXIST:
42             return error_handler(error)
43     else:
44         if mode is not None:
45             os.chmod(abs_path, mode)
46     return abs_path