Hi,

I try to create a repository via the web API with the attached python script.
It seems that reviewboard complains about the value I used for the tool 
parameter (2). I also tried "Git" but an integer is required. I got the 2 from 
the ID column of the scmtools_tool table. Is that not correct?


Below is the output of the script:

---
[david@katze RB Script]$ ./create_repo.py nepomukannotation
DEBUG - Establishing connection
DEBUG - request body: 
name=nepomukannotation&path=/var/git/nepomukannotation/.git&mirror_path=git://anongit.kde.org/nepomukannotation&bug_tracker=http://bugs.kde.org/show_bug.cgi?id=%s&tool=2
DEBUG - Sending create repo request
{u'body': u'{"fields": {"tool": ["This is not a valid SCMTool"]}, "stat": 
"fail", "err": {"msg": "One or more fields had errors", "code": 105}}', 
u'headers': {'status': '400', 'content-length': '131', 'via': '1.1 varnish', 
'content-language': 'en-us', 'set-cookie': 
'rbsessionid=cc9d61fbd49bb791c8a7a0b68647b4c1; expires=Mon, 12-Mar-2012 
11:24:32 GMT; Max-Age=31536000; Path=/', 'age': '0', 'expires': 'Sun, 13 Mar 
2011 11:24:32 GMT', 'vary': 'Accept,Cookie,Accept-Language', 'server': 
'Apache/2.2.14 (Ubuntu)', 'last-modified': 'Sun, 13 Mar 2011 11:24:32 GMT', 
'connection': 'keep-alive', 'x-varnish': '1701373475', 'etag': 
'"ac5c7a82e994cf5e4c126782aa2b7eac"', 'cache-control': 'max-age=0', 'date': 
'Sun, 13 Mar 2011 11:24:32 GMT', 'content-type': 'application/json'}}
ERROR - An error occurred while accessing Reviewboard.
ERROR - One or more fields had errors
[david@katze RB Script]$ 
---

Any hints what I'm doing wrong here?

Best regards,

David

-- 
Want to help the Review Board project? Donate today at 
http://www.reviewboard.org/donate/
Happy user? Let us know at http://www.reviewboard.org/users/
-~----------~----~----~----~------~----~------~--~---
To unsubscribe from this group, send email to 
reviewboard+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/reviewboard?hl=en
#!/usr/bin/python -W ignore::DeprecationWarning
# -*- coding: utf-8 -*-

#   Copyright 2011 Luca Beltrame <ei...@heavensinferno.net>
#   Copyright 2011 David Solbach <d...@vidsolbach.de>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License, under
#   version 2 of the License, or (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details
#
#   You should have received a copy of the GNU General Public
#   License along with this program; if not, write to the
#   Free Software Foundation, Inc.,
#   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import json
import logging
import sys
import os
import urllib
import urlparse

from rest_client import Connection

# Basic constants

REVIEWBOARD_URL = "http://testrb.vidsolbach.de";
DEFAULT_LEVEL = logging.DEBUG


def setup_logger():

    """Setup a logging instance to be used for error reporting."""

    logger = logging.getLogger("reviewboard")
    handler = logging.StreamHandler(sys.stdout)
    formatter = logging.Formatter("%(levelname)s - %(message)s")
    handler.setFormatter(formatter)
    logger.addHandler(handler)

def read_credentials():

    """Read username and password from a file.

    The file should contain a single line in the form "username:password".

    Return:
        A (username, password) tuple.

    """

    credential_file = os.getenv('HOME') + "/reviewboard-credentials"
    with open(credential_file) as handle:
        credentials = handle.readline().strip()
        username, password = credentials.split(":")

    return username, password

def create_repository(name):

    """Create a repository entry on Reviewboard.

    The script assumes, that the repository has already been cloned in /var/git/.

    Username and passwords are read from a local file, to prevent hardcoding in
    the code. Errors are handled with a logger, ranging from critical (JSON
    decoding errors) to error (when Reviewboard answers with an error)

    Parameters:
        - name - the repository name
    """

    reviewboard_url = urlparse.urljoin(REVIEWBOARD_URL, "api")

    username, password = read_credentials()

    # Logger is a singleton
    logger = logging.getLogger("reviewboard")
    logger.setLevel(DEFAULT_LEVEL)

    logger.debug("Establishing connection")
    connection = Connection(reviewboard_url, username=username,
                            password=password)
                            
    path = "/var/git/%s/.git" % (name)
    mirror_path = "git://anongit.kde.org/%s" % (name)
    bug_tracker = "http://bugs.kde.org/show_bug.cgi?id=%s";
    tool = 2 # this is an internal RB ID for the GIT SCM. Viewable in the admin interface
                            
    # HTML-encode the message to avoid unpleasant side effects
    createrepo_request_body = "name=%s&path=%s&mirror_path=%s&bug_tracker=%s&tool=%d" % (name, path, mirror_path, bug_tracker, tool)
    logger.debug("request body: %s" % createrepo_request_body)
	
    # Resource for creating repos
    repo_resource = "/repositories"
    
    # Post a message announcing the submission
    logger.debug("Sending create repo request")
    response = connection.request_post(repo_resource,
                                       body="%s" %
                                       createrepo_request_body)
    try:
        print response
        response = json.loads(response["body"])
    except ValueError:
        logging.critical("Malformed response received from Reviewboard."
                         " Contact the KDE sysadmins.")
        return

    if response["stat"] != "ok":
        logger.error("An error occurred while accessing Reviewboard.")
        logger.error(response["err"]["msg"])
        return

    # Change the actual status
    logger.debug("Sending status")
    response = connection.request_put(submit_resource,
                                      body="status=submitted")

    try:
        response = json.loads(response["body"])
    except ValueError:
        logging.critical("Malformed response received from Reviewboard."
                         " Contact the KDE sysadmins.")
        return

    if response["stat"] != "ok":
        logger.error("An error occurred while accessing Reviewboard.")
        logger.error(response["err"]["msg"])
        return

    logger.info("Review request %s successfully closed." % review_id)

def usage():

    print "Usage: create_repo <name>"
    sys.exit(0)

def main():

    setup_logger()

    if len(sys.argv) != 2:
        logger = logging.getLogger("reviewboard")
        logger.setLevel(DEFAULT_LEVEL)
        # Only output information when we're using debug
        logger.debug(sys.argv)
        usage()

    name = sys.argv[1]
    
    create_repository(name)
    sys.exit(0)

if __name__ == '__main__':
    main()

Reply via email to