xref: /OpenGrok/tools/src/main/python/opengrok_tools/utils/readconfig.py (revision d1fb7b405c9e3fa3b7f967514a630badfae8f85a)
1#
2# CDDL HEADER START
3#
4# The contents of this file are subject to the terms of the
5# Common Development and Distribution License (the "License").
6# You may not use this file except in compliance with the License.
7#
8# See LICENSE.txt included in this distribution for the specific
9# language governing permissions and limitations under the License.
10#
11# When distributing Covered Code, include this CDDL HEADER in each
12# file and include the License file at LICENSE.txt.
13# If applicable, add the following below this CDDL HEADER, with the
14# fields enclosed by brackets "[]" replaced with your own identifying
15# information: Portions Copyright [yyyy] [name of copyright owner]
16#
17# CDDL HEADER END
18#
19
20#
21# Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved.
22#
23
24import logging
25import json
26import yaml
27import sys
28
29# The following is to make the JSON parsing work on Python 3.4.
30try:
31    from json.decoder import JSONDecodeError
32except ImportError:
33    JSONDecodeError = ValueError
34
35
36def read_config(logger, input_file):
37    """
38    Try to interpret input_file as either JSON or YAML file,
39    parse it and return an object representing its contents.
40
41    If neither is valid, return None.
42    """
43    logging.debug("reading in {}".format(input_file))
44    cfg = None
45    try:
46        with open(input_file) as data_file:
47            data = data_file.read()
48
49            try:
50                logger.debug("trying JSON")
51                cfg = json.loads(data)
52            except JSONDecodeError:
53                # Not a valid JSON file.
54                logger.debug("got exception {}".format(sys.exc_info()[0]))
55            else:
56                return cfg
57
58            try:
59                logger.debug("trying YAML")
60                cfg = yaml.safe_load(data)
61            except AttributeError:
62                # Not a valid YAML file.
63                logger.debug("got exception {}".format(sys.exc_info()[0]))
64            else:
65                if cfg is None:
66                    cfg = {}
67
68                return cfg
69    except IOError as e:
70        logger.error("cannot open '{}': {}".format(input_file, e.strerror))
71
72    return cfg
73