Repository : http://git.fedorahosted.org/cgit/copr.git
On branch : master
commit fc27328a0e504876e4efad6df212c28b8ce0cd80 Author: Pierre-Yves Chibon pingou@pingoured.fr Date: Sun Feb 17 15:23:00 2013 +0100
Rework copr-cli
This commit restructure copr-cli by removing cliff from it and thus making it a simple argparse based python program using subparser
This removes complexicity as well as the dependency on cliff.
Move the URL to copr into the config file. This way one can use another copr server than the one provided by the Fedora Project.
Rename the function set_user to get_user, semantically more appropriate.
copr_cli/main.py | 159 ++++++++++++++++++++---------- copr_cli/subcommands.py | 257 ++++++++++++++++++++++++----------------------- coprcli-setup.py | 27 +---- 3 files changed, 244 insertions(+), 199 deletions(-)
diff --git a/copr_cli/main.py b/copr_cli/main.py index 350fdf8..15bfb02 100644 --- a/copr_cli/main.py +++ b/copr_cli/main.py @@ -1,68 +1,123 @@ #-*- coding: UTF-8 -*-
-import logging +import argparse import sys
- -import cliff.app -import cliff.commandmanager -from cliff.commandmanager import CommandManager +import subcommands
__version__ = '0.1.0' __description__ = "CLI tool to run copr"
-copr_url = 'http://copr-fe.cloud.fedoraproject.org/' -copr_api_url = '{0}/api'.format(copr_url) - - -class CoprCli(cliff.app.App): - - log = logging.getLogger(__name__) - - def __init__(self): - manager = cliff.commandmanager.CommandManager('copr_cli.subcommands') - super(CoprCli, self).__init__( - description=__description__, - version=__version__, - command_manager=manager, - ) - requests_log = logging.getLogger("requests") - requests_log.setLevel(logging.WARN) - - def initialize_app(self, argv): - self.log.debug('initialize_app') - - def prepare_to_run_command(self, cmd): - self.log.debug('prepare_to_run_command %s', cmd.__class__.__name__) - - def clean_up(self, cmd, result, err): - self.log.debug('clean_up %s', cmd.__class__.__name__) - if err: - self.log.debug('got an error: %s', err) - - # Overload run_subcommand to gracefully handle unknown commands. - def run_subcommand(self, argv): - try: - self.command_manager.find_command(argv) - except ValueError as e: - if "Unknown command" in str(e): - print "%r is an unknown command" % ' '.join(argv) - print "Try "copr -h"" - sys.exit(1) - else: - raise
- return super(CoprCli, self).run_subcommand(argv) +def action_build(args): + """ Method called when the 'build' action has been selected by the + user. + + :param args: argparse arguments provided by the user + + """ + subcommands.build(args.copr, args.pkgs, + args.memory, args.timeout) + + +def action_create(args): + """ Method called when the 'create' action has been selected by the + user. + + :param args: argparse arguments provided by the user + + """ + subcommands.create(args.name, args.chroots, args.description, + args.instructions, args.repos, + args.initial_pkgs) + + +def action_list(args): + """ Method called when the 'list' action has been selected by the + user. + + :param args: argparse arguments provided by the user + + """ + subcommands.list(args.username) + + +def setup_parser(): + """ + Set the main arguments. + """ + parser = argparse.ArgumentParser(prog="copr-cli") + # General connection options + parser.add_argument('--version', action='version', + version='copr-cli %s' % (__version__)) + + subparsers = parser.add_subparsers(title='actions') + + # create the parser for the "list" command + parser_list = subparsers.add_parser('list', + help='List all the copr of the ' + 'provided ' + ) + parser_list.add_argument("username", nargs='?', + help='The username that you would like to ' + 'list the copr of (defaults to current user)' + ) + parser_list.set_defaults(func=action_list) + + # create the parser for the "create" command + parser_create = subparsers.add_parser('create', + help='Create a new copr') + parser_create.add_argument('name', + help='The name of the copr to create') + parser_create.add_argument("--chroot", dest="chroots", action='append', + help="Chroot to use for this copr") + parser_create.add_argument('--repo', dest='repos', action='append', + help="Repository to add to this copr") + parser_create.add_argument('--initial-pkgs', dest='initial_pkgs', + action='append', + help="List of packages to build in this " + "new copr") + parser_create.add_argument('--description', + help="Description of the copr") + parser_create.add_argument('--instructions', + help="Instructions for the copr") + parser_create.set_defaults(func=action_create) + + # create the parser for the "build" command + parser_build = subparsers.add_parser('build', + help='Build packages to a ' + 'specified copr') + parser_build.add_argument('copr', + help='The copr repo to build the package in' + ) + parser_build.add_argument('pkgs', nargs='+', action='append') + parser_build.add_argument('--memory', dest='memory', + help="") + parser_build.add_argument('--timeout', dest='timeout', + help="") + parser_build.set_defaults(func=action_build) + + return parser
def main(argv=sys.argv[1:]): """ Main function """ - myapp = CoprCli() - return myapp.run(argv) + # Set up parser for global args + parser = setup_parser() + # Parse the commandline + arg = parser.parse_args() + arg.func(arg)
if __name__ == '__main__': - sys.exit(main(sys.argv[1:])) - #add_copr('test2', 'fedora-rawhide-x86_64', - #description='Test repos #2') - #list_copr() + try: + main() + except KeyboardInterrupt: + print "\nInterrupted by user." + sys.exit(1) + except argparse.ArgumentTypeError, e: + print "\nError: {0}".format(e) + sys.exit(2) + except Exception, e: + print 'Error: {0}'.format(e) + sys.exit(100) diff --git a/copr_cli/subcommands.py b/copr_cli/subcommands.py index c0013db..1d561ee 100644 --- a/copr_cli/subcommands.py +++ b/copr_cli/subcommands.py @@ -2,20 +2,13 @@
import ConfigParser import json -import logging -import requests import os import sys
-import cliff.lister -import cliff.show - -from cliff.command import Command - -from main import copr_api_url +import requests
-def set_user(): +def get_user(): """ Retrieve the user information from the config file. """ config = ConfigParser.ConfigParser() config.read(os.path.join(os.path.expanduser('~'), '.config', @@ -25,124 +18,138 @@ def set_user(): return {'username': username, 'token': token}
-class List(cliff.lister.Lister): - """ List all the copr of a user. """ +def get_api_url(): + """ Retrieve the user information from the config file. """ + config = ConfigParser.ConfigParser( + {'copr_url': 'http://copr-fe.cloud.fedoraproject.org%27%7D) + config.read(os.path.join(os.path.expanduser('~'), '.config', + 'copr')) + copr_url = config.get('copr-cli', 'copr_url') + return '%s/api' % copr_url
- log = logging.getLogger(__name__) - - def get_parser(self, prog_name): - parser = super(type(self), self).get_parser(prog_name) - parser.add_argument("username", nargs='?') - return parser - - def take_action(self, args): - user = set_user() - - if args.username: - user['username'] = args.username - URL = '{0}/owned/'.format(copr_api_url) - req = requests.get(URL, params=user) - output = json.loads(req.text) - if 'repos' in output: - if output['repos']: - columns = ['name', 'description', 'repos', 'instructions'] - values = [] - for entry in output['repos']: - values.append([entry[key] for key in columns]) - return (columns, values) - else: - columns = ['output'] - values = ['No copr retrieved for user: "{0}"'.format( - user['username'])] - return (columns, [values]) + +def list(username=None): + """ List all the copr of a user. """ + user = get_user() + copr_api_url = get_api_url() + url = '{0}/owned/'.format(copr_api_url) + + if username: + user['username'] = username + del(user['token']) + + req = requests.get(url, params=user) + output = json.loads(req.text) + columns = [] + values = [] + if 'repos' in output: + if output['repos']: + columns = ['name', 'description', 'repos', 'instructions'] + values = [] + for entry in output['repos']: + values.append([entry[key] for key in columns]) else: columns = ['output'] - values = ['Wrong output format returned by the server'] - return (columns, [values]) - - -class AddCopr(Command): + values = ['No copr retrieved for user: "{0}"'.format( + user['username'])] + else: + columns = ['output'] + values = ['Wrong output format returned by the server'] + + def _list_to_row(values, widths): + ''' Return a print ready version of the provided list ''' + row = [] + cnt = 0 + for item in values: + max_width = widths[cnt] + cnt += 1 + if not item: + item = '' + if cnt < len(values): + row.append(item.ljust(max_width + 1)) + else: + row.append(item) + return row + + if len(columns) > 1: + widths = {} + cnt = 0 + for item in columns: + widths[cnt] = len(item) + cnt += 1 + for row in values: + cnt = 0 + for item in row: + if not item: + item = '' + widths[cnt] = max(widths[cnt], len(item)) + cnt += 1 + + headers = '|'.join(_list_to_row(columns, widths)) + print headers + print '-' * len(headers) + for row in values: + print "|".join(_list_to_row(row, widths)) + + else: + max_width = len(values[0]) + headers = columns[0] + print headers + print "-"*len(headers) + print values[0] + + +def create(name, chroots=[], description=None, instructions=None, + repos=None, initial_pkgs=None): """ Create a new copr. """ - - log = logging.getLogger(__name__) - - def get_parser(self, prog_name): - parser = super(type(self), self).get_parser(prog_name) - parser.add_argument("name") - parser.add_argument("--chroot", dest="chroots", action='append', - help="") - parser.add_argument('--repo', dest='repos', action='append', - help="") - parser.add_argument('--initial-pkgs', dest='initial_pkgs', - action='append', - help="") - parser.add_argument('--description', - help="") - parser.add_argument('--instructions', - help="") - return parser - - def take_action(self, args): - user = set_user() - URL = '{0}/copr/new/'.format(copr_api_url) - - repos = None - if args.repos: - repos = ' '.join(args.repos) - initial_pkgs = None - if args.initial_pkgs: - initial_pkgs = ' '.join(args.initial_pkgs) - data = {'name': args.name, - 'repos': repos, - 'initial_pkgs': initial_pkgs, - 'description': args.description, - 'instructions': args.instructions - } - for chroot in args.chroots: - data[chroot] = 'y' - - req = requests.post(URL, - auth=(user['username'], user['token']), - data=data) - output = json.loads(req.text) - if output['output'] == 'ok': - print output['message'] - else: - print 'Something went wrong:\n {0}'.format(output['error']) - - -class Build(Command): + user = get_user() + copr_api_url = get_api_url() + URL = '{0}/copr/new/'.format(copr_api_url) + + repos = None + if type(repos) == list(): + repos = ' '.join(repos) + initial_pkgs = None + if type(initial_pkgs) == list(): + initial_pkgs = ' '.join(initial_pkgs) + data = {'name': name, + 'repos': repos, + 'initial_pkgs': initial_pkgs, + 'description': description, + 'instructions': instructions + } + for chroot in chroots: + data[chroot] = 'y' + + req = requests.post(URL, + auth=(user['username'], user['token']), + data=data) + output = json.loads(req.text) + if output['output'] == 'ok': + print output['message'] + else: + print 'Something went wrong:\n {0}'.format(output['error']) + + +def build(copr, pkgs, memory, timeout): """ Build a new package into a given copr. """ - - log = logging.getLogger(__name__) - - def get_parser(self, prog_name): - parser = super(type(self), self).get_parser(prog_name) - parser.add_argument('copr') - parser.add_argument('pkgs', nargs='+', action='append') - parser.add_argument('--memory', dest='memory', - help="") - parser.add_argument('--timeout', dest='timeout', - help="") - return parser - - def take_action(self, args): - user = set_user() - URL = '{0}/coprs/detail/{1}/{2}/new_build/'.format( - copr_api_url, - user['username'], - args.copr) - - data = {'pkgs': ' '.join(args.pkgs[0]), - 'memory': args.memory, - 'timeout': args.timeout - } - - req = requests.post(URL, - auth=(user['username'], user['token']), - data=data) - output = json.loads(req.text) - if req.status_code != 200: - print 'Something went wrong:\n {0}'.format(output['error']) - else: - print output['message'] + user = get_user() + copr_api_url = get_api_url() + URL = '{0}/coprs/detail/{1}/{2}/new_build/'.format( + copr_api_url, + user['username'], + copr) + + data = {'pkgs': ' '.join(pkgs), + 'memory': memory, + 'timeout': timeout + } + + req = requests.post(URL, + auth=(user['username'], user['token']), + data=data) + output = json.loads(req.text) + if req.status_code != 200: + print 'Something went wrong:\n {0}'.format(output['error']) + else: + print output['message'] diff --git a/coprcli-setup.py b/coprcli-setup.py index 0084494..ed7eb57 100644 --- a/coprcli-setup.py +++ b/coprcli-setup.py @@ -1,11 +1,6 @@ -#!/usr/bin/env python +#!/usr/bin/python
-try: - from setuptools import setup -except ImportError: - from ez_setup import use_setuptools - use_setuptools() - from setuptools import setup +from setuptools import setup
import sys
@@ -13,25 +8,13 @@ f = open('README') long_description = f.read().strip() f.close()
-# Ridiculous as it may seem, we need to import multiprocessing and -# logging here in order to get tests to pass smoothly on python 2.7. -try: - import multiprocessing - import logging -except ImportError: - pass
from copr_cli.main import __description__, __version__
requires = [ - 'cliff', + 'requests', ]
-subcommands = [ - 'list = copr_cli.subcommands:List', - 'add-copr = copr_cli.subcommands:AddCopr', - 'build-copr = copr_cli.subcommands:Build', -]
__name__ = 'copr-cli' __version__ = __version__ @@ -40,6 +23,7 @@ __author__ = "Pierre-Yves Chibon" __author_email__ = "pingou@pingoured.fr" __url__ = "http://fedorahosted.org/copr/"
+ setup( name=__name__, version=__version__, @@ -64,7 +48,6 @@ setup( entry_points={ 'console_scripts': [ 'copr-cli = copr_cli.main:main' - ], - 'copr_cli.subcommands': subcommands, + ] }, )
copr-devel@lists.fedorahosted.org