gerritssh package

Submodules

gerritssh.bancommit module

Implements the ban-commit command

class gerritssh.bancommit.BanCommit(project, commit, option_str='')[source]

Bases: gerritssh.gerritsite.SiteCommand

Obtain a list of all(visible) groups on a site

Parameters:
  • project – The repository name containingg the commit
  • commit – The SHA-1 for the commit to be banned
  • option_str – List of options to pass to the command
execute_on(the_site)[source]
Parameters:the_site – A Site representing the site
Returns:An empty list as the command has no return value

gerritssh.gerritsite module

Representations of a Gerrit site, and the abstract base class for all executable commands.

All sessions with a Gerrit instance begin by creating a Site object and establishing a connection:

import gerritssh as gssh
mysite = gssh.Site('gerrit.exmaple.com').connect()

Commands are executed by creating an instance of a SiteCommand concrete class, and then executing them against the Site object. The following snippet will connect to a site, and then print out a list of all open reviews by project:

import gerritssh as gssh
mysite = gssh.Site('gerrit.example.org').connect()
lsprojects = gssh.ProjectList()
lsprojects.execute_on(mysite)

for p in lsprojects:
    openp = gssh.open_reviews(project=p).execute_on(mysite)
    if not openp:
        continue

    print('\n{0}\n{1}\n'.format(p, '=' * len(p)))
    for r in openp:
        print('{0}\t{1}\n'.format(r.ref, r.summary))

This example also shows both ways of iterating over the results from executing a command. The line for p in lsprojects iterates directly over the ProjectList object, while the line for r in openp: iterates over the list of results returned by calling execute_on

Note

This module was original called simply ‘site’, but that clashed with the built in site module which is automatically imported during initialization. This lead to strange failures during runs of tox that took a little while to debug.

class gerritssh.gerritsite.Site(sitename, username=None, port=None, keyfile=None)[source]

Bases: object

An individual Gerrit site.

An object of this class manages all access, execution of commands, etc.

Parameters:
  • sitename (str) – The top level URL for the site, e.g. ‘gerrit.example.com’
  • username – The optional user to log in as
  • port – The optional port to connect on
  • keyfile – The optional file containing the SSH key to use
Raises:

TypeError if sitename is not a string

Usage:

import gerritssh
try:
    mysite = gerritssh.Site('gerrit.example.com').connect()
    msg = 'Connected to {}, running Gerrit version {}'
    print(msg.format(mysite.site, mysite.version)
except gerritssh.SSHConnectionError:
    print('Failed to connect to site '+mysite.site)
connect()[source]

Establish an SSH connection to the site

Returns:self to allow chaining
Raises:SSHConnectionError if it is not possible to connect to the site
connected[source]

Indicates if there is a connection active.

copy()[source]

Construct an unconnected copy of this Site.

This can be used to create additional Site instances from one which has already been initialized. An obvious use would be to open multiple connections to the same site, from a point in the code which is not aware of the initial values used to identify the Gerrit instance.

for example:

# In the command line parsing module
site = gerritssh.Site(sitename, username, port).connect()
...

# In another module:
def new_connection(asite):
    return asite.copy().connect()

This method is aliased by __copy__ and __deepcopy__ and allows Site objects to be safely used with copy.copy() and copy.deepCopy()

disconnect()[source]

Terminate the connection to the site

Returns:self to allow chaining
execute(cmd)[source]

Execute a command and return the results

Parameters:cmd – The command to execute as either a SiteComand object, or a string. If a SiteCommand object is passed in, double-dispatch is used to evaluate the command. Otherwise, the string is treated as a valid command string and executed directly.
Returns [str]:A list of stripped strings containing the output of the command.
Raises:InvalidCommandError if the cmd object does not report a valid command
Raises:SSHConnectionError if there is no current connection to the site
Raises:CalledProcessError if the command returns an error
site[source]

The original site name provided to the constructor

This needs to be an immutable attribute of the instance once it is created,hence the definition of a ‘read-only’ property.

version[source]

After connection, provides the version of Gerrit running on the site.

Returns:A semantic_version Version object containing the values extracted from the response to a ‘gerrit version’ command.

Before connecting, or if a valid version number can not be found in the response from Gerrit, it has the value ‘0.0.0’.

This needs to be an immutable attribute of the instance once it is created,hence the definition of a ‘read-only’ property.

version_in(constraint)[source]

Does the site’s version match a constraint specifier.

Client’s are free to roll their own tests, but this method makes it unnecessary for them to actually import the semantic_version module directly.

Parameters:constraint (str) –

A requirement specification conforming to the Semantic Version package’s documentation at

http://pythonhosted.org/semantic_version/#requirement-specification

Returns:True if the site’s version satisfies the requirement.
Raises:SSHConnectionError if there is no active connection
Usage::
s=Site(‘example.gerrit.com’).connect() # Check that the site is running Gerrit 2.5 or later s.version_in(‘>=2.5’) # Check that the site is running 2.6, 2.7, or 2.8 s.version_in(‘>=2.6,<2.9’)
exception gerritssh.gerritsite.SSHConnectionError[source]

Bases: gerritssh.GerritsshException

Raised when a Site object fails to connect via SSH, or when a method is called on an unconnected site which requires a connection.

exception gerritssh.gerritsite.InvalidCommandError[source]

Bases: gerritssh.GerritsshException

Raised when an attempt is made to execute a BaseCommand object.

class gerritssh.gerritsite.SiteCommand(cmd_supported_in, option_set, option_str)[source]

Bases: abc.newbase

Base class for a command to be executed against a Site

This is not meant to be used directly by clients. Instead is allows for duck-typing of sub-classes representing the various Command Line tools supported by Gerrit. Clients can use this to support commands which are missing from the release version of gerritssh or to create macro commands.

The key method to override is execute_on() which uses the provided Site object to actually implement the command. The method returns its results, usually as an iterable. The parameters for the command are meant to be provided to the constructor of the concrete class.

On completion, the execute_on method should store its results in self._results as an iterable object, to allow iteration over the object.

The constructor creates a parser and parses the provided options string, storing the results in self._parsed_options.

For example, a minimal class to represent the ls-projects command, with the response in JSON format (on a site which supports it) might declare the method as follows:

class JSONProjects(SiteCommand):
    def __init__(self):
        super(JSONProjects,self).__init__()

    def execute_on(self, site):
        self._results = site.execute('ls-projects')
        return self._results

and be used thus:

site=Site('gerrit.example.com').connect()
cmd=JSONProjects()
projects = cmd.execute_on(site)

or, the command object can be passed to the site (useful in building macro operations):

site=Site('gerrit.example.com').connect()
cmd=JSONProjects()
projects = site.execute(cmd)

Either way, providing the SiteCommand class sets _results properly, the caller can then iterate over the results in two ways. By directly iterating over the returned value:

projects = site.execute(cmd)
for p in projects:
    pass

or, by iterating over the command object itself:

site.execute(cmd) # or cmd.execute_on(site)
for p in cmd:
    pass
Parameters:
  • cmd_supported_in

    The semantic-version compliant version specification defining which Gerrit versions support the command.

    If not specified, or specified as None, defaults to ‘>=2.4’

  • option_set

    An OptionSet instance defining the options supported by the command

    If not specfied, or given as None, no options will be parsed. You can not provide an option_str argument without an OptionSet.

  • option_str

    The options to be parsed and passed to the Gerrit site.

    Defaults to ‘’ if omitted or given as None.

Raises:

TypeError if option_set is not an OptionSet instance

Raises:

ValueError if option_str is specified without an option_set

Raises:

SystemExit if the option_str fails to parse

check_support_for(site)[source]

Validate that the provided site supports the command and all provided options.

Parameters:site – A connected Site instance
Raises:NotImplementedError If the command or one of the options are unsupported on the site.
execute_on(the_site)[source]

Execute the command on the given site

This method must be overridden in concrete classes, and thus the base class implementation is guaranteed to raise an exception.

Raises:TypeError
results[source]

Results from the most recent execution

static text_to_json(text_or_list)[source]

Convert one or more JSON strings to a list of dictionaries.

Every string is split and stripped (via text_to_list()) before decoding. All empty strings (or substrings) are ignored.

Parameters:text_or_list – Either a single string, or a list of strings to be interpreted as JSON.
Returns [dict]:A list of dictionaries, one per string, produced by interpreting each string JSON.
Raises:TypeError if text_or_list` is not one or more strings or if one of the strings can’t be decoded as valid JSON.
static text_to_list(text_or_list, nonempty=False)[source]

Split a single string containing embedded newlines into a list of trimmed strings

Useful for cleaning up multi-line output from commands. Note that a list of strings (perhaps the output from multiple commands) will be flattened to a single list.

Parameters:
  • text_or_list (str) – Either a string with embedded newlines, or a list or tuple of strings with embedded newlines.
  • nonempty (bool) – If true, all empty lines will be removed from the output.
Returns [str]:

List of stripped strings, one string per embedded line.

Raises:

TypeError if text_or_list contains anything other than strings.

Usage::
>>> SiteCommand.text_to_list('a\n \nb')
['a', '', 'b']
>>> SiteCommand.text_to_list('a\n \nb\n', True)
['a', 'b']
>>> SiteCommand.text_to_list(['a\nb','c\nd'])
['a','b','c','d']

gerritssh.lsgroups module

Implements the ls-groups command

class gerritssh.lsgroups.ListGroups(option_str='')[source]

Bases: gerritssh.gerritsite.SiteCommand

Obtain a list of all(visible) groups on a site

Parameters:option_str – List of options to pass to the command
execute_on(the_site)[source]
Parameters:the_site – A Site representing the site to search
Returns:A list of group names, with possibly more information if the verbose option is specified.

gerritssh.lsmembers module

Implements the ls-groups command

class gerritssh.lsmembers.ListMembers(group, option_str='')[source]

Bases: gerritssh.gerritsite.SiteCommand

Obtain a list of all members of a given group

Parameters:
  • group – The group name
  • option_str – List of options to pass to the command
Raises:

SystemExit if the option string fails to parse.

Raises:

ValueError if the group is not provided

Raises:

AttributeError if the group is not a string

execute_on(the_site)[source]
Parameters:the_site – A Site representing the site to search
Returns:A list of dictionaries, one per member, with the keys id, username, fullname, and email.
Raises:NotImplementedError If the site does not support the command, or a specified option
Raises:InvalidGroupError if the command returns an error line
exception gerritssh.lsmembers.InvalidGroupError[source]

Bases: gerritssh.GerritsshException

gerritssh.lsprojects module

Miscellaneous SiteCommand classes for simple commands

class gerritssh.lsprojects.ProjectList(option_str='')[source]

Bases: gerritssh.gerritsite.SiteCommand

Obtain a list of all(visible) projects on a site

Parameters:option_str – List of options to pass to the command
execute_on(the_site)[source]
Parameters:
  • the_site – A Site representing the site to search
  • list_all – Indicates whether to list all types of project
Returns:

A list of Review objects

gerritssh.query module

Commands for querying code review objects on a Gerrit Site

Specifically, the Query command encapsulates the ‘query’ command line utility.

Some common queries are provided in the form of functions which return a prepared Query object. For example, open_reviews reviews a Query prepared to return a complete list of all open code reviews, optionally restricted to a single project:

import gerritssh
s = gerritssh.Site('gerrit.example.com').connect()
r = gerritssh.open_reviews('myproject').execute_on(s)

Following the PEP8 naming conventions, methods which return prepared Query objects will have names in all lowercase. Classes which represent more complex queries will have CamelCase names.

The ‘more complex’ distinction may be necessary if, for example, variants of a command are supported only in specific versions of Gerrit.

class gerritssh.query.Query(option_str='', query='', max_results=0)[source]

Bases: gerritssh.gerritsite.SiteCommand

Command to execute queries on reviews

Parameters:
  • option_str

    One or more supported options to be passed to the command

    note:In order to ensure that the necessary information is returned to allow creation of the Review objects, many of the options will be overridden by execute_on. The following will always be sent:
    • –current-patch-set
    • –patch-sets
    • –all-approvals
    • –dependencies
    • –commit-message
    • –format JSON
  • query – arguments to the query commands, e.g. ‘status:abandoned owner:self’
  • max_results – limit the result set to the first ‘n’. If not given, all results are returned. This may require multiple commands being sent to the Gerrit site, as Gerrit instances often have a built-in limit to the number of results it returns (often around 500).
execute_on(the_site)[source]

Perform a Gerrit query command.

Parameters:the_site – A Site object on which to execute the command
Returns:A list of GerritReview objects converted from returned JSON
gerritssh.query.open_reviews(project=None, branch=None, max_results=0)[source]

Query for all open reviews on a site, optionally restricted to a single project and/or branch.

Parameters:
  • project – If specified, limits the search to a specific project
  • branch – If specified, limits the search to a specific branch
  • max_results – Limit the result set to the first ‘n’. A value of zero (the default) results in all possible results being returned,
Returns:

A list of Review objects

gerritssh.query.merged_reviews(project=None, branch=None, max_results=0)[source]

Query for all merged reviews on a site, optionally restricted to a single project and/or branch.

Parameters:
  • project – If specified, limits the search to a specific project
  • branch – If specified, limits the search to a specific branch
  • max_results – Limit the result set to the first ‘n’. A value of zero (the default) results in all possible results being returned,
Returns:

A list of Review objects

gerritssh.query.abandoned_reviews(project=None, branch=None, max_results=0)[source]

Query for all abandoned reviews on a site, optionally restricted to a single project and/or branch.

Parameters:
  • project – If specified, limits the search to a specific project
  • branch – If specified, limits the search to a specific branch
  • max_results – Limit the result set to the first ‘n’. A value of zero (the default) results in all possible results being returned,
Returns:

A list of Review objects

gerritssh.review module

Classes to represent a Gerrit code review and its patch sets

Typically, objects of these classes are created by executing Query operations. There is little obvious use for a bare Review or Patchset object.

Both classes override __getattr__ to provide acees to the underling raw JSON. Thus, instead of:

ref = somepatchset.raw['ref']

one can simply do:

ref = somepatchset.ref

It also obviates the need to declare many properties that simply return a field, without needing any manipulation.

However, some properties such as the patchset number, are defined as explicit properties to allow conversion to a more natural type.

As a note for contributors, it might seem to make sense to move these classes into the query module. But it is not difficult to envisage other modules which operate solely on collections of Review or Patchset objects, and do not themselves need to be coupled to the gerritsite or query modules.

Safe for: from review import *

class gerritssh.review.Review(raw)[source]

Bases: object

A single code review, containing all patchsets

Parameters:raw – A dict() representing the raw JSON response from Gerrit
Raises:TypeError if raw is not a dictionary

Other than in initialization, this class is meant to be read-only so all instance variables are declared with double leading underscores and provided as properties with getters only

SHA1[source]

SHA1 for the latest Patchset

age[source]

How old is the review as a timedelta

author[source]

Author of the review.

created_on[source]

When the review was created

highest_patchset[source]

The Patchset object for the current patch set

highest_patchset_number[source]

Number of the latest Patch set in the Review

host[source]

The Gerrit host name, e.g. review.example.com

last_updated_on[source]

When was the review last updated

merged[source]

Has the change been merged

merged_on[source]

When was the review merged. :returns: None if not merged

number[source]

The review number a an integer

patchsets[source]

List of Patch sets for this Review

raw[source]

The raw JSON received from Gerrit

ref[source]

The REF string for the review (REFS/CHANGES/...)

repo_name[source]

The name of the repository (including folders)

summary[source]

Summary line of the commit message

class gerritssh.review.Patchset(review, raw)[source]

Bases: object

A single patch set within a GerritReview

Parameters:
  • review – The enclosing Review object
  • raw – The raw JSON extracted from the Review details
Raises:

TypeError if review is not a Review object, or if raw is not a dictionary.

Other than in initialization, this class is meant to be read-only so all instance variables are declared with double leading underscores and provided as properties with getters only.

A library user is not expected to create instances of this class directly. They are created as part of a Review object when processing a response from Gerrit.

author[source]

Author of the Patchset

Returns:(str) The uploader’s name if available, else their user name.
created_on[source]

When was the Patchset created

Returns:(datetime) The date and time the patchset was created
number[source]

The patchset number as an integer rather than a string

raw[source]

The raw JSON returned from Gerrit

Returns:(dict) The keys and values returned from Gerrit.

Module contents

exception gerritssh.GerritsshException[source]

Bases: exceptions.Exception

Base class for each of the package’s exceptions.