File: compat.py

package info (click to toggle)
argparse-manpage 4.7-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 568 kB
  • sloc: python: 2,772; makefile: 47; sh: 18
file content (68 lines) | stat: -rw-r--r-- 2,119 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""
Compatibility hacks for the argparse-manpage project.
"""

import os
import sys
import time

import datetime
try:
    import datetime.timezone
    _TZ_ARGS = [datetime.timezone.utc]
except ImportError:
    _TZ_ARGS = []


# Drop once Python 2.7 is dropped
# pylint: disable=unused-import
try:
    from configparser import ConfigParser, NoSectionError
except ImportError:
    from ConfigParser import SafeConfigParser as ConfigParser, NoSectionError  # type: ignore

if sys.version_info < (3, 0):
    import imp  # pylint: disable=deprecated-module
    def load_py_file(filename):
        """ Small wrapper having the same call arg list as runpy.run_path() """
        return imp.load_source("argparse_manpage_loaded_file", filename)
else:
    from runpy import run_path as load_py_file

def get_module_object(module_or_dict, objname, objtype):
    """
    Get OBJNAME from a given MODULE (or dict, if loaded using runpy.run_path(),
    but call the object first if OBJTYPE is 'function'.
    """
    obj = None
    if isinstance(module_or_dict, dict):
        obj = module_or_dict[objname]
    else:
        obj = getattr(module_or_dict, objname)
    if objtype != 'object':
        obj = obj()
    return obj


def load_file_as_module(filename):
    """
    Load a given python filename as a dict (runpy on Python 3) or as a module
    (imp module, Python 2).  Note that 'runpy.run_path()' doesn't work correctly
    with Python 2.7 (the imported object doesn't see it's own globals/imported
    modules), and 'imp' module is deprecated for modern Python 3.
    """

    # We used to call 'runpy.run_path()' here, but that did not work correctly
    # with Python 2.7 where the imported object did not see it's own
    # globals/imported modules (including the 'argparse' module).
    return load_py_file(filename)


def get_reproducible_date():
    """
    Return current datetime string, but respect SOURCE_DATE_EPOCH environment
    variable if specified.
    """
    return datetime.datetime.fromtimestamp(
        int(os.environ.get('SOURCE_DATE_EPOCH', time.time())),
        *_TZ_ARGS).strftime('%Y-%m-%d')