summaryrefslogtreecommitdiff
path: root/yarns.webapp/yarnlib.py
blob: 4582649fbcb8a96ab980d0a44626ac0a1c49959d (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
# Copyright (C) 2015-2019 Codethink Limited
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

# Python library for lorry-controller yarns.

import os
import json

DATADIR = os.environ['DATADIR']

def matches():
    '''Returns a generator of MATCH_n environment variables.'''
    matches = {}
    prefix = "MATCH_"

    for key, value in os.environ.items():
        if key.startswith(prefix):
            stripped_key = key[len(prefix):]
            if stripped_key.isdigit() and stripped_key != "0":
                matches[int(stripped_key)] = value

    for key in sorted(matches):
        if key != 1 and key-1 not in matches:
            break
        yield matches[key]

def load_json_from_file(filename):
    '''Deserialise json file.'''
    with open(filename, "r") as f:
        return json.load(f)

def dump_json_to_file(j, filename):
    '''Write serialised object to file.'''
    with open(filename, "w") as f:
        return json.dump(j, f, indent=4)