summaryrefslogtreecommitdiffstats
path: root/ipaserver/secrets/handlers/common.py
blob: a700e56ccf4b668c39055be2f00bb7b6289caede (plain)
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
69
70
71
72
73
74
75
#
# Copyright (C) 2019  IPA Project Contributors, see COPYING for license
#
"""Common helpers for handlers
"""
import argparse
import base64
import json
import shutil
import tempfile


def default_json(obj):
    """JSON encoder default handler
    """
    if isinstance(obj, (bytes, bytearray)):
        return base64.b64encode(obj).decode('ascii')
    raise TypeError(
        "Object of type {} is not JSON serializable".format(type(obj))
    )


def json_dump(data, exportfile):
    """Dump JSON to file
    """
    json.dump(
        data,
        exportfile,
        default=default_json,
        separators=(',', ':'),
        sort_keys=True
    )


def mkparser(supports_import=True, **kwargs):
    """Create default parser for handler with export / import args

    All commands support export to file or stdout. Most commands can also
    import from a file or stdin. Export and import are mutually exclusive
    options.
    """
    parser = argparse.ArgumentParser(**kwargs)

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument(
        '--export',
        help='JSON export file ("-" for stdout)',
        dest='exportfile',
        type=argparse.FileType('w')
    )
    if supports_import:
        group.add_argument(
            '--import',
            help='JSON import file ("-" for stdin)',
            dest='importfile',
            type=argparse.FileType('r')
        )

    return parser


def main(parser, export_func, import_func=None, **kwargs):
    """Common main function for handlers
    """
    args = parser.parse_args()
    if args.exportfile is not None:
        func = export_func
    else:
        func = import_func

    tmpdir = tempfile.mkdtemp()
    try:
        func(args, tmpdir, **kwargs)
    finally:
        shutil.rmtree(tmpdir)