# Path: pyjob/config.py
# class ImmutableDictMixin(object):
# class PyJobConfig(UserDict, ImmutableDictMixin):
#     def lock(self):
#     def unlock(self):
#     def assert_lock(fn):
#         def wrapper(self, *args, **kwargs):
#     def __setitem__(self, key, value):
#     def setdefault(self, key, value=None):
#     def update(self, *args, **kwargs):
#     def write(self):
#     def read_yaml(yamlf):
#     def from_default(cls):
# 
# Path: pyjob/factory.py
# def TaskFactory(platform, *args, **kwargs):
#     """Accessibility function for any :obj:`~pyjob.task.Task`
# 
#     Examples
#     --------
# 
#     >>> from pyjob import TaskFactory
#     >>> with TaskFactory('local', script) as task:
#     ...     task.run()
# 
#     Parameters
#     ----------
#     platform : str
#        The platform to create the :obj:`~pyjob.task.Task` on
#     *args : tuple
#        Any positional arguments relevant to the :obj:`~pyjob.task.Task`
#     **kwargs : dict
#        Any keyword arguments relevant to the :obj:`~pyjob.task.Task`
# 
#     Raises
#     ------
#     :exc:`~pyjob.exception.PyJobUnknownTaskPlatform`
#        Unknown platform
# 
#     """
#     platform = platform.lower()
#     if platform in TASK_PLATFORMS:
#         logger.debug("Found requested platform in available task list")
#         module, class_ = TASK_PLATFORMS[platform]
#         return getattr(importlib.import_module(module), class_)(*args, **kwargs)
#     else:
#         raise PyJobUnknownTaskPlatform(f"Unknown platform: {platform}")
# 
# Path: pyjob/version.py

# 
# Path: pyjob/factory.py
# TASK_PLATFORMS = {
#     "local": ("pyjob.local", "LocalTask"),
#     "lsf": ("pyjob.lsf", "LoadSharingFacilityTask"),
#     "pbs": ("pyjob.pbs", "PortableBatchSystemTask"),
#     "slurm": ("pyjob.slurm", "SlurmTask"),
#     "sge": ("pyjob.sge", "SunGridEngineTask"),
#     "torque": ("pyjob.torque", "TorqueTask"),
# }
# 
# Path: pyjob/misc.py
# def typecast(value):
#     """Recursively typecast an input
# 
#     Parameters
#     ----------
#     value : int, float, str, tuple, list
# 
#     """
#     if isinstance(value, (dict, list)):
#         iterator = range(len(value)) if isinstance(value, list) else value
#         for i in iterator:
#             value[i] = typecast(value[i])
#     elif value == "None":
#         return None
#     elif value in ("False", "True"):
#         return True if value == "True" else False
#     else:
#         for type_fn in (int, float, str):
#             try:
#                 return type_fn(value)
#             except ValueError:
#                 pass
#     return value


import argparse
import enum
import logging
import os
import sys
from pyjob import TaskFactory, __version__, config
from pyjob.factory import TASK_PLATFORMS
from pyjob.misc import typecast

def main():
    p = argparse.ArgumentParser(
        prog="pyjob", formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    mark_parser(p, Subcommand.NONE)  # may be removed once Py3-only

    sub_p = p.add_subparsers()
    add_exec_subparser(sub_p)
    add_conf_subparser(sub_p)
    args = p.parse_args()

    if args.which == Subcommand.EXEC:
        kwargs = vars(args)
        platform = kwargs.pop("platform")
        executables = [os.path.abspath(f) for f in kwargs.pop("executables")]
        kwargs["directory"] = os.path.abspath(kwargs["directory"])

        verbosity_lvl = kwargs.pop("verbose")
        if verbosity_lvl == 0:
            logging.basicConfig(level=logging.INFO)
        else:
            logging.basicConfig(level=logging.DEBUG)

        with TaskFactory(platform, executables, **kwargs) as task:
            task.run()

    elif args.which == Subcommand.CONF:
        for pair in args.arguments:
            k, v = pair.split(":")

# Path: pyjob/config.py
# class ImmutableDictMixin(object):
# class PyJobConfig(UserDict, ImmutableDictMixin):
#     def lock(self):
#     def unlock(self):
#     def assert_lock(fn):
#         def wrapper(self, *args, **kwargs):
#     def __setitem__(self, key, value):
#     def setdefault(self, key, value=None):
#     def update(self, *args, **kwargs):
#     def write(self):
#     def read_yaml(yamlf):
#     def from_default(cls):
# 
# Path: pyjob/factory.py
# def TaskFactory(platform, *args, **kwargs):
#     """Accessibility function for any :obj:`~pyjob.task.Task`
# 
#     Examples
#     --------
# 
#     >>> from pyjob import TaskFactory
#     >>> with TaskFactory('local', script) as task:
#     ...     task.run()
# 
#     Parameters
#     ----------
#     platform : str
#        The platform to create the :obj:`~pyjob.task.Task` on
#     *args : tuple
#        Any positional arguments relevant to the :obj:`~pyjob.task.Task`
#     **kwargs : dict
#        Any keyword arguments relevant to the :obj:`~pyjob.task.Task`
# 
#     Raises
#     ------
#     :exc:`~pyjob.exception.PyJobUnknownTaskPlatform`
#        Unknown platform
# 
#     """
#     platform = platform.lower()
#     if platform in TASK_PLATFORMS:
#         logger.debug("Found requested platform in available task list")
#         module, class_ = TASK_PLATFORMS[platform]
#         return getattr(importlib.import_module(module), class_)(*args, **kwargs)
#     else:
#         raise PyJobUnknownTaskPlatform(f"Unknown platform: {platform}")
# 
# Path: pyjob/version.py

# 
# Path: pyjob/factory.py
# TASK_PLATFORMS = {
#     "local": ("pyjob.local", "LocalTask"),
#     "lsf": ("pyjob.lsf", "LoadSharingFacilityTask"),
#     "pbs": ("pyjob.pbs", "PortableBatchSystemTask"),
#     "slurm": ("pyjob.slurm", "SlurmTask"),
#     "sge": ("pyjob.sge", "SunGridEngineTask"),
#     "torque": ("pyjob.torque", "TorqueTask"),
# }
# 
# Path: pyjob/misc.py
# def typecast(value):
#     """Recursively typecast an input
# 
#     Parameters
#     ----------
#     value : int, float, str, tuple, list
# 
#     """
#     if isinstance(value, (dict, list)):
#         iterator = range(len(value)) if isinstance(value, list) else value
#         for i in iterator:
#             value[i] = typecast(value[i])
#     elif value == "None":
#         return None
#     elif value in ("False", "True"):
#         return True if value == "True" else False
#     else:
#         for type_fn in (int, float, str):
#             try:
#                 return type_fn(value)
#             except ValueError:
#                 pass
#     return value


# Path: pyjob/__main__.py
import argparse
import enum
import logging
import os
import sys
from pyjob import TaskFactory, __version__, config
from pyjob.factory import TASK_PLATFORMS
from pyjob.misc import typecast


def main():
    p = argparse.ArgumentParser(
        prog="pyjob", formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    mark_parser(p, Subcommand.NONE)  # may be removed once Py3-only

    sub_p = p.add_subparsers()
    add_exec_subparser(sub_p)
    add_conf_subparser(sub_p)
    args = p.parse_args()

    if args.which == Subcommand.EXEC:
        kwargs = vars(args)
        platform = kwargs.pop("platform")
        executables = [os.path.abspath(f) for f in kwargs.pop("executables")]
        kwargs["directory"] = os.path.abspath(kwargs["directory"])

        verbosity_lvl = kwargs.pop("verbose")
        if verbosity_lvl == 0:
            logging.basicConfig(level=logging.INFO)
        else:
            logging.basicConfig(level=logging.DEBUG)

        with TaskFactory(platform, executables, **kwargs) as task:
            task.run()

    elif args.which == Subcommand.CONF:
        for pair in args.arguments:
            k, v = pair.split(":")

            config.setdefault(k, value=typecast(v))