Source

xenv / xenv / main.py

Full commit
'''
This defines the main 'xe' entry point to the xenv. Below, the parser
definition describes the usage and UI for interacting with an xenv.
'''
import os
from subprocess import call

from argparse import ArgumentParser
from xenv.models import Xenv


def run_cmd(args):
    xenv = Xenv(root=args.root)
    xenv.run(args.cmd.pop())


def create_xenv_cmd(args):
    xenv = Xenv(root=args.root)
    xenv.create()


class CLI(object):
    description = '''Utilize a specific executable environment (xenv) for running applications'''

    def __init__(self):
        self.parser = ArgumentParser(description=self.description)
        self.parser.add_argument('--root', '-r', default=os.environ.get('XE_ROOT'),
                                 help='The xenv root. This will override using the XE_ROOT env var.')
        
        self.subs = self.parser.add_subparsers(help='sub command help')

        # Create a new xenv
        create = self.subs.add_parser('create', help='Create a new xenv')
        create.add_argument('root', help='The root of the xenv')
        create.set_defaults(func=create_xenv_cmd)

        # run a command via the xenv
        run = self.subs.add_parser('run', prefix_chars='!',
                                   help='Run a command from the xenv')
        run.add_argument('cmd', type=str, nargs='*', action='append',
                         help='The command and flags to run via the xenv')
        run.set_defaults(func=run_cmd)

    def run(self, args=None):
        if not args:
            args = self.parser.parse_known_args()
        else:
            args = self.parser.parse_args(args)
        return args
    

def xe():
    cli = CLI()
    args, extras = cli.run()
    if args.root:
        args.root = os.path.abspath(args.root)
    if args.func:
        args.func(args)