# Path: servi/command.py
# def process_and_run_command_line(command_line=None):
#         servi_parser, sub_parsers = setup_parsers()
# 
#         commands = load_plugins(sub_parsers)
# 
#         args, extra_args = parse_args(commands, servi_parser, command_line)
# 
#         log_level = arg_to_log_level(args.verbose)
#         retval = False
#         with use_log_level(log_level):
#             if args.template_dir:
#                 c.TMPL_DIR_SITE = args.template_dir
#                 warn('*** Just set TMPL_DIR_SITE to |{0}|'.format(
#                     c.TMPL_DIR_SITE))
# 
#             if not args.command:
#                 error('\n***** Error ******\nNo command on command line.\n')
#                 servi_parser.print_help()
#                 raise ServiError('No command line')
# 
#             if args.command not in commands:
#                 raise ServiError('Unknown command: {0}'.format(args.command))
# 
#             special = getattr(commands[args.command], "special", {})
# 
#             if not special.get("skip_init", False):
#                 master_dir = c.find_master_dir(os.getcwd())
#                 set_master_dir(master_dir)
#                 load_user_config()
# 
#             try:
#                 info('Servi - Running: {0}\n'.format(args.command))
#                 if c.MASTER_DIR:
#                     debug('Master Directory: {0}'
#                           .format(os.path.abspath(c.MASTER_DIR)))
#                 debug('Template Directory: {0}'
#                       .format(os.path.abspath(c.TMPL_DIR_SITE)))
# 
#                 retval = args.command_func(args, extra_args)
#             except (ForceError, ServiError):
#                 raise
# 
# 
#         return retval
# 
# Path: servi/utils.py
# def file_exists(path):
#     return os.path.isfile(path) and os.access(path, os.R_OK)
# 
# @contextmanager
# def reset_cwd():
#     origdir = os.getcwd()
#     yield
#     os.chdir(origdir)
# 
# Path: servi/semantic.py
# class SemanticVersion(object):
#     mult = [10**8, 10**4, 10**0]
# 
#     def __init__(self, sv_string):
#         self.sv, self.sv_ar = self.sv_string_to_ver(sv_string)
# 
#     @staticmethod
#     def sv_string_to_ver(sv_string):
#         if sv_string is None:
#             return None
# 
#         if type(sv_string) is not str:
#             raise ValueError('Bad semantic version - must be string: |{0}|'
#                              .format(sv_string))
# 
#         sv_ar = sv_string.split('.')
#         if len(sv_ar) > 3 or len(sv_ar) == 0:
#             raise ValueError('Bad semantic version string: |{0}|'
#                              .format(sv_string))
#         try:
#             sv_ar = [int(s) for s in sv_ar]
#             sv_val = SemanticVersion.sv_ar_to_sv(sv_ar)
#         except ValueError:
#             raise ValueError('Bad semantic version string: |{0}|'
#                              .format(sv_string))
#         sv_ar = [a1+a2 for a1, a2 in
#                  zip_longest(sv_ar, [0, 0, 0], fillvalue=0)]
#         return sv_val, sv_ar
# 
#     @staticmethod
#     def sv_ar_to_sv(sv_ar):
#         sv_zip = zip_longest(SemanticVersion.mult, sv_ar, fillvalue=0)
#         sv_val = [m * v for m, v in sv_zip]
#         return sv_val
# 
#     def __lt__(self, other):
#         return self.sv < other.sv
# 
#     def __le__(self, other):
#         return self.sv <= other.sv
# 
#     def __eq__(self, other):
#         return self.sv == other.sv
# 
#     def __ge__(self, other):
#         return self.sv >= other.sv
# 
#     def __gt__(self, other):
#         return self.sv > other.sv
# 
#     def __str__(self):
#         return '.'.join([str(v) for v in self.sv_ar])
# 
#     def bump_ver(self, ver_type):
#         assert ver_type in SEMANTIC_VERSIONS
#         if ver_type == MAJOR:
#             pos = 0
#         elif ver_type == MINOR:
#             pos = 1
#         else:
#             pos = 2
#         self.sv_ar[pos] += 1
#         self.sv = self.sv_ar_to_sv(self.sv_ar)
#         return self
# 
# Path: servi/exceptions.py
# class ServiError(Exception):
#     # Expected errrors. Handle gracefully (ie: no stack dump)
#     def __init__(self, msg=None):
#         self.msg = msg
# 
#     def __str__(self):
#         return (
#             '\n***** ERROR *****\n'
#             '{0}\n'
#             '\n**Servi Aborting**'.format(self.msg))
# 
# Path: servi/commands/utils.py
# def in_servi_code_dir():
#     # returns True if cwd is within the servi code directory hierarchy
#     servi_root = servi_code_root()
#     common = os.path.commonprefix([servi_root, os.getcwd()])
#     debug('in_servi_code_dir == {0}'.format(common == servi_root))
#     return common == servi_root


import subprocess
import servi.manifest as man
    import py.path
from filecmp import cmp
from tests.fixtures import *
from servi.command import process_and_run_command_line as servi_run
from servi.utils import file_exists, reset_cwd
from servi.semantic import SemanticVersion
from servi.exceptions import ServiError
from servi.commands.utils import in_servi_code_dir



def test_cmd_utils(mock_template_dir, mock_in_servi_dir):
    # Test changed manifest
    modify_file(pathfor('ansible_config/playbook.yml', c.TEMPLATE))
    assert not servi_run('utils --ensure_latest_manifest')

    # Now test skipping
    assert servi_run('utils --ensure_latest_manifest')

    # Test no manifest
    os.remove(pathfor(c.MANIFEST_FILE, c.TEMPLATE))
    assert not servi_run('utils --ensure_latest_manifest')

# Path: servi/command.py
# def process_and_run_command_line(command_line=None):
#         servi_parser, sub_parsers = setup_parsers()
# 
#         commands = load_plugins(sub_parsers)
# 
#         args, extra_args = parse_args(commands, servi_parser, command_line)
# 
#         log_level = arg_to_log_level(args.verbose)
#         retval = False
#         with use_log_level(log_level):
#             if args.template_dir:
#                 c.TMPL_DIR_SITE = args.template_dir
#                 warn('*** Just set TMPL_DIR_SITE to |{0}|'.format(
#                     c.TMPL_DIR_SITE))
# 
#             if not args.command:
#                 error('\n***** Error ******\nNo command on command line.\n')
#                 servi_parser.print_help()
#                 raise ServiError('No command line')
# 
#             if args.command not in commands:
#                 raise ServiError('Unknown command: {0}'.format(args.command))
# 
#             special = getattr(commands[args.command], "special", {})
# 
#             if not special.get("skip_init", False):
#                 master_dir = c.find_master_dir(os.getcwd())
#                 set_master_dir(master_dir)
#                 load_user_config()
# 
#             try:
#                 info('Servi - Running: {0}\n'.format(args.command))
#                 if c.MASTER_DIR:
#                     debug('Master Directory: {0}'
#                           .format(os.path.abspath(c.MASTER_DIR)))
#                 debug('Template Directory: {0}'
#                       .format(os.path.abspath(c.TMPL_DIR_SITE)))
# 
#                 retval = args.command_func(args, extra_args)
#             except (ForceError, ServiError):
#                 raise
# 
# 
#         return retval
# 
# Path: servi/utils.py
# def file_exists(path):
#     return os.path.isfile(path) and os.access(path, os.R_OK)
# 
# @contextmanager
# def reset_cwd():
#     origdir = os.getcwd()
#     yield
#     os.chdir(origdir)
# 
# Path: servi/semantic.py
# class SemanticVersion(object):
#     mult = [10**8, 10**4, 10**0]
# 
#     def __init__(self, sv_string):
#         self.sv, self.sv_ar = self.sv_string_to_ver(sv_string)
# 
#     @staticmethod
#     def sv_string_to_ver(sv_string):
#         if sv_string is None:
#             return None
# 
#         if type(sv_string) is not str:
#             raise ValueError('Bad semantic version - must be string: |{0}|'
#                              .format(sv_string))
# 
#         sv_ar = sv_string.split('.')
#         if len(sv_ar) > 3 or len(sv_ar) == 0:
#             raise ValueError('Bad semantic version string: |{0}|'
#                              .format(sv_string))
#         try:
#             sv_ar = [int(s) for s in sv_ar]
#             sv_val = SemanticVersion.sv_ar_to_sv(sv_ar)
#         except ValueError:
#             raise ValueError('Bad semantic version string: |{0}|'
#                              .format(sv_string))
#         sv_ar = [a1+a2 for a1, a2 in
#                  zip_longest(sv_ar, [0, 0, 0], fillvalue=0)]
#         return sv_val, sv_ar
# 
#     @staticmethod
#     def sv_ar_to_sv(sv_ar):
#         sv_zip = zip_longest(SemanticVersion.mult, sv_ar, fillvalue=0)
#         sv_val = [m * v for m, v in sv_zip]
#         return sv_val
# 
#     def __lt__(self, other):
#         return self.sv < other.sv
# 
#     def __le__(self, other):
#         return self.sv <= other.sv
# 
#     def __eq__(self, other):
#         return self.sv == other.sv
# 
#     def __ge__(self, other):
#         return self.sv >= other.sv
# 
#     def __gt__(self, other):
#         return self.sv > other.sv
# 
#     def __str__(self):
#         return '.'.join([str(v) for v in self.sv_ar])
# 
#     def bump_ver(self, ver_type):
#         assert ver_type in SEMANTIC_VERSIONS
#         if ver_type == MAJOR:
#             pos = 0
#         elif ver_type == MINOR:
#             pos = 1
#         else:
#             pos = 2
#         self.sv_ar[pos] += 1
#         self.sv = self.sv_ar_to_sv(self.sv_ar)
#         return self
# 
# Path: servi/exceptions.py
# class ServiError(Exception):
#     # Expected errrors. Handle gracefully (ie: no stack dump)
#     def __init__(self, msg=None):
#         self.msg = msg
# 
#     def __str__(self):
#         return (
#             '\n***** ERROR *****\n'
#             '{0}\n'
#             '\n**Servi Aborting**'.format(self.msg))
# 
# Path: servi/commands/utils.py
# def in_servi_code_dir():
#     # returns True if cwd is within the servi code directory hierarchy
#     servi_root = servi_code_root()
#     common = os.path.commonprefix([servi_root, os.getcwd()])
#     debug('in_servi_code_dir == {0}'.format(common == servi_root))
#     return common == servi_root


# Path: tests/test_cmd_utils.py
import subprocess
import servi.manifest as man
    import py.path
from filecmp import cmp
from tests.fixtures import *
from servi.command import process_and_run_command_line as servi_run
from servi.utils import file_exists, reset_cwd
from servi.semantic import SemanticVersion
from servi.exceptions import ServiError
from servi.commands.utils import in_servi_code_dir




def test_cmd_utils(mock_template_dir, mock_in_servi_dir):
    # Test changed manifest
    modify_file(pathfor('ansible_config/playbook.yml', c.TEMPLATE))
    assert not servi_run('utils --ensure_latest_manifest')

    # Now test skipping
    assert servi_run('utils --ensure_latest_manifest')

    # Test no manifest
    os.remove(pathfor(c.MANIFEST_FILE, c.TEMPLATE))
    assert not servi_run('utils --ensure_latest_manifest')

    assert file_exists(pathfor(c.MANIFEST_FILE, c.TEMPLATE))