Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/run scripts #5

Merged
merged 11 commits into from
Jan 9, 2022
2 changes: 1 addition & 1 deletion mmp/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__='0.0.5a'
__version__='0.1.0a'
3 changes: 3 additions & 0 deletions mmp/cli/errors/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .missing import (
MissingFiles, MissingValue, NotSuchScript
)
18 changes: 18 additions & 0 deletions mmp/cli/errors/missing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class MissingFiles(Exception):
def __init__(self, file_name):
super().__init__("Missing File: %s" % file_name)

self.file = file_name

class MissingValue(Exception):
def __init__(self, file_name, value_name):
super().__init__(f"Missing value on file {file_name}: {value_name}")

self.file_name = file_name
self.value_name = value_name

class NotSuchScript(Exception):
def __init__(self, script_name):
super().__init__(f"Not such script: {script_name}")

self.script_name = script_name
46 changes: 40 additions & 6 deletions mmp/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@
from .docopt_command import DocoptDispatcher
from .docopt_command import get_handler
from .docopt_command import NoSuchCommand
from .run_scripts import RunScripts
from .formatter import ConsoleWarningFormatter
from .utils import get_version_info


log = logging.getLogger(__name__)
console_handler = logging.StreamHandler(sys.stderr)
sys.path.insert(1, '.')


def main():
Expand All @@ -27,17 +29,21 @@ def main():
print("Aborting.")
sys.exit(1)
except NoSuchCommand as e:
pass_to_lib()
pass_to_script()
except Exception as e:
print(str(e))

def pass_to_lib():

def pass_to_script():
'''
Function dedicated to pass commands to the virtualenviroment
'''
lib_command: str = ' '.join(sys.argv[1:])
os.system(f'pip_modules/bin/{lib_command}')
return
script: list = sys.argv[1:]
try:
RunScripts.get_run_script_value(script)
except Exception as e:
print(str(e))


def dispatch():
dispatcher = DocoptDispatcher(
Expand All @@ -56,7 +62,6 @@ def perform_command(options, handler, command_options):
return

command = TopLevelCommand(options=options)
# with errors.handle_connection_errors(project.client):
handler(command, command_options)


Expand All @@ -72,6 +77,7 @@ class TopLevelCommand:

Commands:
run Run python files with the environment modules
ls list installed packages
install Install your libraries on pip_modules
init Create requirements.txt to to add python libraries
upgrade Upgrade module on the pip_modules
Expand Down Expand Up @@ -99,6 +105,20 @@ def run(self, options=None):
bcolors.printColor('FAIL', 'Missing run.py or file parameter')
return
os.system('pip_modules/bin/python run.py')

def ls(self, options=None):
'''
List modules on project.

Options:
-a List all the modules with their dependencies

usage: ls [options]
'''
if options.get('-a'):
os.system('./pip_modules/bin/pip list')
else:
os.system(f'cat ./requirements.txt')

def install(self, options=None):
'''
Expand Down Expand Up @@ -135,6 +155,7 @@ def init(self, options=None):
'''
bcolors.printColor('HEADER', 'Initializing mmp')
self.__check_virtual_env()
self.__create_git()
self.__check_requirements()
bcolors.printColor('OKGREEN', 'Finish init')

Expand Down Expand Up @@ -179,6 +200,19 @@ def upgrade(self, options=None):
return
module_name = options.get('COMMAND')
os.system(f'pip_modules/bin/pip install --upgrade {module_name}')

def __create_git(self) -> None:
'''
Function dedicated to create git i
'''
if os.popen("command -v git").read() != ''\
and os.popen("[ -f ./.git ] && echo \"true\"") != '':
os.system("git init")

if os.popen("[ -f ./.gitignore ] && echo \"true\"") != '':
file = open('.gitignore', 'w+')
file.write("*.DS_Store\n.vscode/\n\n*.pyc\n\npip_modules/")


def __uninstall_pip_module(self, module_name: str):
'''
Expand Down
105 changes: 105 additions & 0 deletions mmp/cli/mex.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import functools
import json
import re
import os
import logging
import sys
from inspect import getdoc

from . import signals
from .colors import bcolors
from .docopt_command import DocoptDispatcher
from .docopt_command import get_handler
from .docopt_command import NoSuchCommand
from .formatter import ConsoleWarningFormatter
from .utils import get_version_info


log = logging.getLogger(__name__)
console_handler = logging.StreamHandler(sys.stderr)


def main():
try:
command = dispatch()
command()
except (KeyboardInterrupt, signals.ShutdownException):
print("Aborting.")
sys.exit(1)
except NoSuchCommand as e:
TopLevelCommand.pass_to_lib()
except Exception as e:
print(str(e))

def dispatch():
dispatcher = DocoptDispatcher(
TopLevelCommand, {
'options_first': True,
'version': get_version_info('mmp')
}
)
options, handler, command_options = dispatcher.parse(sys.argv[1:])
return functools.partial(perform_command, options, handler, command_options)


def perform_command(options, handler, command_options):
if options['COMMAND'] in ('help', 'version'):
handler(command_options)
return

command = TopLevelCommand(options=options)
handler(command, command_options)


class TopLevelCommand:
'''Module Environment Executor

This is the short for mmp exec, running a command from local modules

usage:
mex [options] [--] [COMMAND] [ARGS...]
mex -h|--help

Options:
-v, --version Shows mmp version
'''

def __init__(self, options=None):
'''
Constructor function
'''
self.toplevel_options = options or {}

@staticmethod
def pass_to_lib():
'''
Function dedicated to pass commands to the virtualenviroment
'''
command_to_find: str = sys.argv[1]
full_command: str = ' '.join(sys.argv[1:])
try:
if not os.path.isfile(f'pip_modules/bin/{command_to_find}'):
raise NoSuchCommand(command_to_find, 'aol')

os.system(f'pip_modules/bin/{full_command}')
except Exception as e:
print(str(e))
return

@classmethod
def help(cls, options):
"""
Get help on a command.

Usage: help [COMMAND]
"""
if options['COMMAND']:
subject = get_handler(cls, options['COMMAND'])
else:
subject = cls

print(getdoc(subject))


def set_no_color_if_clicolor(no_color_flag):
return no_color_flag or os.environ.get('CLICOLOR') == "0"
34 changes: 34 additions & 0 deletions mmp/cli/run_scripts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import os
from .errors import (
MissingFiles, MissingValue, NotSuchScript
)


class RunScripts:

@staticmethod
def get_run_script_value(command):
'''
Function dedicated to find the scripts on values

param: command list
'''
try:
import run as run_file
except ImportError as e:
raise Exception(f'Error on run.py: {str(e)}')
except:
raise MissingFiles('run.py')

if not hasattr(run_file, 'SCRIPTS'):
raise MissingValue('run.py', 'SCRIPTS')

script_target: str = command[0]
user_script: str = run_file.SCRIPTS.get(script_target, False)
if not user_script:
raise NotSuchScript(script_target)
extra_args = ' '.join(command[1:])
if extra_args:
user_script = f'{user_script} {extra_args}'
os.system(f'pip_modules/bin/{user_script}')
return
9 changes: 6 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@

setup(
name='mmp',
version='0.0.5',
authro='Alfonso Villaobos',
version='0.1.0',
author='Alfonso Villaobos',
author_email='alfonso@codepeat.com',
url='https://github.com/alfonsocv12/mmp',
license='MIT',
Expand All @@ -19,7 +19,10 @@
long_description=open('readme.md', 'r').read(),
long_description_content_type='text/markdown',
entry_points={
'console_scripts': ['mmp=mmp.cli.main:main']
'console_scripts': [
'mmp=mmp.cli.main:main',
'mex=mmp.cli.mex:main'
]
},
install_requires=[
'virtualenv>=20.4.4',
Expand Down