6e49388655fc88e35b112e0153ccbef7c0c29f52
[optf/osdf.git] / osdf / adapters / local_data / local_policies.py
1 # -------------------------------------------------------------------------
2 #   Copyright (c) 2015-2017 AT&T Intellectual Property
3 #
4 #   Licensed under the Apache License, Version 2.0 (the "License");
5 #   you may not use this file except in compliance with the License.
6 #   You may obtain a copy of the License at
7 #
8 #       http://www.apache.org/licenses/LICENSE-2.0
9 #
10 #   Unless required by applicable law or agreed to in writing, software
11 #   distributed under the License is distributed on an "AS IS" BASIS,
12 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 #   See the License for the specific language governing permissions and
14 #   limitations under the License.
15 #
16 # -------------------------------------------------------------------------
17 #
18
19 import json
20 import os
21 import re
22
23
24 def get_local_policies(local_policy_folder, local_policy_list, policy_id_list=None):
25     """
26     Get policies from a local file system.
27     Required for the following scenarios:
28     (a) doing work-arounds (e.g. if we are asked to drop some policies for testing purposes)
29     (b) work-arounds when policy platform is giving issues (e.g. if dev/IST policies are wiped out in an upgrade)
30     :param local_policy_folder: where the policy files are present
31     :param local_policy_list: list of local policies
32     :param policy_id_list: list of policies to get (if unspecified or None, get all)
33     :return: get policies
34     """
35     policies = []
36     if policy_id_list:
37         for policy_id in policy_id_list:
38             with open(os.path.join(local_policy_folder, policy_id + ".json")) as fid:
39                 policies.append(json.load(fid))
40     else:
41         for fname in local_policy_list:
42             with open(os.path.join(local_policy_folder, fname)) as fid:
43                 policies.append(json.load(fid))
44     return policies
45
46
47 def get_policy_names_from_file(fname_for_list_of_files):
48     """Get policy names; take care of comments, empty lines, etc"""
49     with open(fname_for_list_of_files) as fid:
50         return [
51             re.sub(r'#.*$', '', x).strip()  # remove inline comments and strip spaces
52             for x in fid
53             if not re.search(r'^#|^$', x.strip())  # remove blank or comments-only lines
54         ]