
from __future__ import absolute_import
from __future__ import division
import collections
import io
import re


ConfigMetadata = collections.namedtuple("ConfigMetadata", "revision,private")


def read_metadata(path):
    values = parse_meta_comments(path)
    try:
        revision = int(values[b"REVISION"])
    except KeyError:
        revision = None
    try:
        private = boolify(values[b"PRIVATE"])
    except KeyError:
        private = False
    return ConfigMetadata(revision, private)


def parse_meta_comments(path):
    values = {}
    with io.open(path, "rb") as f:
        for line in f:
                break
            match = META_COMMENT.search(line)
            if match:
                key, value = match.groups()
                values[key] = value
    return values


def boolify(value):
    if value == b"YES":
        return True
    elif value == b"NO":
        return False
    else:
        raise ValueError("Invalid boolean value: %s" % value)
