From f96dd14d03e83de13f832eefeaf1fdbce7ce93de Mon Sep 17 00:00:00 2001 From: Fred Date: Mon, 4 Mar 2013 14:09:15 +0800 Subject: [PATCH] Deprecating moodle-*.py --- lib/commands/__init__.py | 6 ++ mdk.py | 8 +- moodle | 11 +-- moodle-alias.py | 60 ++++----------- moodle-backport.py | 153 ++++-------------------------------- moodle-backup.py | 114 ++++----------------------- moodle-behat.py | 152 ++++-------------------------------- moodle-check.py | 104 ++++--------------------- moodle-config.py | 67 ++++------------ moodle-create.py | 100 ++++-------------------- moodle-fix.py | 57 ++++---------- moodle-info.py | 77 ++++--------------- moodle-init.py | 176 ++++-------------------------------------- moodle-install.py | 61 ++++----------- moodle-phpunit.py | 51 ++++-------- moodle-pull.py | 196 ++++------------------------------------------- moodle-purge.py | 55 ++++--------- moodle-push.py | 107 ++++---------------------- moodle-rebase.py | 118 ++++------------------------ moodle-remove.py | 51 ++++-------- moodle-run.py | 56 ++++---------- moodle-update.py | 80 ++++--------------- moodle-upgrade.py | 71 ++++------------- 23 files changed, 301 insertions(+), 1630 deletions(-) diff --git a/lib/commands/__init__.py b/lib/commands/__init__.py index 97cd048..90c9d8b 100644 --- a/lib/commands/__init__.py +++ b/lib/commands/__init__.py @@ -22,6 +22,12 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ + +def getCommand(cmd): + """Lazy loading of a command class. Millseconds saved, hurray!""" + cls = cmd.capitalize() + 'Command' + return getattr(getattr(getattr(__import__('lib.%s.%s' % ('commands', cmd)), 'commands'), cmd), cls) + commandsList = [ 'alias', 'backport', diff --git a/mdk.py b/mdk.py index 4e17c58..26d699d 100755 --- a/mdk.py +++ b/mdk.py @@ -27,19 +27,13 @@ import argparse import os import re from lib.command import CommandRunner -from lib.commands import commandsList +from lib.commands import getCommand, commandsList from lib.config import Conf from lib.tools import process from version import __version__ C = Conf() - -def getCommand(cmd): - """Lazy loading of a command class. Millseconds saved, hurray!""" - cls = cmd.capitalize() + 'Command' - return getattr(getattr(getattr(__import__('lib.%s.%s' % ('commands', cmd)), 'commands'), cmd), cls) - availaliases = [str(x) for x in C.get('aliases').keys()] choices = sorted(commandsList + availaliases) diff --git a/moodle b/moodle index 68ab836..5f09b30 100755 --- a/moodle +++ b/moodle @@ -23,9 +23,9 @@ ARGS=${@:2} # Resolve a command function resolve { - PY='moodle-$1.py' - if [[ $1 == 'mdk.py' ]]; then - PY='mdk.py' + PY="moodle-$1.py" + if [[ $1 == "mdk.py" ]]; then + PY="mdk.py" fi BIN=`which $PY` if [ -z "$BIN" ] @@ -56,7 +56,7 @@ function resolve { echo "You are using a deprecated bash script." echo "Please update your symlink '`basename $0`'." MDK=`resolve 'mdk.py'` -if [ -n "$MDK" ]; then +if [ -n "$MDK" ] && [ -f "$MDK" ]; then CLI="`which python` $MDK $COMMAND $ARGS" echo " ln -sf '$MDK' '$0'" echo "" @@ -64,10 +64,11 @@ if [ -n "$MDK" ]; then $CLI exit $? fi +echo "" # Checking if an alias exist for that command. BIN=`resolve "alias"` -ALIAS=`$BIN show $COMMAND` +ALIAS=`$BIN show $COMMAND | tail -1` if [ -n "$ALIAS" ] then diff --git a/moodle-alias.py b/moodle-alias.py index db7f0a4..a5c44ef 100755 --- a/moodle-alias.py +++ b/moodle-alias.py @@ -22,51 +22,19 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import argparse -from lib.tools import debug +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand from lib.config import Conf -try: - C = Conf() -except: - # Quietly die here. The main reason would be that the config file could not - # be loaded for some reason, which means that the environment has not been - # set yet. Therefore we exit quietly. This is a very specific case for - # moodle-alias as it is used in the Moodle bash script which does not know - # if the environment is properly set or not. - sys.exit() - -# Arguments -parser = argparse.ArgumentParser(description='Manage your aliases') -parser.add_argument('command', metavar='command', choices=['list', 'show', 'add', 'remove'], help='the action to perform') -parser.add_argument('arguments', type=str, metavar='arguments', default=None, nargs=argparse.REMAINDER, help='arguments for the command') -args = parser.parse_args() - -if args.command == 'list': - aliases = C.get('aliases') - for alias, command in aliases.items(): - print '{0:<20}: {1}'.format(alias, command) - -elif args.command == 'show': - if len(args.arguments) != 1: - debug('Too few/many arguments. One needed: moodle alias show aliasName') - sys.exit(1) - alias = C.get('aliases.%s' % args.arguments[0]) - if alias != None: - debug(alias) - -elif args.command == 'add': - if len(args.arguments) < 2: - debug('Too few/many arguments. Two needed: moodle alias add aliasName Command To Perform') - sys.exit(1) - alias = args.arguments[0] - command = ' '.join(args.arguments[1:]) - C.add('aliases.%s' % alias, command) - -elif args.command == 'remove': - if len(args.arguments) != 1: - debug('Too few/many arguments. One needed: moodle alias remove aliasName') - sys.exit(1) - alias = args.arguments[0] - C.remove('aliases.%s' % alias) +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-backport.py b/moodle-backport.py index 840f43f..a5c44ef 100755 --- a/moodle-backport.py +++ b/moodle-backport.py @@ -22,144 +22,19 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import argparse -from lib import workplace, tools -from lib.tools import debug, yesOrNo +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand from lib.config import Conf -Wp = workplace.Workplace() -C = Conf() - -# Arguments -parser = argparse.ArgumentParser(description="Backports a branch") -parser.add_argument('-b', '--branch', metavar='branch', help='the branch to backport if not the current one. If omitted, guessed from instance name.') -parser.add_argument('-i', '--integration', action='store_true', help='backport to integration instances.', dest='integration') -parser.add_argument('-p', '--push', action='store_true', help='push the branch after successful backport') -parser.add_argument('-t', '--push-to', metavar='remote', help='the remote to push the branch to. Default is %s.' % C.get('myRemote'), dest='pushremote') -parser.add_argument('-f', '--force-push', action='store_true', help='Force the push', dest='forcepush') -parser.add_argument('-j', '--update-jira', action='store_true', help='also add the github links to the jira issue.', dest='updatejira') -parser.add_argument('name', metavar='name', default=None, nargs='?', help='name of the instance to backport from. Can be omitted if branch is specified.') -parser.add_argument('-v', '--versions', metavar='version', required=True, nargs='+', choices=[str(x) for x in range(13, int(C.get('masterBranch')))] + ['master'], help='versions to backport to') -args = parser.parse_args() - -M = None -branch = args.branch -versions = args.versions -integration = args.integration - -# If we don't have a branch, we need an instance -M = Wp.resolve(args.name) -if not M and not branch: - debug('This is not a Moodle instance') - sys.exit(1) - -# Getting issue number -if M and not branch: - branch = M.currentBranch() - -# Parsing the branch -parsedbranch = tools.parseBranch(branch, C.get('wording.branchRegex')) -if not parsedbranch: - debug('Could not extract issue number from %s' % branch) - sys.exit(1) -issue = parsedbranch['issue'] -suffix = parsedbranch['suffix'] -version = parsedbranch['version'] - -# Original track -originaltrack = tools.stableBranch(version) - -# Integration? -if M: - integration = M.isIntegration() - - -def stashPop(stash): - """Small helper to pop the stash has we have to do it in some different places""" - if not stash[1].startswith('No local changes'): - pop = M2.git().stash(command='pop') - if pop[0] != 0: - debug('An error ocured while unstashing your changes') - else: - debug('Popped the stash') - -# Begin backport -for v in versions: - - # Gets the instance to cherry-pick to - name = Wp.generateInstanceName(v, integration=integration) - if not Wp.isMoodle(name): - debug('Could not find instance %s for version %s' % (name, v)) - continue - M2 = Wp.get(name) - - debug("Preparing cherry-pick of %s/%s in %s" % (M.get('identifier'), branch, name)) - - # Get hash list - cherry = '%s/%s..%s' % (C.get('upstreamRemote'), originaltrack, branch) - hashes = M.git().hashes(cherry) - hashes.reverse() - - # Stash - stash = M2.git().stash(untracked=True) - if stash[0] != 0: - debug('Error while trying to stash your changes. Skipping %s.' % M2.get('identifier')) - debug(stash[2]) - continue - elif not stash[1].startswith('No local changes'): - debug('Stashed your local changes') - - # Fetch the remote to get reference to the branch to backport - debug("Fetching remote %s..." % (M.get('path'))) - M2.git().fetch(M.get('path'), branch) - - # Creates a new branch if necessary - newbranch = M2.generateBranchName(issue, suffix=suffix) - track = '%s/%s' % (C.get('upstreamRemote'), M2.get('stablebranch')) - if not M2.git().hasBranch(newbranch): - debug('Creating branch %s' % newbranch) - if not M2.git().createBranch(newbranch, track=track): - debug('Could not create branch %s tracking %s in %s' % (newbranch, track, name)) - stashPop(stash) - continue - M2.git().checkout(newbranch) - else: - M2.git().checkout(newbranch) - debug('Hard reset %s to %s' % (newbranch, track)) - M2.git().reset(to=track, hard=True) - - # Picking the diff upstream/MOODLE_23_STABLE..github/MDL-12345-master - debug('Cherry-picking %s' % (cherry)) - result = M2.git().pick(hashes) - if result[0] != 0: - debug('Error while cherry-picking %s in %s.' % (cherry, name)) - debug(result[2]) - if yesOrNo('The cherry-pick might still be in progress, would you like to abort it?'): - result = M2.git().pick(abort=True) - if result[0] > 0 and result[0] != 128: - debug('Could not abort the cherry-pick!') - else: - stashPop(stash) - debug('') - continue - - # Pushing branch - if args.push: - pushremote = args.pushremote - if pushremote == None: - pushremote = C.get('myRemote') - debug('Pushing %s to %s' % (newbranch, pushremote)) - result = M2.git().push(remote=pushremote, branch=newbranch, force=args.forcepush) - if result[0] != 0: - debug('Error while pushing to remote %s' % (pushremote)) - debug(result[2]) - stashPop(stash) - continue - - stashPop(stash) - - debug('Instance %s successfully patched!' % name) - debug('') - -debug('Done.') +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-backup.py b/moodle-backup.py index 3e48b44..a5c44ef 100755 --- a/moodle-backup.py +++ b/moodle-backup.py @@ -22,105 +22,19 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import os -import argparse -import json -import time -from distutils.dir_util import copy_tree -from distutils.errors import DistutilsFileError -from lib import workplace, moodle, tools, backup -from lib.exceptions import * -from lib.tools import debug +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand from lib.config import Conf -Wp = workplace.Workplace() -C = Conf() - -# Arguments -parser = argparse.ArgumentParser(description='Backup a Moodle instance') -parser.add_argument('-l', '--list', action='store_true', help='list the backups', dest='list') -parser.add_argument('-i', '--info', metavar='backup', help='lists all the information about a backup', dest='info') -parser.add_argument('-r', '--restore', help='restore a backup', metavar='backup', dest='restore') -parser.add_argument('name', metavar='name', default=None, nargs='?', help='name of the instance') -args = parser.parse_args() - -name = args.name -BackupManager = backup.BackupManager() - -# List the backups -if args.list: - backups = BackupManager.list() - for key in sorted(backups.keys()): - B = backups[key] - backuptime = time.ctime(B.get('backup_time')) - print '{0:<25}: {1:<30} {2}'.format(key, B.get('release'), backuptime) - -# Displays backup information -elif args.info: - name = args.info - - # Resolve the backup - if not name or not BackupManager.exists(name): - debug('This is not a valid backup') - sys.exit(1) - - # Restore process - B = BackupManager.get(name) - infos = B.infos - debug('Displaying information about %s' % name) - for key in sorted(infos.keys()): - debug('{0:<20}: {1}'.format(key, infos[key])) - -# Restore -elif args.restore: - name = args.restore - - # Resolve the backup - if not name or not BackupManager.exists(name): - debug('This is not a valid backup') - sys.exit(1) - - # Restore process - B = BackupManager.get(name) - - try: - M = B.restore() - except BackupDirectoryExistsException as e: - debug('Cannot restore an instance on an existing directory. Please remove %s first.' % B.get('identifier')) - debug('Run: moodle remove %s' % B.get('identifier')) - sys.exit(1) - except BackupDBExistsException as e: - debug('The database %s already exists. Please remove it first.' % B.get('dbname')) - debug('This command could help: moodle remove %s' % B.get('identifier')) - sys.exit(1) - - # Loads M object and display information - debug('') - debug('Restored instance information') - debug('') - infos = M.info() - for key in sorted(infos.keys()): - print '{0:<20}: {1}'.format(key, infos[key]) - debug('') - - debug('Done.') - -# Backup the instance -else: - M = Wp.resolve(name) - if not M: - debug('This is not a Moodle instance') - sys.exit(1) - - try: - BackupManager.create(M) - except BackupDBEngineNotSupported as e: - debug('Does not support backup for the DB engine %s yet, sorry!' % M.get('dbtype')) - sys.exit(1) - except DistutilsFileError as e: - debug('Error while copying files. Check the permissions on the data directory.') - debug('Or run: sudo chmod -R 0777 %s' % M.get('dataroot')) - sys.exit(1) - - debug('Done.') +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-behat.py b/moodle-behat.py index a71a9ff..a5c44ef 100755 --- a/moodle-behat.py +++ b/moodle-behat.py @@ -21,142 +21,20 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import argparse -import os -import urllib -import re -from time import sleep -from lib import workplace -from lib.tools import debug, process, ProcessInThread -from lib.config import Conf - -C = Conf() - -# Arguments -parser = argparse.ArgumentParser(description='Initialise Behat') -parser.add_argument('-r', '--run', action='store_true', help='run the tests') -parser.add_argument('-j', '--no-javascript', action='store_true', help='skip the tests involving Javascript', dest='nojavascript') -parser.add_argument('-s', '--switch-completely', action='store_true', help='force the switch completely setting. This will be automatically enabled for PHP < 5.4', dest='switchcompletely') -parser.add_argument('--selenium', metavar='jarfile', nargs='?', default=None, help='path to the selenium standalone server to use', dest='selenium') -parser.add_argument('--selenium-verbose', action='store_true', help='outputs the output from selenium in the same window', dest='seleniumverbose') -parser.add_argument('name', metavar='name', default=None, nargs='?', help='name of the instance') -args = parser.parse_args() - -Wp = workplace.Workplace(C.get('dirs.storage')) - -# Loading instance -M = Wp.resolve(args.name) -if not M: - debug('This is not a Moodle instance') - sys.exit(1) - -# Check if installed -if not M.get('installed'): - debug('This instance needs to be installed first') - sys.exit(1) - -# No Javascript -nojavascript = args.nojavascript -if not nojavascript and not C.get('java') or not os.path.isfile(os.path.abspath(C.get('java'))): - nojavascript = True - debug('Disabling Javascript because Java is required to run Selenium and could not be found.') - -# If not composer.phar, install Composer -if not os.path.isfile(os.path.join(M.get('path'), 'composer.phar')): - debug('Installing Composer') - cliFile = 'behat_install_composer.php' - cliPath = os.path.join(M.get('path'), 'behat_install_composer.php') - urllib.urlretrieve('http://getcomposer.org/installer', cliPath) - M.cli('/' + cliFile, stdout=None, stderr=None) - os.remove(cliPath) - M.cli('composer.phar', args='install --dev', stdout=None, stderr=None) - - -# Download selenium -seleniumPath = os.path.expanduser(os.path.join(C.get('dirs.mdk'), 'selenium.jar')) -if args.selenium: - seleniumPath = args.selenium -elif not nojavascript and not os.path.isfile(seleniumPath): - debug('Attempting to find a download for Selenium') - url = urllib.urlopen('http://docs.seleniumhq.org/download/') - content = url.read() - selenium = re.search(r'http:[a-z0-9/._-]+selenium-server-standalone-[0-9.]+\.jar', content, re.I) - if selenium: - debug('Downloading Selenium from %s' % (selenium.group(0))) - urllib.urlretrieve(selenium.group(0), seleniumPath) - else: - debug('Could not locate Selenium server to download') - -if not os.path.isfile(seleniumPath): - debug('Selenium file %s does not exist') - sys.exit(1) - -# Run cli -try: - M.initBehat(switchcompletely=args.switchcompletely) - debug('Behat ready!') - # Preparing Behat command - cmd = ['vendor/bin/behat'] - if nojavascript: - cmd.append('--tags ~@javascript') - cmd.append('--config=%s/behat/behat.yml' % (M.get('behat_dataroot'))) - cmd = ' '.join(cmd) - - phpCommand = '%s -S localhost:8000' % (C.get('php')) - seleniumCommand = None - if seleniumPath: - seleniumCommand = '%s -jar %s' % (C.get('java'), seleniumPath) - - if args.run: - debug('Preparing Behat testing') - - # Preparing PHP Server - phpServer = None - if not M.get('behat_switchcompletely'): - debug('Starting standalone PHP server') - kwargs = {} - kwargs['cwd'] = M.get('path') - phpServer = ProcessInThread(phpCommand, **kwargs) - phpServer.start() - - # Launching Selenium - seleniumServer = None - if seleniumPath and not nojavascript: - debug('Starting Selenium server') - kwargs = {} - if args.seleniumverbose: - kwargs['stdout'] = None - kwargs['stderr'] = None - seleniumServer = ProcessInThread(seleniumCommand, **kwargs) - seleniumServer.start() - - debug('Running Behat tests') - - # Sleep for a few seconds before starting Behat - if phpServer or seleniumServer: - sleep(3) - - # Running the tests - process(cmd, M.path, None, None) - - # Kill the remaining processes - if phpServer: - phpServer.kill() - if seleniumServer: - seleniumServer.kill() - - # Remove the switch completely tag - if M.get('behat_switchcompletely'): - M.removeConfig('behat_switchcompletely') - - else: - debug('Launch PHP Server (or set $CFG->behat_switchcompletely to True):\n %s' % (phpCommand)) - if seleniumCommand: - debug('Launch Selenium (optional):\n %s' % (seleniumCommand)) - debug('Launch Behat:\n %s' % (cmd)) +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand +from lib.config import Conf -except Exception as e: - debug(e) - sys.exit(1) +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-check.py b/moodle-check.py index ec80360..a5c44ef 100755 --- a/moodle-check.py +++ b/moodle-check.py @@ -22,95 +22,19 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import os -import argparse -from lib import workplace -from lib.tools import debug +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand from lib.config import Conf -Wp = workplace.Workplace() -C = Conf() - -# Arguments -parser = argparse.ArgumentParser(description='Perform several checks on your current installation') -# parser.add_argument('-f', '--fix', dest='fix', action='store_true', help='Fix the problems where possible') -parser.add_argument('-i', '--integration', action='store_true', help='runs the script on the integration instances', dest='integration') -parser.add_argument('-s', '--stable', action='store_true', help='runs the script on the stable instances', dest='stable') -parser.add_argument('names', metavar='names', default=None, nargs='*', help='name of the instances') -args = parser.parse_args() - -# Check configuration file -debug('[Config file]') -distSettings = Conf(os.path.dirname(__file__), 'config-dist.json').get() -allSettings = C.get() - -errors = [] -def dictCompare(orig, mine, path = ''): - for k in orig: - currentpath = path + '.' + k - currentpath = currentpath.strip('.') - if k not in mine: - errors.append(currentpath) - elif type(orig[k]) in (dict, list): - dictCompare(orig[k], mine[k], currentpath) -dictCompare(distSettings, allSettings) - -if len(errors) > 0: - for err in errors: - debug(u'Missing setting %s' % err) -else: - debug('All good!') -debug('') - -# Checking instances -names = args.names -if not names: - names = Wp.list() -elif args.integration or args.stable: - names = Wp.list(integration = args.integration, stable = args.stable) - -Mlist = Wp.resolveMultiple(names) -if len(Mlist) < 1: - debug('No instances to check.') -else: - upstream = C.get('upstreamRemote') - myremote = C.get('myRemote') - myremoteurl = C.get('remotes.mine') - - if C.get('useCacheAsRemote'): - remoteInt = os.path.abspath(os.path.realpath(os.path.join(C.get('dirs.mdk'), 'integration.git'))) - remoteSta = os.path.abspath(os.path.realpath(os.path.join(C.get('dirs.mdk'), 'moodle.git'))) - else: - remoteInt = C.get('remotes.integration') - remoteSta = C.get('remotes.stable') - - for M in Mlist: - errors = [] - isIntegration = M.isIntegration() - - # Checking remotes - if upstream: - thisupstream = M.git().getRemote(upstream) - if not thisupstream: - errors.append('Missing remote %s' % upstream) - elif isIntegration and thisupstream != remoteInt: - errors.append('Remote %s is not %s' % (upstream, remoteInt)) - elif not isIntegration and thisupstream != remoteSta: - errors.append('Remote %s is not %s' % (upstream, remoteSta)) - - if myremote: - thismyremote = M.git().getRemote(myremote) - if not thismyremote: - errors.append('Missing remote %s' % myremote) - elif thismyremote != myremoteurl: - errors.append('Remote %s is not %s' % (myremote, myremoteurl)) - - if len(errors) > 0: - debug('[%s]' % M.get('identifier')) - for err in errors: - debug(u' %s' % err) - -# Done. -debug('') -debug('Done.') +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-config.py b/moodle-config.py index 2fd095c..a5c44ef 100755 --- a/moodle-config.py +++ b/moodle-config.py @@ -22,58 +22,19 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import argparse -from lib.tools import debug +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand from lib.config import Conf -C = Conf() - -# Arguments -parser = argparse.ArgumentParser(description='Manage your configuration') -parser.add_argument('command', metavar='command', choices=['flatlist', 'list', 'show', 'set'], help='the action to perform') -parser.add_argument('arguments', metavar='arguments', default=None, nargs='*', help='arguments for the command') -args = parser.parse_args() - -if args.command == 'list': - def show_list(settings, ident): - for name, setting in settings.items(): - if type(setting) != dict: - print u'{0:<20}: {1}'.format(u' ' * ident + name, setting) - else: - print u' ' * ident + '[%s]' % name - show_list(setting, ident + 2) - show_list(C.get(), 0) - -elif args.command == 'flatlist': - def show_list(settings, parent=''): - for name, setting in settings.items(): - if type(setting) != dict: - print u'%s: %s' % (parent + name, setting) - else: - show_list(setting, parent + name + u'.') - show_list(C.get()) - -elif args.command == 'show': - if len(args.arguments) != 1: - debug('Too few/many arguments. One needed: moodle config show settingName') - sys.exit(1) - setting = C.get(args.arguments[0]) - if setting != None: - debug(setting) - -elif args.command == 'set': - if len(args.arguments) < 2: - debug('Too few arguments. Two needed: moodle config set settingName value') - sys.exit(1) - setting = args.arguments[0] - val = u' '.join(args.arguments[1:]) - if val.startswith('b:'): - val = True if val[2:].lower() in ['1', 'true'] else False - elif val.startswith('i:'): - try: - val = int(val[2:]) - except ValueError: - # Not a valid int, let's consider it a string. - pass - C.set(setting, val) +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-create.py b/moodle-create.py index 17b0138..a5c44ef 100755 --- a/moodle-create.py +++ b/moodle-create.py @@ -22,91 +22,19 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import os -import argparse -import re - -from lib import db, moodle, workplace -from lib.tools import debug, yesOrNo +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand from lib.config import Conf -DB = db.DB -Wp = workplace.Workplace() -C = Conf() - -# Arguments -parser = argparse.ArgumentParser(description='Creates a new instance of Moodle') -parser.add_argument('-t', '--integration', action='store_true', help='create an instance from integration') -parser.add_argument('-i', '--install', action='store_true', help='launch the installation script after creating the instance', dest='install') -parser.add_argument('-r', '--run', action='store', nargs='*', help='scripts to run after installation', metavar='run') -parser.add_argument('-v', '--version', action='store', choices=[str(x) for x in range(13, int(C.get('masterBranch')))] + ['master'], default='master', help='version of Moodle', metavar='version') -parser.add_argument('-s', '--suffix', action='store', help='suffix for the instance name', metavar='suffix') -parser.add_argument('-e', '--engine', action='store', choices=['mysqli', 'pgsql'], default=C.get('defaultEngine'), help='database engine to use', metavar='engine') -args = parser.parse_args() - -engine = args.engine -version = args.version -name = Wp.generateInstanceName(version, integration=args.integration, suffix=args.suffix) - -# Wording version -versionNice = version -if version == 'master': - versionNice = C.get('wording.master') - -# Generating names -if args.integration: - fullname = C.get('wording.integration') + ' ' + versionNice + ' ' + C.get('wording.%s' % engine) -else: - fullname = C.get('wording.stable') + ' ' + versionNice + ' ' + C.get('wording.%s' % engine) - -# Append the suffix -if args.suffix: - fullname += ' ' + args.suffix.replace('-', ' ').replace('_', ' ').title() - -# Create the instance -debug('Creating instance %s...' % name) -kwargs = { - 'name': name, - 'version': version, - 'integration': args.integration, - 'useCacheAsRemote': C.get('useCacheAsRemote') -} -try: - M = Wp.create(**kwargs) -except Exception as e: - debug(e) - sys.exit(1) - -# Run the install script -if args.install: - - # Checking database - dbname = re.sub(r'[^a-zA-Z0-9]', '', name).lower()[:28] - db = DB(engine, C.get('db.%s' % engine)) - dropDb = False - if db.dbexists(dbname): - debug('Database already exists (%s)' % dbname) - dropDb = yesOrNo('Do you want to remove it?') - - # Install - kwargs = { - 'engine': engine, - 'dbname': dbname, - 'dropDb': dropDb, - 'fullname': fullname, - 'dataDir': Wp.getPath(name, 'data') - } - M.install(**kwargs) - - # Running scripts - if M.isInstalled() and type(args.run) == list: - for script in args.run: - debug('Running script \'%s\'' % (script)) - try: - M.runScript(script) - except Exception as e: - debug('Error while running the script') - debug(e) - -debug('Process complete!') +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-fix.py b/moodle-fix.py index bacba9a..a5c44ef 100755 --- a/moodle-fix.py +++ b/moodle-fix.py @@ -22,48 +22,19 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import os -import sys -import argparse -import re - -from lib import git, tools, moodle, workplace -from lib.tools import debug +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand from lib.config import Conf -C = Conf() - -# Arguments -parser = argparse.ArgumentParser(description='Creates a branch associated to an MDL issue') -parser.add_argument('issue', help='issue number') -parser.add_argument('suffix', nargs='?', default='', help='suffix of the branch') -parser.add_argument('-n', '--name', metavar='name', default=None, help='name of the instance') -args = parser.parse_args() - -Wp = workplace.Workplace() - -# Loading instance -M = Wp.resolve(args.name) -if not M: - debug('This is not a Moodle instance') - sys.exit(1) - -# Branch name -branch = M.generateBranchName(args.issue, suffix=args.suffix) - -# Track -track = '%s/%s' % (C.get('upstreamRemote'), M.get('stablebranch')) - -# Git repo -repo = M.git() - -# Creating and checking out the new branch -if not repo.hasBranch(branch): - if not repo.createBranch(branch, track): - debug('Could not create branch %s' % branch) - sys.exit(1) -if not repo.checkout(branch): - debug('Error while checkout out branch %s' % branch) - sys.exit(1) - -debug('Branch %s checked out' % branch) +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-info.py b/moodle-info.py index 6f48e0b..a5c44ef 100755 --- a/moodle-info.py +++ b/moodle-info.py @@ -22,64 +22,19 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import argparse -from lib import workplace -from lib.tools import debug - -Wp = workplace.Workplace() - -# Arguments -parser = argparse.ArgumentParser(description='Display information about a Moodle instance') -parser.add_argument('-l', '--list', action='store_true', help='list the instances', dest='list') -parser.add_argument('-i', '--integration', action='store_true', help='used with --list, only display integration instances', dest='integration') -parser.add_argument('-s', '--stable', action='store_true', help='used with --list, only display stable instances', dest='stable') -parser.add_argument('-n', '--name-only', action='store_true', help='used with --list, only display instances name', dest='nameonly') -parser.add_argument('-v', '--var', metavar='var', default=None, nargs='?', help='variable to output or edit') -parser.add_argument('-e', '--edit', metavar='value', nargs='?', help='value to set to the variable (--var). This value will be set in the config file of the instance. Prepend the value with i: or b: to set as int or boolean. DO NOT use names used by MDK (identifier, stablebranch, ...).', dest='edit') -parser.add_argument('name', metavar='name', default=None, nargs='?', help='name of the instance') -args = parser.parse_args() - -# List the instances -if args.list: - if args.integration != False or args.stable != False: - l = Wp.list(integration=args.integration, stable=args.stable) - else: - l = Wp.list() - l.sort() - for i in l: - if not args.nameonly: - M = Wp.get(i) - print '{0:<25}'.format(i), M.get('release') - else: - print i - -# Loading instance -else: - M = Wp.resolve(args.name) - if not M: - debug('This is not a Moodle instance') - sys.exit(1) - - # Printing/Editing variable. - if args.var != None: - # Edit a value. - if args.edit != None: - val = args.edit - if val.startswith('b:'): - val = True if val[2:].lower() in ['1', 'true'] else False - elif val.startswith('i:'): - try: - val = int(val[2:]) - except ValueError: - # Not a valid int, let's consider it a string. - pass - M.updateConfig(args.var, val) - debug('Set $CFG->%s to %s on %s' % (args.var, str(val), M.get('identifier'))) - else: - print M.get(args.var) - - # Printing info - else: - for key, info in M.info().items(): - print '{0:<20}: {1}'.format(key, info) +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand +from lib.config import Conf + +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-init.py b/moodle-init.py index 1b74445..a5c44ef 100755 --- a/moodle-init.py +++ b/moodle-init.py @@ -22,163 +22,19 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import os -import argparse -import shutil -import grp -import re -import pwd -import subprocess - -from lib.tools import debug, question, get_current_user - - -def resolve_directory(path, user): - if path.startswith('~'): - path = re.sub(r'^~', '~%s' % user, path) - path = os.path.abspath(os.path.realpath(os.path.expanduser(path))) - return path - -# Arguments -parser = argparse.ArgumentParser(description='Initialise MDK for the current user.') -parser.add_argument('-f', '--force', action='store_true', help='Force the initialisation') -args = parser.parse_args() - -# Check root. -if os.getuid() != 0: - debug('You must execute this as root.') - debug(' sudo mdk init') - sys.exit(1) - -# Check what user we want to initialise for. -while True: - username = question('What user are you initialising MDK for?', get_current_user()) - try: - user = pwd.getpwnam(username) - except: - debug('Error while getting information for user %s' % (username)) - continue - - try: - usergroup = grp.getgrgid(user.pw_gid) - except: - debug('Error while getting the group of user %s' % (username)) - continue - - break - -# Default directories. -userdir = resolve_directory('~/.moodle-sdk', username) -scriptdir = os.path.dirname(os.path.realpath(__file__)) - -# Create the main MDK folder. -if not os.path.isdir(userdir): - debug('Creating directory %s.' % userdir) - os.mkdir(userdir, 0755) - os.chown(userdir, user.pw_uid, usergroup.gr_gid) - -# Checking if the config file exists. -userconfigfile = os.path.join(userdir, 'config.json') -if os.path.isfile(userconfigfile): - debug('Config file %s already in place.' % userconfigfile) - if not args.force: - debug('Aborting. Use --force to continue.') - sys.exit(1) -elif not os.path.isfile(userconfigfile): - debug('Creating user config file in %s.' % userconfigfile) - open(userconfigfile, 'w') - os.chown(userconfigfile, user.pw_uid, usergroup.gr_gid) - -# If the group moodle-sdk exists, then we want to add the user to it. -try: - group = grp.getgrnam('moodle-sdk') - if not username in group.gr_mem: - debug('Adding user %s to group %s.' % (username, group.gr_name)) - # This command does not work for some reason... - # os.initgroups(username, group.gr_gid) - chgrp = subprocess.Popen(['usermod', '-a', '-G', 'moodle-sdk', username]) - chgrp.wait() -except KeyError: - # Raised when the group has not been found. - group = None - pass - -# Loading the configuration. -from lib.config import Conf as Config -C = Config(userfile=userconfigfile) - -# Asks the user what needs to be asked. -while True: - www = question('What is the DocumentRoot of your virtual host?', C.get('dirs.www')) - www = resolve_directory(www, username) - try: - if not os.path.isdir(www): - os.mkdir(www, 0775) - os.chown(www, user.pw_uid, usergroup.gr_gid) - except: - debug('Error while creating directory %s' % www) - continue - else: - C.set('dirs.www', www) - break - -while True: - storage = question('Where do you want to store your Moodle instances?', C.get('dirs.storage')) - storage = resolve_directory(storage, username) - try: - if not os.path.isdir(storage): - if storage != www: - os.mkdir(storage, 0775) - os.chown(storage, user.pw_uid, usergroup.gr_gid) - else: - debug('Error! dirs.www and dirs.storage must be different!') - continue - except: - debug('Error while creating directory %s' % storage) - continue - else: - C.set('dirs.storage', storage) - break - -# The default configuration file should point to the right directory for dirs.mdk, -# we will just ensure that it exists. -mdkdir = C.get('dirs.mdk') -mdkdir = resolve_directory(mdkdir, username) -if not os.path.isdir(mdkdir): - try: - debug('Creating MDK directory %s' % mdkdir) - os.mkdir(mdkdir, 0775) - os.chown(mdkdir, user.pw_uid, usergroup.gr_gid) - except: - debug('Error while creating %s, please fix manually.' % mdkdir) - -# Git repository. -github = question('What is your Github username? (Leave blank if not using Github)') -if github != None: - C.set('remotes.mine', C.get('remotes.mine').replace('YourGitHub', github)) - C.set('repositoryUrl', C.get('repositoryUrl').replace('YourGitHub', github)) - C.set('diffUrlTemplate', C.get('diffUrlTemplate').replace('YourGitHub', github)) - C.set('myRemote', 'github') - C.set('upstreamRemote', 'origin') -else: - C.set('remotes.mine', question('What is your remote?', C.get('remotes.mine'))) - C.set('myRemote', question('What to call your remote?', C.get('myRemote'))) - C.set('upstreamRemote', question('What to call the upsream remote (official Moodle remote)?', C.get('upstreamRemote'))) - -# Database settings. -C.set('db.mysqli.user', question('What is your MySQL user?', C.get('db.mysqli.user'))) -C.set('db.mysqli.passwd', question('What is your MySQL password?', C.get('db.mysqli.passwd'), password=True)) -C.set('db.pgsql.user', question('What is your PostgreSQL user?', C.get('db.pgsql.user'))) -C.set('db.pgsql.passwd', question('What is your PostgreSQL password?', C.get('db.pgsql.passwd'), password=True)) - -debug('') -debug('MDK has been initialised with minimal configuration.') -debug('For more settings, edit your config file: %s.' % userconfigfile) -debug('Use %s as documentation.' % os.path.join(scriptdir, 'config-dist.json')) -debug('') -debug('Type the following command to create your first instance:') -debug(' mdk create') -debug('(This will take some time, but don\'t worry, that\'s because the cache is still empty)') -debug('') -debug('/!\ Please logout/login before to avoid permission issues: sudo su `whoami`') +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand +from lib.config import Conf + +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-install.py b/moodle-install.py index fa96fd7..a5c44ef 100755 --- a/moodle-install.py +++ b/moodle-install.py @@ -21,53 +21,20 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import os -import argparse -from lib import db, moodle, workplace -from lib.tools import debug +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand from lib.config import Conf -DB = db.DB -Wp = workplace.Workplace() -C = Conf() - -# Arguments -parser = argparse.ArgumentParser(description='Install a Moodle instance') -parser.add_argument('-e', '--engine', action='store', choices=['mysqli', 'pgsql'], default=C.get('defaultEngine'), help='database engine to use', metavar='engine') -parser.add_argument('-f', '--fullname', action='store', help='full name of the instance', metavar='fullname') -parser.add_argument('-r', '--run', action='store', nargs='*', help='scripts to run after installation', metavar='run') -parser.add_argument('name', metavar='name', default=None, nargs='?', help='name of the instance') -args = parser.parse_args() - -name = args.name -engine = args.engine -fullname = args.fullname - -M = Wp.resolve(name) -if not M: - debug('This is not a Moodle instance') - sys.exit(1) - -name = M.get('identifier') -dataDir = Wp.getPath(name, 'data') -if not os.path.isdir(dataDir): - os.mkdir(dataDir, 0777) - -kwargs = { - 'engine': engine, - 'fullname': fullname, - 'dataDir': dataDir -} -M.install(**kwargs) - -# Running scripts -if M.isInstalled() and type(args.run) == list: - for script in args.run: - debug('Running script \'%s\'' % (script)) - try: - M.runScript(script) - except Exception as e: - debug('Error while running the script') - debug(e) +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-phpunit.py b/moodle-phpunit.py index a2d2d5f..a5c44ef 100755 --- a/moodle-phpunit.py +++ b/moodle-phpunit.py @@ -21,41 +21,20 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import argparse -from lib import workplace -from lib.tools import debug, process + +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand from lib.config import Conf -C = Conf() - -# Arguments -parser = argparse.ArgumentParser(description='Initialize PHPUnit') -parser.add_argument('-f', '--force', action='store_true', help='force the initialisation') -parser.add_argument('-r', '--run', action='store_true', help='also run the tests') -parser.add_argument('name', metavar='name', default=None, nargs='?', help='name of the instance') -args = parser.parse_args() - -Wp = workplace.Workplace(C.get('dirs.storage')) - -# Loading instance -M = Wp.resolve(args.name) -if not M: - debug('This is not a Moodle instance') - sys.exit(1) - -# Check if installed -if not M.get('installed'): - debug('This instance needs to be installed first') - sys.exit(1) - -# Run cli -try: - M.initPHPUnit(force=args.force) - debug('PHPUnit ready!') - if args.run: - debug('Running PHPUnit') - process('phpunit', M.path, None, None) -except Exception as e: - debug(e) - sys.exit(1) +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-pull.py b/moodle-pull.py index 3ddda9e..735caef 100755 --- a/moodle-pull.py +++ b/moodle-pull.py @@ -22,187 +22,19 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import argparse -import re -import os -from datetime import datetime -from lib import workplace, tools, jira -from lib.tools import debug, question +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand from lib.config import Conf -Wp = workplace.Workplace() -C = Conf() - -# Arguments -parser = argparse.ArgumentParser(description="Pull a branch from a tracker issue.") -parser.add_argument('-i', '--integration', action='store_true', help='checkout the stable branch before proceeding to the pull (Integration mode).') -parser.add_argument('-n', '--no-merge', action='store_true', help='checkout the remote branch without merging. Also this does not work with patch files. (No merge mode)', dest='nomerge') -parser.add_argument('-t', '--testing', action='store_true', help='checkout a testing branch before proceeding to the pull (Testing mode).') -parser.add_argument('issue', metavar='issue', default=None, nargs='?', help='tracker issue to pull from (MDL-12345, 12345). If not specified, read from current branch.') -args = parser.parse_args() - -M = Wp.resolve() -if not M: - debug('This is not a Moodle instance') - sys.exit(1) - -if (args.testing and args.integration) or (args.testing and args.nomerge) or (args.integration and args.nomerge): - debug('You cannot combine --integration, --testing or --no-merge') - sys.exit(1) - -# Tracker issue number. -issuenb = args.issue -if not issuenb: - parsedbranch = tools.parseBranch(M.currentBranch(), C.get('wording.branchRegex')) - if not parsedbranch: - debug('Could not extract issue number from %s' % M.currentBranch()) - sys.exit(1) - issuenb = parsedbranch['issue'] - -issue = re.sub(r'(MDL|mdl)(-|_)?', '', issuenb) -mdl = 'MDL-' + issue - -# Reading the information about the current instance. -branch = M.get('branch') - -# Get information from Tracker -debug('Retrieving information about %s from Moodle Tracker' % (mdl)) -J = jira.Jira() -issueInfo = J.getIssue(mdl) - -mode = 'pull' -remoteUrl = issueInfo.get('named').get(C.get('tracker.fieldnames.repositoryurl')) -remoteBranch = issueInfo.get('named').get(C.get('tracker.fieldnames.%s.branch' % (branch))) -patchesToApply = [] - -if not args.nomerge and (not remoteUrl or not remoteBranch): - mode = None - attachments = issueInfo.get('fields').get('attachment') - patches = {} - for attachment in attachments: - if attachment['filename'].endswith('.patch'): - patches[attachment['filename']] = attachment - - if len(patches) > 0: - mapping = {} - i = 1 - for key in sorted(patches.keys()): - patch = patches[key] - mapping[i] = patch - date = jira.Jira.parseDate(patch['created']) - print '{0:<2}: {1:<60} {2}'.format(i, patch['filename'][:60], datetime.strftime(date, '%Y-%m-%d %H:%M')) - i += 1 - - ids = question('What patches would you like to apply?') - if ids: - ids = re.split(r'\s*[, ]\s*', ids) - for i in ids: - i = int(i) - if not i in mapping.keys(): - continue - j = 0 - while True: - mapping[i]['mdk-filename'] = mapping[i]['filename'] + (('.' + str(j)) if j > 0 else '') - j += 1 - if not os.path.isfile(mapping[i]['mdk-filename']): - break - patchesToApply.append(mapping[i]) - mode = 'patch' - else: - mode = False - -if not mode: - debug('Did not find enough information to pull a patch.') - sys.exit() - -# Stash -stash = M.git().stash(untracked=True) -if stash[0] != 0: - debug('Error while trying to stash your changes. Exiting...') - sys.exit(1) -elif not stash[1].startswith('No local changes'): - debug('Stashed your local changes') - -# Create a testing branch -if args.testing: - i = 0 - while True: - i += 1 - suffix = 'test' if i <= 1 else 'test' + str(i) - newBranch = M.generateBranchName(issue, suffix=suffix, version=branch) - if not M.git().hasBranch(newBranch): - break - track = '%s/%s' % (C.get('upstreamRemote'), M.get('stablebranch')) - M.git().createBranch(newBranch, track=track) - if not M.git().checkout(newBranch): - debug('Could not checkout branch %s' % (newBranch)) - sys.exit(1) - debug('Checked out branch %s' % (newBranch)) - -# Checkout the stable branch -elif args.integration: - if not M.git().checkout(M.get('stablebranch')): - debug('Could not checkout branch %s' % (M.get('stablebranch'))) - debug('Checked out branch %s' % (M.get('stablebranch'))) - -# Create a no-merge branch -elif args.nomerge: - i = 0 - while True: - i += 1 - suffix = 'nomerge' if i <= 1 else 'nomerge' + str(i) - newBranch = M.generateBranchName(issue, suffix=suffix, version=branch) - if not M.git().hasBranch(newBranch): - break - track = '%s/%s' % (C.get('upstreamRemote'), M.get('stablebranch')) - M.git().createBranch(newBranch, track=track) - if not M.git().checkout(newBranch): - debug('Could not checkout branch %s' % (newBranch)) - sys.exit(1) - debug('Checked out branch %s' % (newBranch)) - mode = 'nomerge' - -if mode == 'pull': - # Pull branch from tracker - debug('Pulling branch %s from %s into %s' % (remoteBranch, remoteUrl, M.currentBranch())) - M.git().pull(remote=remoteUrl, ref=remoteBranch) - -elif mode == 'patch': - # Apply a patch from tracker - files = [] - for patch in patchesToApply: - dest = patch['mdk-filename'] - debug('Downloading %s' % (patch['filename'])) - if not J.download(patch['content'], dest): - debug('Failed to download. Aborting...') - files = [] - break - files.append(dest) - - if len(files) > 0: - debug('Applying patch(es)...') - if not M.git().apply(files): - debug('Could not apply the patch(es), please apply manually') - else: - for f in files: - os.remove(f) - -elif mode == 'nomerge': - # Checking out the patch without merging it. - debug('Fetching %s %s' % (remoteUrl, remoteBranch)) - M.git().fetch(remote=remoteUrl, ref=remoteBranch) - debug('Hard reset to FETCH_HEAD') - M.git().reset('FETCH_HEAD', hard=True) - -# Stash pop -if not stash[1].startswith('No local changes'): - pop = M.git().stash(command='pop') - if pop[0] != 0: - debug('An error ocured while unstashing your changes') - else: - debug('Popped the stash') - -debug('Done.') - -# TODO Tidy up the messy logic above! +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-purge.py b/moodle-purge.py index b11a31b..a5c44ef 100755 --- a/moodle-purge.py +++ b/moodle-purge.py @@ -22,46 +22,19 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import argparse -from lib import workplace, moodle, tools -from lib.tools import debug +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand from lib.config import Conf -Wp = workplace.Workplace() -C = Conf() - -# Arguments -parser = argparse.ArgumentParser(description='Purge an instance cache') -parser.add_argument('-a', '--all', action='store_true', help='runs the script on every instances', dest='all') -parser.add_argument('-i', '--integration', action='store_true', help='runs the script on the integration instances', dest='integration') -parser.add_argument('-s', '--stable', action='store_true', help='runs the script on the stable instances', dest='stable') -parser.add_argument('names', metavar='names', default=None, nargs='*', help='name of the instances') -args = parser.parse_args() - -# Resolving instances -names = args.names -if args.all: - names = Wp.list() -elif args.integration or args.stable: - names = Wp.list(integration = args.integration, stable = args.stable) - -# Doing stuff -Mlist = Wp.resolveMultiple(names) -if len(Mlist) < 1: - debug('No instances to work on. Exiting...') - sys.exit(1) - -for M in Mlist: - debug('Purging cache on %s' % (M.get('identifier'))) - - try: - M.purge() - except Exception as e: - debug(e) - else: - debug('Cache purged!') - - debug('') - -debug('Done.') +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-push.py b/moodle-push.py index 525270b..a5c44ef 100755 --- a/moodle-push.py +++ b/moodle-push.py @@ -22,98 +22,19 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import argparse -from lib import workplace, tools, jira -from lib.tools import debug +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand from lib.config import Conf -Wp = workplace.Workplace() -C = Conf() - -# Arguments -parser = argparse.ArgumentParser(description="Push a branch to a remote.") -parser.add_argument('-b', '--branch', metavar='branch', help='the branch to push. Default is current branch.') -parser.add_argument('-r', '--remote', metavar='remote', help='remote to push to. Default is your remote.') -parser.add_argument('-f', '--force', action='store_true', help='force the push (does not apply on the stable branch).') -parser.add_argument('-t', '--update-tracker', action='store_true', help='also add the diff information to the tracker issue.', dest='updatetracker') -parser.add_argument('-s', '--include-stable', action='store_true', help='also push the stable branch (MOODLE_xx_STABLE, master)', dest='includestable') -parser.add_argument('-k', '--force-stable', action='store_true', help='force the push on the stable branch', dest='forcestable') -parser.add_argument('name', metavar='name', default=None, nargs='?', help='name of the instance to work on') -args = parser.parse_args() - -M = Wp.resolve(args.name) -if not M: - debug('This is not a Moodle instance') - sys.exit(1) - -# Setting remote -if args.remote == None: - remote = C.get('myRemote') -else: - remote = args.remote - -# Setting branch -if args.branch == None: - branch = M.currentBranch() - if branch == 'HEAD': - debug('Cannot push HEAD branch') - sys.exit(1) -else: - branch = args.branch - -# Pushing current branch -debug('Pushing branch %s to remote %s...' % (branch, remote)) -result = M.git().push(remote, branch, force=args.force) -if result[0] != 0: - debug(result[2]) - sys.exit(1) - -if args.updatetracker: - # Getting issue number - # Parsing the branch - parsedbranch = tools.parseBranch(branch, C.get('wording.branchRegex')) - if not parsedbranch: - debug('Could not extract issue number from %s' % branch) - sys.exit(1) - issue = 'MDL-%s' % (parsedbranch['issue']) - - version = parsedbranch['version'] - - # Get the jira config - repositoryurl = C.get('repositoryUrl') - diffurltemplate = C.get('diffUrlTemplate') - stablebranch = M.get('stablebranch') - upstreamremote = C.get('upstreamRemote') - # Get the hash of the last upstream commit - ref = '%s/%s' % (upstreamremote, stablebranch) - headcommit = M.git().hashes(ref=ref, limit=1)[0] - - J = jira.Jira() - diffurl = diffurltemplate.replace('%branch%', branch).replace('%stablebranch%', stablebranch).replace('%headcommit%', headcommit) - - fieldrepositoryurl = C.get('tracker.fieldnames.repositoryurl') - fieldbranch = C.get('tracker.fieldnames.%s.branch' % version) - fielddiffurl = C.get('tracker.fieldnames.%s.diffurl' % version) - - if not (fieldrepositoryurl or fieldbranch or fielddiffurl): - debug('Cannot set tracker fields for this version (%s) as the field names are not configured in the config file.', version) - - else: - debug('Setting tracker fields: \n\t%s: %s \n\t%s: %s \n\t%s: %s\n' % (fieldrepositoryurl, repositoryurl, - fieldbranch, branch, - fielddiffurl, diffurl)) - J.setCustomFields(issue, {fieldrepositoryurl: repositoryurl, - fieldbranch: branch, - fielddiffurl: diffurl}) - -# Pushing stable branch -if args.includestable: - branch = M.get('stablebranch') - debug('Pushing branch %s to remote %s...' % (branch, remote)) - result = M.git().push(remote, branch, force=args.forcestable) - if result[0] != 0: - debug(result[2]) - sys.exit(1) - -debug('Done.') +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-rebase.py b/moodle-rebase.py index 86140d1..a5c44ef 100755 --- a/moodle-rebase.py +++ b/moodle-rebase.py @@ -22,109 +22,19 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import argparse -import re -from lib import workplace, moodle, tools -from lib.tools import debug +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand from lib.config import Conf -Wp = workplace.Workplace() -C = Conf() - -# Arguments -parser = argparse.ArgumentParser(description="Rebases branches") -parser.add_argument('-i', '--issues', metavar='issues', required=True, nargs='+', help='issues to be rebased') -parser.add_argument('-s', '--suffix', metavar='suffix', help='the suffix of the branch of those issues') -parser.add_argument('-v', '--versions', metavar='version', nargs='+', choices=[ str(x) for x in range(13, int(C.get('masterBranch'))) ] + ['master'], help='versions to rebase the issues on. Ignored if names is set.') -parser.add_argument('-p', '--push', action='store_true', help='push the branch after successful rebase') -parser.add_argument('-r', '--remote', metavar='remote', help='the remote to push the branch to. Default is %s.' % C.get('myRemote')) -parser.add_argument('-f', '--force-push', action='store_true', help='Force the push', dest='forcepush') -parser.add_argument('names', metavar='names', default=None, nargs='*', help='name of the instances to rebase') -args = parser.parse_args() - -names = args.names -issues = args.issues -versions = args.versions - -# If we don't have a version, we need an instance -if not names and not versions: - debug('This is not a Moodle instance') - sys.exit(1) - -# We don't have any names but some versions are set -if not names: - names = [] - for v in versions: - names.append(Wp.generateInstanceName(v)) - -# Getting instances -Mlist = Wp.resolveMultiple(names) - -# Loops over instances to rebase -for M in Mlist: - debug('Working on %s' % (M.get('identifier'))) - M.git().fetch(C.get('upstreamRemote')) - - # Test if currently in a detached branch - if M.git().currentBranch() == 'HEAD': - result = M.git().checkout(M.get('stablebranch')) - # If we can't checkout the stable branch, that is probably because we are in an unmerged situation - if not result: - debug('Error. The repository seem to be on a detached branch. Skipping.') - continue - - # Stash - stash = M.git().stash(untracked=True) - if stash[0] != 0: - debug('Error while trying to stash your changes. Skipping %s.' % M.get('identifier')) - debug(stash[2]) - continue - elif not stash[1].startswith('No local changes'): - debug('Stashed your local changes') - - # Looping over each issue to rebase - for issue in issues: - branch = M.generateBranchName(issue, suffix=args.suffix) - if not M.git().hasBranch(branch): - debug('Could not find branch %s' % (branch)) - continue - - # Rebase - debug('> Rebasing %s...' % (branch)) - base = '%s/%s' % (C.get('upstreamRemote'), M.get('stablebranch')) - result = M.git().rebase(branch=branch, base=base) - if result[0] != 0: - debug('Error while rebasing branch %s on top of %s' % (branch, base)) - if result[0] == 1 and result[2].strip() == '': - debug('There must be conflicts.') - debug('Aborting... Please rebase manually.') - M.git().rebase(abort=True) - else: - debug(result[2]) - continue - - # Pushing branch - if args.push: - remote = args.remote - if remote == None: - remote = C.get('myRemote') - debug('Pushing %s to %s' % (branch, remote)) - result = M.git().push(remote=remote, branch=branch, force=args.forcepush) - if result[0] != 0: - debug('Error while pushing to remote') - debug(result[2]) - continue - - # Stash pop - if not stash[1].startswith('No local changes'): - pop = M.git().stash(command='pop') - if pop[0] != 0: - debug('An error ocured while unstashing your changes') - debug(pop[2]) - else: - debug('Popped the stash') - - debug('') - -debug('Done.') +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-remove.py b/moodle-remove.py index c9a17f7..a5c44ef 100755 --- a/moodle-remove.py +++ b/moodle-remove.py @@ -22,42 +22,19 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import os -import sys -import argparse - -from lib import tools, workplace -from lib.tools import debug +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand from lib.config import Conf -C = Conf() - -# Arguments -parser = argparse.ArgumentParser(description='Completely remove an instance') -parser.add_argument('name', help='name of the instance') -parser.add_argument('-y', action='store_true', help='do not ask for confirmation', dest='do') -args = parser.parse_args() - -Wp = workplace.Workplace() -try: - M = Wp.get(args.name) -except: - debug('This is not a Moodle instance') - sys.exit(1) - -if not args.do: - confirm = raw_input('Are you sure? (Y/n) ') - if confirm != 'Y': - debug('Exiting...') - sys.exit(0) - -debug('Removing %s...' % args.name) -try: - Wp.delete(args.name) -except OSError: - debug('Error while deleting the instance.') - debug('This is probably a permission issue.') - debug('Run: sudo chmod -R 0777 %s' % Wp.getPath(args.name)) - sys.exit(1) - -debug('Instance removed') +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-run.py b/moodle-run.py index 9692acb..a5c44ef 100755 --- a/moodle-run.py +++ b/moodle-run.py @@ -22,43 +22,19 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import argparse -from lib import workplace, moodle, tools -from lib.tools import debug - -Wp = workplace.Workplace() - -# Arguments -parser = argparse.ArgumentParser(description='Run a script on a Moodle instance') -parser.add_argument('-a', '--all', action='store_true', help='runs the script on every instances', dest='all') -parser.add_argument('-i', '--integration', action='store_true', help='runs the script on the integration instances', dest='integration') -parser.add_argument('-s', '--stable', action='store_true', help='runs the script on the stable instances', dest='stable') -parser.add_argument('script', metavar='script', help='the name of the script to run') -parser.add_argument('names', metavar='names', default=None, nargs='*', help='name of the instances') -args = parser.parse_args() - -# Resolving instances -names = args.names -if args.all: - names = Wp.list() -elif args.integration or args.stable: - names = Wp.list(integration=args.integration, stable=args.stable) - -# Doing stuff -Mlist = Wp.resolveMultiple(names) -if len(Mlist) < 1: - debug('No instances to work on. Exiting...') - sys.exit(1) - -for M in Mlist: - debug('Running \'%s\' on \'%s\'' % (args.script, M.get('identifier'))) - try: - M.runScript(args.script, stderr=None, stdout=None) - except Exception as e: - debug('Error while running the script on %s' % M.get('identifier')) - debug(e) - else: - debug('') - -debug('Done.') +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand +from lib.config import Conf + +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-update.py b/moodle-update.py index d513a20..a5c44ef 100755 --- a/moodle-update.py +++ b/moodle-update.py @@ -22,71 +22,19 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import argparse -from lib import workplace -from lib.tools import debug +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand from lib.config import Conf -Wp = workplace.Workplace() -C = Conf() - -# Arguments -parser = argparse.ArgumentParser(description='Updates the instance from remote') -parser.add_argument('-a', '--all', action='store_true', help='runs the script on every instances', dest='all') -parser.add_argument('-i', '--integration', action='store_true', help='runs the script on the integration instances', dest='integration') -parser.add_argument('-s', '--stable', action='store_true', help='runs the script on the stable instances', dest='stable') -parser.add_argument('-u', '--upgrade', action='store_true', help='upgrade the instance after successful update', dest='upgrade') -parser.add_argument('-c', '--update-cache', action='store_true', help='update the cached remotes. Useful when using cache as remote.', dest='updatecache') -parser.add_argument('-p', '--proceed', action='store_true', help='do not exit the process after updating the cache', dest='process') -parser.add_argument('names', metavar='names', default=None, nargs='*', help='name of the instances') -args = parser.parse_args() - -# Updating cache only -if args.updatecache: - debug('Updating cached remote') - Wp.updateCachedClones() - debug('Done.') - if not args.process: - sys.exit(0) - debug('') - -# Updating instances -names = args.names -if args.all: - names = Wp.list() -elif args.integration or args.stable: - names = Wp.list(integration=args.integration, stable=args.stable) - -Mlist = Wp.resolveMultiple(names) -if len(Mlist) < 1: - debug('No instances to work on. Exiting...') - sys.exit(1) - -errors = [] - -for M in Mlist: - debug('Updating %s...' % M.get('identifier')) - try: - M.update() - except Exception as e: - errors.append(M) - debug('Error during the update of %s' % M.get('identifier')) - debug(e) - else: - if args.upgrade: - try: - M.upgrade() - except Exception as e: - errors.append(M) - debug('Error during the upgrade of %s' % M.get('identifier')) - pass - debug('') -debug('Done.') - -if errors and len(Mlist) > 1: - debug('') - debug('/!\ Some errors occurred on the following instances:') - for M in errors: - debug('- %s' % M.get('identifier')) - sys.exit(1) +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) diff --git a/moodle-upgrade.py b/moodle-upgrade.py index 13df1fd..a5c44ef 100755 --- a/moodle-upgrade.py +++ b/moodle-upgrade.py @@ -22,62 +22,19 @@ along with this program. If not, see . http://github.com/FMCorz/mdk """ -import sys -import argparse -from lib import workplace, moodle, tools -from lib.tools import debug +from os.path import basename +from lib.command import CommandRunner +from lib.commands import getCommand from lib.config import Conf -Wp = workplace.Workplace() -C = Conf() - -# Arguments -parser = argparse.ArgumentParser(description='Runs the Moodle upgrade script') -parser.add_argument('-a', '--all', action='store_true', help='runs the script on every instances', dest='all') -parser.add_argument('-i', '--integration', action='store_true', help='runs the script on the integration instances', dest='integration') -parser.add_argument('-n', '--no-checkout', action='store_true', help='do not checkout the stable branch before upgrading', dest='nocheckout') -parser.add_argument('-s', '--stable', action='store_true', help='runs the script on the stable instances', dest='stable') -parser.add_argument('-u', '--update', action='store_true', help='update the instance before running the upgrade script', dest='update') -parser.add_argument('names', metavar='names', default=None, nargs='*', help='name of the instances') -args = parser.parse_args() - -names = args.names -if args.all: - names = Wp.list() -elif args.integration or args.stable: - names = Wp.list(integration = args.integration, stable = args.stable) - -Mlist = Wp.resolveMultiple(names) -if len(Mlist) < 1: - debug('No instances to work on. Exiting...') - sys.exit(1) - -errors = [] - -for M in Mlist: - if args.update: - debug('Updating %s...' % M.get('identifier')) - try: - M.update() - except Exception as e: - errors.append(M) - debug('Error during update. Skipping...') - debug(e) - continue - debug('Upgrading %s...' % M.get('identifier')) - - try: - M.upgrade(args.nocheckout) - except Exception as e: - errors.append(M) - debug('Error during the upgrade of %s' % M.get('identifier')) - debug(e) - debug('') -debug('Done.') - -if errors and len(Mlist) > 1: - debug('') - debug('/!\ Some errors occurred on the following instances:') - for M in errors: - debug('- %s' % M.get('identifier')) - sys.exit(1) +f = basename(__file__) +print "Do not call %s directly." % (f) +print "This file will be removed in a later version." +print "Please use `mdk [command] [arguments]`" +print "" + +cmd = f.replace('moodle-', '').replace('.py', '') +cls = getCommand(cmd) +Cmd = cls(Conf()) +Runner = CommandRunner(Cmd) +Runner.run(None, prog='%s %s' % ('mdk', cmd)) -- 2.11.0