<commit_before># Copyright (c) 2017 <NAME> <<EMAIL>>
# MIT license
#
# <NAME>
# 2017-02-11

"""
Manage the observation manifest in YAML format.

NOTE
----
Use `ruamel.yaml`_ instead of `PyYAML`_ to preserve the comments
and other structures in the YAML file.

.. _`ruamel.yaml`: https://bitbucket.org/ruamel/yaml
.. _`PyYAML`: http://pyyaml.org/
"""

import os
from collections import OrderedDict
import argparse

import ruamel.yaml


class Manifest:
    """
    Manage the observational products manifest.
    """
    def __init__(self, filepath):
        self.filepath = os.path.abspath(filepath)
        self.manifest = ruamel.yaml.load(
            open(filepath), Loader=ruamel.yaml.RoundTripLoader)
        if self.manifest is None:
            self.manifest = ruamel.yaml.comments.CommentedMap()

    def dump(self):
        return ruamel.yaml.dump(self.manifest,
                                Dumper=ruamel.yaml.RoundTripDumper)

    def save(self):
        with open(self.filepath, "w") as f:
            f.write(self.dump())

    def show(self):
        print(self.dump())

    def get(self, key):
        """
        Get the value of the specified item in the manifest.

        Parameters
        ----------
        key : str
            The key of the item to be requested.

        Raises
        ------
        KeyError :
            If the specified item doesn't exist.
        """
        if key in self.manifest:
            return self.manifest[key]
        else:
            raise KeyError("manifest doesn't have item: '%s'" % key)

    def gets(self, keys, default=None, splitlist=False):
        """
        Get the value of the specified item in the manifest.

        TODO: splitlist

        Parameters
        ----------
        keys : list[str]
            A list of keys specifying the items to be requested.
        default : optional
            The default value to return if the item not exists.
        splitlist : bool, optional
            Split the item value if it is a list, making it is easier
            to export as CSV format.

        Returns
        -------
        data : `~OrderedDict`
            Ordered dictionary containing the requested items.

        Returns
        -------
        """
        data = OrderedDict([
            (key, self.manifest.get(key, default)) for key in keys
        ])
        if splitlist:
            ds = OrderedDict()
            for k, v in data.items():
                if isinstance(v, list):
                    for i, vi in enumerate(v):
                        ki = "{0}[{1}]".format(k, i)
                        ds[ki] = vi
                else:
                    ds[k] = v
            data = ds
        return data

    def getpath(self, key, relative=False):
        """
        Get the absolute path to the specified item by joining
        with the location of this manifest file.
        """
        value = self.get(key)
        cwd = os.getcwd()
        if isinstance(value, list):
            path = [os.path.join(os.path.dirname(self.filepath), f)
                    for f in value]
            if relative:
                path = [os.path.relpath(p, start=cwd) for p in path]
        else:
            path = os.path.join(os.path.dirname(self.filepath), value)
            if relative:
                path = os.path.relpath(path, start=cwd)
        return path

    def set(self, key, value):
        """
        Set the value of the specified item in the manifest.
        (Will add a new item or update an existing item.)
        """
        self.manifest[key] = self.parse_value(value)
        self.save()

    def setpath(self, key, path):
        """
        Get the relative path of the given file w.r.t. this manifest file,
        and set it to be the value of the specified item.
        (Will add a new item or update an existing item.)
        """
        dirname = os.path.dirname(self.filepath)
        if isinstance(path, list):
            abspath = [os.path.abspath(p) for p in path]
            relpath = [os.path.relpath(p, start=dirname) for p in abspath]
        else:
            abspath = os.path.abspath(path)
            relpath = os.path.relpath(abspath, start=dirname)
        self.manifest[key] = relpath
        self.save()

    def add(self, key, value):
        """
        Add the specified new item in the manifest.

        If the specified item already exists, raise a ``KeyError``.
        """
        if key in self.manifest:
            raise KeyError("manifest already has item: '%s'" % key)
        else:
            self.set(key, value)

    def update(self, key, value):
        """
        Update the specified existing item in the manifest.

        If the specified item doesn't exist, raise a ``KeyError``.
        """
        if key in self.manifest:
            self.set(key, value)
        else:
            raise KeyError("manifest doesn't have item: '%s'" % key)

    def delete(self, key):
        """
        Delete the specified item from the manifest.
        """
        del self.manifest[key]
        self.save()

    @classmethod
    def parse_value(self, value):
        """
        Parse the given (list of) value(s) from string.

        If the value list only has length of 1, then just return
        the only element without list enclosure.
        """
        if isinstance(value, list):
            pv = [self.parse_value_single(v) for v in value]
            if len(pv) == 1:
                return pv[0]
            else:
                return pv
        else:
            return self.parse_value_single(value)

    @staticmethod
    def parse_value_single(value):
        """
        Try to parse the given value from string to integer, float, boolean
        or string.
        """
        try:
            v = int(value)
        except ValueError:
            try:
                v = float(value)
            except ValueError:
                # string/boolean
                if value.lower() in ["true", "yes"]:
                    v = True
                elif value.lower() in ["false", "no"]:
                    v = False
                else:
                    v = value  # string
        return v


def find_manifest(filename="manifest.yaml", startdir=os.getcwd()):
    """
    Find the specified manifest file in current directory and
    the upper-level directories.

    Parameters
    ----------
    filename : str, optional<commit_msg>acispy/manifest.py: Fix parsing procedure for 'parse_value_single()'<commit_after># Copyright (c) 2017 <NAME> <<EMAIL>>
# MIT license
#
# <NAME>
# 2017-02-11

"""
Manage the observation manifest in YAML format.

NOTE
----
Use `ruamel.yaml`_ instead of `PyYAML`_ to preserve the comments
and other structures in the YAML file.

.. _`ruamel.yaml`: https://bitbucket.org/ruamel/yaml
.. _`PyYAML`: http://pyyaml.org/
"""

import os
from collections import OrderedDict
import argparse

import ruamel.yaml


class Manifest:
    """
    Manage the observational products manifest.
    """
    def __init__(self, filepath):
        self.filepath = os.path.abspath(filepath)
        self.manifest = ruamel.yaml.load(
            open(filepath), Loader=ruamel.yaml.RoundTripLoader)
        if self.manifest is None:
            self.manifest = ruamel.yaml.comments.CommentedMap()

    def dump(self):
        return ruamel.yaml.dump(self.manifest,
                                Dumper=ruamel.yaml.RoundTripDumper)

    def save(self):
        with open(self.filepath, "w") as f:
            f.write(self.dump())

    def show(self):
        print(self.dump())

    def get(self, key):
        """
        Get the value of the specified item in the manifest.

        Parameters
        ----------
        key : str
            The key of the item to be requested.

        Raises
        ------
        KeyError :
            If the specified item doesn't exist.
        """
        if key in self.manifest:
            return self.manifest[key]
        else:
            raise KeyError("manifest doesn't have item: '%s'" % key)

    def gets(self, keys, default=None, splitlist=False):
        """
        Get the value of the specified item in the manifest.

        TODO: splitlist

        Parameters
        ----------
        keys : list[str]
            A list of keys specifying the items to be requested.
        default : optional
            The default value to return if the item not exists.
        splitlist : bool, optional
            Split the item value if it is a list, making it is easier
            to export as CSV format.

        Returns
        -------
        data : `~OrderedDict`
            Ordered dictionary containing the requested items.

        Returns
        -------
        """
        data = OrderedDict([
            (key, self.manifest.get(key, default)) for key in keys
        ])
        if splitlist:
            ds = OrderedDict()
            for k, v in data.items():
                if isinstance(v, list):
                    for i, vi in enumerate(v):
                        ki = "{0}[{1}]".format(k, i)
                        ds[ki] = vi
                else:
                    ds[k] = v
            data = ds
        return data

    def getpath(self, key, relative=False):
        """
        Get the absolute path to the specified item by joining
        with the location of this manifest file.
        """
        value = self.get(key)
        cwd = os.getcwd()
        if isinstance(value, list):
            path = [os.path.join(os.path.dirname(self.filepath), f)
                    for f in value]
            if relative:
                path = [os.path.relpath(p, start=cwd) for p in path]
        else:
            path = os.path.join(os.path.dirname(self.filepath), value)
            if relative:
                path = os.path.relpath(path, start=cwd)
        return path

    def set(self, key, value):
        """
        Set the value of the specified item in the manifest.
        (Will add a new item or update an existing item.)
        """
        self.manifest[key] = self.parse_value(value)
        self.save()

    def setpath(self, key, path):
        """
        Get the relative path of the given file w.r.t. this manifest file,
        and set it to be the value of the specified item.
        (Will add a new item or update an existing item.)
        """
        dirname = os.path.dirname(self.filepath)
        if isinstance(path, list):
            abspath = [os.path.abspath(p) for p in path]
            relpath = [os.path.relpath(p, start=dirname) for p in abspath]
        else:
            abspath = os.path.abspath(path)
            relpath = os.path.relpath(abspath, start=dirname)
        self.manifest[key] = relpath
        self.save()

    def add(self, key, value):
        """
        Add the specified new item in the manifest.

        If the specified item already exists, raise a ``KeyError``.
        """
        if key in self.manifest:
            raise KeyError("manifest already has item: '%s'" % key)
        else:
            self.set(key, value)

    def update(self, key, value):
        """
        Update the specified existing item in the manifest.

        If the specified item doesn't exist, raise a ``KeyError``.
        """
        if key in self.manifest:
            self.set(key, value)
        else:
            raise KeyError("manifest doesn't have item: '%s'" % key)

    def delete(self, key):
        """
        Delete the specified item from the manifest.
        """
        del self.manifest[key]
        self.save()

    @classmethod
    def parse_value(self, value):
        """
        Parse the given (list of) value(s) from string.

        If the value list only has length of 1, then just return
        the only element without list enclosure.
        """
        if isinstance(value, list):
            pv = [self.parse_value_single(v) for v in value]
            if len(pv) == 1:
                return pv[0]
            else:
                return pv
        else:
            return self.parse_value_single(value)

    @staticmethod
    def parse_value_single(value):
        """
        Try to parse the given value from string to integer, float, boolean
        or string.

        If the input value is not string, then just ignore the parse.
        """
        if not isinstance(value, str):
            return value

        try:
            v = int(value)
        except ValueError:
            try:
                v = float(value)
            except ValueError:
                # string/boolean
                if value.lower() in ["true", "yes"]:
                    v = True
                elif value.lower() in ["false", "no"]:
                    v = False
                else:
                    v = value  # string
        return v


def find_manifest(filename="manifest.yaml", startdir=os.getcwd()):
    """
    Find the specified manifest file in current directory and
    the upper-level directories.

    Parameters
    ----------
    filename : str, optional
{'fraction_non_alphanumeric': 0.10138707946969117, 'fraction_numerical': 0.0026055636447237336, 'mean_word_length': 1.5816023738872405, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1954682', 'n_tokens_mistral': 3698, 'n_tokens_neox': 3493, 'n_words': 1200}