API description

Core

Main API access

class osctiny.osc.Osc(url: str | None = None, username: str | None = None, password: str | None = None, verify: str | None = None, ssh_key_file: Path | str | None = None)

Build service API client

An instance of Osc provides all the extensions and access to the API as attributes, e.g. to get a list of groups use:

instance = Osc(*args, **kwargs)
instance.groups.get_list()
Extensions

Extension

Accessible through attribute

osctiny.extensions.packages.Package

packages

osctiny.extensions.projects.Project

projects

osctiny.extensions.bs_requests.Request

requests

osctiny.extensions.search.Search

search

osctiny.extensions.users.Group

groups

osctiny.extensions.users.Person

users

osctiny.extensions.build.Build

build

osctiny.extensions.comments.Comment

comments

osctiny.extensions.distributions.Distribution

distributions

osctiny.extensions.origin.Origin

origins

osctiny.extensions.attributes.Attribute

attributes

osctiny.extensions.staging.Staging

staging

Parameters:
  • url – API URL of a BuildService instance

  • username – Username

  • password – Password; this is either the user password (ssh_key_file is None) or the SSH passphrase, if ssh_key_file is defined

  • verify – See SSL Cert Verification for more details

  • ssh_key_file – Path to SSH private key file

Raises:

osctiny.errors.OscError – if no credentials are provided

Added in version 0.1.1: The cache parameter and the build extension

Added in version 0.1.8: The comments extension

Added in version 0.2.2: The issues extension

Added in version 0.2.3: The distributions extension

Added in version 0.3.0: The origins extension

Changed in version 0.4.0: Raises an exception when no credentials are provided

Changed in version 0.6.0: Support for 2FA authentication (i.e. added the ssh_key_file parameter and changed the meaning of the password parameter

Changed in version 0.8.0: * Removed the cache parameter * Added the attributes extension

Changed in version 0.9.0: * Added the staging extension

Changed in version 0.10.2: * Deprecated default_connection_retries and default_retry_timeout * Introduced osctiny.utils.session.RetryPolicy

property cookies: RequestsCookieJar

Access session cookies

download(url: str, destdir: Path, destfile: str | None = None, overwrite: bool = False, **params: bytes | str | StringIO | BytesIO | BufferedReader | dict | ObjectifiedElement) Path

Shortcut for a streaming GET request

Parameters:
  • url (str) – Download URL

  • destdir (pathlib.Path) – Destination directory

  • destfile (str) – Target file name. If not specified, it will be taken from the URL

  • overwrite (bool) – switch to overwrite existing downloaded file

  • params – Additional query params

Returns:

absolute path to file or None

Added in version 0.7.0.

get_boolean_params(url: str, method: str) Tuple[str]

Get the actual boolean parameter for url and method

Added in version 0.7.3.

get_objectified_xml(response: Response) ObjectifiedElement

Return API response as an XML object

Changed in version 0.1.6: Allow parsing of “huge” XML inputs

Changed in version 0.2.4: Allow response to be a string

Changed in version 0.8.0: Content moved to osctiny.utils.xml.get_objectified_xml()

handle_params(url: str, method: str, params: bytes | str | StringIO | BytesIO | BufferedReader | dict | ObjectifiedElement) bytes

Translate request parameters to API conform format

Note

The build service does not handle URL-encoded Unicode well. Therefore, parameters are encoded as bytes.

Warning

The build service does not declare its parameters properly and developers do not intend to fix this server-side. If you want to use _boolean_ parameters, make sure to use True and False. If you use 0 or 1 instead, you might receive unexpected results.

Parameters:
  • params – Request parameter

  • url (str) – URL to which the parameters will be sent

  • method (str) – HTTP method to send request

Returns:

converted data ready to be used in HTTP request

Return type:

dict or bytes

Changed in version 0.7.3: Added the url and method parameters

Changed in version 0.9.0: Instances of ObjectifiedElement are accepted for argument params

property parser

Explicit parser instance

Changed in version 0.8.0: Content moved to osctiny.utils.xml.get_xml_parser()

request(url: str, method: str = 'GET', stream: bool = False, data: bytes | str | StringIO | BytesIO | BufferedReader | dict | ObjectifiedElement | None = None, params: bytes | str | StringIO | BytesIO | BufferedReader | dict | ObjectifiedElement | None = None, raise_for_status: bool = True, timeout: int | None = None) Response | None

Perform HTTP(S) request

data is URL-encoded and passed on as GET parameters. If data is a dictionary and contains a key comment, this value is passed on as a POST parameter.

if raise_for_status is True, the used requests framework will raise an exception for occured errors.

Changed in version 0.1.2: Added parameters raise_for_status

Changed in version 0.1.3:

  • Added parameter timeout

  • Transfer data as GET parameters (except for comments and texts)

Changed in version 0.1.5: Retry sending the request, if the remote host disconnects

Added in version 0.1.7: Added parameter params

Changed in version 0.5.0: Added logging of request/response

Parameters:
  • url – Full URL

  • method – HTTP method

  • stream – Delayed access, see Body Content Workflow

  • data – Data to be included as POST parameters in request

  • params – Additional GET parameters to be included in request

  • raise_for_status – See requests.Response.raise_for_status

  • timeout – Request timeout. See Timeouts

Returns:

requests.Response

property session: Session

Session object

Extensions

Attributes extension

Added in version 0.8.0.

class osctiny.extensions.attributes.Attribute(osc_obj: Osc)

Access attribute namespaces and definitions

get_attribute_meta(namespace: str, name: str) ObjectifiedElement

Get meta data for attribute

Parameters:
  • namespace – Namespace name

  • name – Attribute name

Returns:

Objectified XML element

get_namespace_meta(namespace: str) ObjectifiedElement

Get the meta of the namespace

Parameters:

namespace – namespace name

Returns:

Objectified XML element

list_attributes(namespace: str) List[str]

List the attributes available in namespace

Parameters:

namespace – Namespace name

Returns:

List of attribute names

list_namespaces() List[str]

Get a list of all namespaces

Returns:

List of namespace names

Build result extension

class osctiny.extensions.buildresults.Build(osc_obj: Osc)

Osc extension for retrieving build results

cmd(project, cmd, **params)

Execute cmd for project and get response

Added in version 0.6.2.

Parameters:
  • project (str) – Project name

  • cmd (str) – Command to execute

  • params – Additional parameters

download_binary(project, repo, arch, package, filename, destdir, destfile=None, overwrite=False)

Download binary file to disk

Parameters:
  • project – Project name

  • repo – Repository name

  • arch – Architecture name

  • package – Package name

  • filename – File name

  • destdir (pathlib.Path) – Destination directory

  • destfile (str) – Target file name. If not specified, it will be taken from the URL

  • overwrite (bool) – switch to overwrite existing downloaded file

Returns:

Path of downloaded file

Return type:

pathlib.Path

Added in version 0.7.0.

get(project, package=None, repo=None, **params)

Get build infos

If no parameters are supplied, a compact list of build states for all packages in the project are returned.

If a package and/or repo are supplied, an extended list of build results for these particular values is returned.

Parameters:
  • project – Project name

  • package – Package name

  • repo – Repository name

  • params – Additional parameters

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

Added in version 0.1.1.

get_binary(project, repo, arch, package, filename, raw=False)

Get the content of file

Note

This method decodes the content of the file and returns a Python string by default.

Parameters:
  • project – Project name

  • repo – Repository name

  • arch – Architecture name

  • package – Package name

  • filename – File name

  • raw – If True, return a byte string. Otherwise, a string is returned

Returns:

Content of binary file

Return type:

str or bytes

Added in version 0.2.4.

Changed in version 0.7.0: Added the raw parameter

get_binary_list(project, repo, arch, package, **params)

Get a list of built RPMs

Parameters:
  • project – Project name

  • repo – Repository name

  • arch – Architecture name

  • package – Package name

  • params – Additional parameters

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

Added in version 0.1.3.

get_history(project, package, repo, arch='x86_64', **params)

Get build history

Parameters:
  • project – Project name

  • package – Package name

  • repo – Repository name

  • arch – Architecture name

  • params – Additional parameters

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

Added in version 0.5.0.

get_log(project, repo, arch, package)

Get the build log of a package

Parameters:
  • project – Project name

  • repo – Repository name

  • arch – Architecture name

  • package – Package name

Returns:

The package build log file

Return type:

str

Added in version 0.8.0.

get_package_list(project, repo, arch)

Get a list of packages for which build results exist

Parameters:
  • project – Project name

  • repo – Repository name

  • arch – Architecture name

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

Added in version 0.2.4.

get_published_list(project: str, repo: str, arch: str, **params)

Get a list of published binaries in a repository

Deprecated since version 0.12.0: Use osctiny.extensions.published.Published.get_binary_list() instead.

Parameters:
  • project – Project name

  • repo – Repository name

  • arch – Architecture name

  • params – Additional parameters

Returns:

Objectified XML element containing directory entries

Return type:

lxml.objectify.ObjectifiedElement

get_status_and_build_id(project, repo, arch)

Get build status and build ID

Parameters:
  • project – Project name

  • repo – Repository name

  • arch – Architecture name

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

Added in version 0.9.0.

Comments extension

class osctiny.extensions.comments.Comment(osc_obj: Osc)

The BuildService comment(s) API is accessible through this object.

add(obj_type, ids, comment, parent_id=None)

Add a comment to object

Parameters:
  • obj_type (str) – Name of object type (project, package, request)

  • ids (iterable) – IDs of object

  • comment – Comment to be added

  • parent_id – ID of parent comment. Default: None

Returns:

True, if successful.

Raises:

HTTPError – if comment was not saved correctly. The raised exception contains the full response object and API response.

Changed in version 0.3.0: Instead of simply returning the API response, if the comment was not added, an exception is raised.

delete(comment_id)

Delete comment

Added in version 0.1.8.

Parameters:

comment_id – ID of comment

Returns:

True, if successful. Otherwise API response

Return type:

bool or lxml.objectify.ObjectifiedElement

get(obj_type, ids)

Get a list of comments for object

Added in version 0.1.8.

Note

The ids argument will look like this, e.g. for a package: ('project_name', 'package_name').

Parameters:
  • obj_type (str) – Name of object type (project, package, request)

  • ids (iterable) – IDs of object

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

Distributions extension

class osctiny.extensions.distributions.Distribution(osc_obj: Osc)

Osc extension to interact with distributions

Added in version 0.2.3.

get(distribution_id)

Get data of one base distributions hosted on this OBS instance

Parameters:

distribution_id (int) – ID of distribution

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_list(include_remotes=False)

Get list of base distributions

Parameters:

include_remotes (bool) – If True response will include distributions also from remote instances

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

Requests extension

class osctiny.extensions.bs_requests.Request(osc_obj: Osc)

The BuildService request API is accessible through this object.

add_comment(request_id: int | str, comment: str, parent_id: str | None = None) bool

Add a comment to a request

Added in version 0.1.1.

Changed in version 0.1.8: Use internally osctiny.comments.Comment.add

Parameters:
  • request_id – ID of the request

  • comment – Comment to be added

  • parent_id – ID of parent comment. Default: None

Returns:

True, if successful. Otherwise API response

Return type:

bool or lxml.objectify.ObjectifiedElement

cmd(request_id: int | str, cmd: str = 'diff', **kwargs: bytes | str | StringIO | BytesIO | BufferedReader | dict | ObjectifiedElement) ObjectifiedElement | str

Get the result of the specified command

Available commands:

  • diff: Shows the diff of all affected packages.

  • addreview: Assign a user or group to review

  • changereviewstate: Accept/Decline a review

Parameters:
  • request_id – ID of the request

  • cmd – Name of the command

  • view – One of: xml or nothing

  • unified

    ???

  • missingok

    ???

  • filelimit

    ???

  • expand

    ???

  • withissues

    ???

Returns:

plain text

Return type:

str

Changed in version 0.1.3:

  • Added addreview to list of allowed commands

  • Added validation for arguments of command changereviewstate

Deprecated since version 0.7.8:

create(actions: Iterable[Action], reviewers: Iterable[Review] | None = None, description: str | None = None, addrevision: bool = False, ignore_delegate: bool = False, ignore_build_state: bool = False) int

Create a request

Parameters:
  • actions – Actions to be included in request

  • reviewers – Reviewers to be assigned

  • description – Description text

  • addrevision – Ask the server to add revisions of the current sources to the request.

  • ignore_delegate – Enforce a new package instance in a project which has OBS:DelegateRequestTarget set

  • ignore_build_state – Skip the build state check

Returns:

Request ID

Added in version 0.10.0.

Changed in version 0.10.1: Added the description parameter.

get(request_id: int | str, withhistory: bool = False, withfullhistory: bool = False) ObjectifiedElement

Get one request object

Parameters:
  • request_id – ID of the request

  • withhistory (bool) – includes the request history in result

  • withfullhistory (bool) – includes the request and review history in result

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_comments(request_id: int | str) ObjectifiedElement

Get a list of comments for request

Changed in version 0.1.8: Use internally osctiny.comments.Comment.get

Parameters:

request_id – ID of the request

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_list(**params: bytes | str | StringIO | BytesIO | BufferedReader | dict | ObjectifiedElement) ObjectifiedElement

Get a list or request objects

Parameters:

params – see https://build.opensuse.org/apidocs/index#73

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

update(request_id: int | str, **kwargs: bytes | str | StringIO | BytesIO | BufferedReader | dict | ObjectifiedElement) ObjectifiedElement | str

Update request or execute command

Note

In most cases, the API returns an XML response, so this method will try to return an objectified XML element. Otherwise, if parsing fails due to a syntax error, the response body is returned as plain text. In case of all other errors, this method lets the caller handle the exception.

Parameters:
  • request_id – ID of the request

  • kwargs – See Build Service API documentation for accepted keys and values.

Returns:

Response content

Return type:

lxml.objectify.ObjectifiedElement or plain text

Added in version 0.7.8.

Issues extension

class osctiny.extensions.issues.Issue(osc_obj: Osc)

The BuildService issue(-tracker) API is accessible through this object.

Added in version 0.2.2.

get(tracker, name, force_update=False)

Get details for an issue

Parameters:
  • tracker (str) – issue tracker name

  • name (str) – issue name

  • force_update (bool) – If True, BuildService will update the issue details internally prior to returning the response

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_tracker(name)

Get information on one issue tracker

Parameters:

name (str) – issue tracker name

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_trackers()

Get all issue trackers with data

Origin extension

This is a runtime optimized implementation of the Origin Manager.

The intention of this implementation is to quickly yield batch results. In doing so a different logic than in the original OSC plugin is used:

  • If a project inherits a package from another project, the origin is checked for the package in the original project.

  • If the package has received submissions from potential origin projects, only those projects are considered.

  • The first project from the origin configuration (including above limitations) containing the package is considered as origin project.

  • If a project was found and if that project inherits the package, the original project is returned.

Added in version 0.3.0.

class osctiny.extensions.origin.DevelProjects(osc_obj, **kwargs)

Lazy lookup table for package specific development projects

get_devel_projects(*projects)

Find package specific development projects for (maintained) projects

Parameters:

projects (str) – One or more project names

Returns:

Dictionary with development projects per package

Return type:

dict

class osctiny.extensions.origin.Origin(osc_obj)

Query tool to find the origin of packages in maintained projects

Added in version 0.3.0.

property devel_projects

Delayed initialization of the package specific development project dictionary

This dictionary is populated in a lazy/JIT fashion.

Returns:

DevelProjects

property expanded_origins

Expand the projects from the Origin Configuration

This property returns all the expanded origin projects for all projects that have the OSRT:OriginConfig attribute set in build service.

Note

Even if OSRT:OriginConfig explicitly defines a bogus order of projects, e.g.

  • SUSE:SLE-15:Update

  • SUSE:SLE-15-SP1:Update

  • SUSE:SLE-15-SP2:Update

this method will rearrange the projects in a meaningful way, e.g. into:

  • SUSE:SLE-15-SP2:Update

  • SUSE:SLE-15-SP1:Update

  • SUSE:SLE-15:Update

Consider this a workaround for this issue.

Returns:

Dictionary with lists of origin project names for all projects

Return type:

dict

family_sort_key(key)

Provides a numeric key for sorting projects of the same family

Parameters:

key (str) – Project name

Returns:

Numeric value representing the version and priority of projects

Return type:

float

family_sorter(unsorted_list)

Sort consecutive projects of the same family

In case the configuration does not list the projects in a meaningful way, they are sorted now to avoid the need to check the package histories for every package.

Note

This sorter is only allowed to change the order of consecutive projects belonging to the same family.

Consider this a workaround for this issue.

Parameters:

unsorted_list (list of str) – List with project names

Returns:

Generator with sorted list items

Return type:

generator

find_package_origin(package, project, resolve_inheritance=True)

Find the origin project for package in project

This method will return simply None for patchinfo packages and packages with an incident ID as suffix.

Important

When you want to check multiple packages by multiple calls to this method, you should resolve from where project inherits the package for all your (package, project) pairs in advance and set resolve_inheritance to False to speed up the response time.

Parameters:
  • package (str) – Package name

  • project (str) – Project name

  • resolve_inheritance (bool) – Trigger to cause this method to replace project with the project from which package is inherited from

Returns:

Origin project name or None

Return type:

str

get_origin_from_submissions(package, project)

Get potential origin projects from accepted submissions (aka. requests)

This method returns the source project names from accepted requests.

Parameters:
  • package (str) – Target package name

  • project (str) – Target project name

Returns:

Set of source project names

Return type:

set or str

get_project_origin_config(project)

Get the Origin configuration for project

This method returns the decoded YAML data, e.g. for “openSUSE:Leap:15.2:Update”:

{
  "origins": [
    {
      "<devel>": {}
    },
    {
      "SUSE:SLE-15:Update": {
        "maintainer_review_initial": false
      }
    },
    {
      "SUSE:SLE-15-SP1:Update": {
        "maintainer_review_initial": false
      }
    },
    {
      "SUSE:SLE-15-SP2:Update": {
        "maintainer_review_initial": false
      }
    },
    {
      "openSUSE:Leap:15.1:Update": {
        "pending_submission_allow": true
      }
    },
    {
      "openSUSE:Factory": {
        "pending_submission_allow": true
      }
    },
    {
      "*~": {}
    }
  ],
  "fallback-group": "origin-reviewers-maintenance"
}
Parameters:

project (name) – The project name

Returns:

Configuration content

Return type:

dict

is_linked(package, project)

Guess whether a package is a link source (with incident number as suffix).

Parameters:
  • package – Package name to check

  • project – Project name containing the package

Returns:

True, if package name seems to have an incident ID as suffix

list(project)

List all packages in a maintained project and their origin projects

Parameters:

project (str) – Project name

Returns:

Generator of pairs: (‘pkg’, ‘origin’)

Return type:

generator

property maintained_projects

Get the list of maintained projects

Maintained projects are identified by the presence of the OBS:Maintained attribute.

Returns:

Project names

Return type:

List of str

Changed in version 0.4.0: Search maintained projects via the OBS:Maintained attribute and not via the maintenance project.

property maintenance_project

Get the maintenance project

This project is important, because it’s meta can provide the list of maintained projects.

Returns:

Project name or None

Return type:

str or None

Changed in version 0.4.0: Return string instead of XML object

property package_matrix

Delayed initialization of the lookup package matrix.

The matrix is populated in a lazy/JIT fashion.

Returns:

PackageMatrix

class osctiny.extensions.origin.PackageMatrix(osc_obj, expanded_origins, **kwargs)

Lazy lookup matrix for package origins

This matrix collects for every project (provided as key) a dictionary with all allowed origin projects and packages therein. If the origin project inherits the package from another project, this information is available, too.

The matrix is not populated at initialization time. When the matrix for a project is requested for the first, only the corresponding items are populated. Subsequent access to the same project does not trigger new population. Hence “lazy”.

Example:

{
    'openSUSE:Leap:15.2:Update': {
        'SUSE:SLE-15-SP2:Update': {
            # ...
            'zeromq': ['SUSE:SLE-15:Update'],
            'zypper': ['SUSE:SLE-15-SP2:Update', 'SUSE:SLE-15-SP2:GA']
        },
        'SUSE:SLE-15-SP1:Update': {
            'zinnia-tomoe': ['SUSE:SLE-15:GA']
            # ...
        },
        'openSUSE:Factory': {
            # ...
            'zziplib': ['openSUSE:Factory']
        }
    },
    'openSUSE:Leap:15.2': ...
}
Parameters:

Packages extension

class osctiny.extensions.packages.Package(osc_obj: Osc)

Osc extension to interact with packages

add_comment(project, package, comment, parent_id=None)

Add a comment to a package

Changed in version 0.1.8: Use internally osctiny.comments.Comment.add

Parameters:
  • project – name of project

  • package – name of package

  • comment – Comment to be added

  • parent_id – ID of parent comment. Default: None

Returns:

True, if successful. Otherwise API response

Return type:

bool or lxml.objectify.ObjectifiedElement

aggregate(src_project, src_package, tgt_project, tgt_package, publish=True, repo_map=None, no_sources=False)

Aggregate a package to another package

Added in version 0.1.2.

Changed in version 0.2.5: When creating a new aggregate package, the build flag is always enabled.

Parameters:
  • src_project – Name of source project

  • src_package – Name of source package

  • tgt_project – Name of target project

  • tgt_package – Name of target package

  • publish – En-/Disable publishing of aggregated package

  • repo_map (None or dict) – Optional repository mapping

  • no_sources – If True, ignore source packages when copying build results to destination project

Returns:

checkout(project, package, destdir, rev=None, meta=False, expand=False)

Checkout all files and directories of package

Parameters:
  • project – name of project

  • package – name of package

  • destdir – target local directory

  • rev – Package revision to check out

  • meta – Checkout meta files instead

  • expand – If True and the package is a link, download the file from the linked package

Returns:

nothing

Added in version 0.1.1.

Changed in version 0.3.3: Added the parameter expand

Changed in version 0.10.3: The feature to create an osc compatible .osc/ directory structure was removed.

static cleanup_params(**params) dict | str

Prepare query parameters

The build service is inconsistent in its validation of parameters. In most cases it does not complain about excess parameters, in some it complains about unexpected ones.

Parameters:

params – Query parameters

Returns:

The original dictionary of query parameters or a subset of it

Added in version 0.7.4.

Changed in version 0.7.7: Handle more inconsistencies in the API endpoints

cmd(project, package, cmd, **params)

Get the result of the specified command

Available commands:

  • diff: Shows the diff of all affected packages.

  • showlinked: List all package instances linking to this one.

  • instantiate: Instantiate a package container, which is available via project links only so far.

  • release: Releases sources and binaries of that package.

  • unlock: Unlocks a locked package.

  • branch: Create a source link from a package of an existing project.

  • set_flag: Modify or set a defined flag for package

  • createSpecFileTemplate: Create template for RPM SPEC file.

  • commit: Commits package changes to buildservice.

  • collectbuildenv: Creates _buildenv files based on origin package builds.

  • importchannel: Import a kiwi channel file for OBS.

Note

Command diff

The diff command returns plain text, instead of XML, by default! To get XML, pass the view='xml' param.

Parameters:
Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement or str

delete(project, package, force=False, comment=None)

Delete package

Added in version 0.1.2.

Parameters:
  • project – Project name

  • package – Package name

  • force – Delete package even if pending requests exist

  • comment – Optional comment

Returns:

True, if successful. Otherwise API response

Return type:

bool or lxml.objectify.ObjectifiedElement

delete_file(project, package, filename, force=False, comment=None)

Delete package

Added in version 0.10.3.

Parameters:
  • project – Project name

  • package – Package name

  • filename – Name of file

  • force – Delete package even if pending requests exist

  • comment – Optional comment

Returns:

True, if successful. Otherwise API response

Return type:

bool or lxml.objectify.ObjectifiedElement

download_file(project, package, filename, destdir, meta=False, overwrite=False, rev=None, expand=False)

Download a file to directory

Parameters:
  • project – name of project

  • package – name of package

  • filename – name of file

  • destdir – path of directory

  • meta – switch to meta files

  • overwrite – switch to overwrite existing downloaded file

  • rev – Download file from this specific package revision

  • expand – If True and the package is a link, download the file from the linked package

Returns:

absolute path to file or None

Raises:

OSError – if something goes wrong

Added in version 0.1.1: Parameter rev

Changed in version 0.3.3: Added the parameter expand

Changed in version 0.7.0: Moved some logic to osctiny.osc.Osc.download()

exists(project, package, filename=None) bool

Check whether package or file in package exists

Added in version 0.1.2.

Parameters:
  • project – Project name

  • package – Package name

  • filename – Name of file

Returns:

True, if package exists, otherwise False

get_attribute(project, package, attribute=None)

Get one attribute of a package

Parameters:
  • project – name of project

  • package – name of package

  • attribute – name of attribute

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_comments(project, package)

Get a list of comments for package

Added in version 0.1.8: Use internally osctiny.comments.Comment.get

Parameters:
  • project – name of project

  • package – name of package

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_file(project, package, filename, meta=False, rev=None, expand=False)

Get a source file

Downloads a specific file from a package and returns a response object from which the file contents can be read.

Parameters:
  • project – name of project

  • package – name of package

  • filename – name of file

  • meta – switch to meta files

  • rev – Get file from this specific package revision

  • expand – If the package is linked, it typically only contains a _link file. In order to allow retrieval of the linked package instead of a 404 error, set this parameter to ‘1’

Returns:

response

Return type:

requests.Response

Added in version 0.1.1: Parameter rev

Added in version 0.1.11: Parameter expand

get_files(project, package, **params)

List package files

Parameters:
Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_history(project, package, limit=None)

Get history of package

Parameters:
  • project – name of project

  • package – name of package

  • limit – Optional number of history entries to return. If specified, only the last n entries are returned.

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_list(project: str, deleted: bool | None = None, expand: bool = False, **params)

Get packages from project

Added in version 0.1.7: Parameter deleted

Added in version 0.7.0: Parameter expand

Added in version 0.7.4: Parameter params

Changed in version 0.7.6: Changed default value of expand to False

Changed in version 0.10.7: Made the deleted parameter fully optional. It is no longer a boolean flag but really a boolean parameter, so deleted=0 is actually added to the API call.

Parameters:
  • project – name of project

  • deleted – If true, also shows deleted packages instead of the present ones. If False, then deleted=0 is appended to the query explicitly. Default is None, which implies no parameter addition to the query.

  • expand – Include inherited packages and their project of origin

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_meta(project, package, blame=False)

Get package metadata

Note

When blame annotations are requested no XML object can be returned!

Changed in version 0.1.2: Added parameter blame

Parameters:
  • project – name of project

  • package – name of package

  • blame – Show metadata with change annotations

Returns:

Objectified XML element or str

Return type:

lxml.objectify.ObjectifiedElement or str

push_file(project, package, filename, data, comment=None)

Upload a file to package

Parameters:
  • project – Name of project

  • package – Name of package

  • filename – Name of file

  • data (str or open file handle) – content of file

  • comment – Optional comment to use as commit message

Changed in version 0.5.0: Added an optional comment argument to be used as the commit message when writing the file.

set_meta(project, package, title=None, description=None, meta=None, comment=None)

Set package metadata

Note

By setting the meta data package is created, if it does not exist.

Specify title and description to create an XML file with minimum content or provide a complete XML string via meta.

Note

If title or description is given in combination with meta, the existing values in meta will be overwritten.

Added in version 0.1.2.

Changed in version 0.7.8: Added an optional comment argument to be used as commit message

Parameters:
  • project – Project name

  • package – New package name

  • title – Title for meta

  • description – Description for meta

  • meta (str or lxml.objectify.ObjectifiedElement) – New content for meta

  • comment – Optional comment to use as commit message

Returns:

Projects extension

class osctiny.extensions.projects.Project(osc_obj: Osc)

Osc extension to interact with projects

add_comment(project, comment, parent_id=None)

Add a comment to a project

Changed in version 0.1.8: Use internally osctiny.comments.Comment.add

Parameters:
  • project – name of project

  • comment – Comment to be added

  • parent_id – ID of parent comment. Default: None

Returns:

True, if successful. Otherwise API response

Return type:

bool or lxml.objectify.ObjectifiedElement

create(project, metafile=None, title=None, description=None, bugowner=None, maintainer=None, comment=None, force=False)

Edit project meta data or create a new project

If no metafile is provided, a default template is used.

Added in version 0.7.2.

Changed in version 0.7.8: Added an optional comment argument to be used as commit message

Changed in version 0.7.11: Added an optional force argument to allow changing the meta even when IBS reports repository dependency problems

Parameters:
  • project – name of project

  • metafile (str or ElementTree) – Complete metafile

  • title – Title for meta file

  • description – Description for meta file

  • bugowner – Bugowner for meta file

  • maintainer – Maintainer for meta file

  • comment – Optional comment to use as commit message

  • force – Whether to force a meta change, even if there are repo dependency errors

Returns:

True, if successful. Otherwise API response

Return type:

bool or lxml.objectify.ObjectifiedElement

delete(project, force=False, comment=None)

Delete project

Added in version 0.1.2.

Parameters:
  • project – Project name

  • force – Delete project even if subprojects, packages or pending requests for those packages exist

  • comment – Optional comment

Returns:

True, if successful. Otherwise API response

Return type:

bool or lxml.objectify.ObjectifiedElement

delete_attribute(project, attribute)

Delete an attribute of a project

Parameters:
  • project – name of project

  • attribute – name of attribute

Returns:

True, if successful. Otherwise API response

Return type:

bool or lxml.objectify.ObjectifiedElement

exists(project)

Check whether project exists

Added in version 0.1.2.

Parameters:

project – Project name

Returns:

True, if project exists, otherwise False

get_attribute(project, attribute=None)

Get one attribute of a project

Note

Be aware of namespace prefixes.

When specifying the attribute argument make sure to include the namespace prefix and separate both by a colon, e.g. OBS:IncidentPriority.

Parameters:
  • project – name of project

  • attribute – name of attribute

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_comments(project)

Get a list of comments for project

Changed in version 0.1.8: Use internally osctiny.comments.Comment.get

Parameters:

project – name of project

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_config(project, revision=None)

Get project configuration

Added in version 0.7.10.

Parameters:
  • project – name of project

  • revision – optional revision of the config to get

Returns:

The project configuration as string

Return type:

str

get_files(project, directory='', meta=False, rev=None, **kwargs)

List project files

Parameters:
  • project – name of project

  • directory – directory in project

  • meta (bool) – switch for _meta files

  • rev (int) – revision

  • kwargs – More keyword arguments for API call

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

Deprecated since version 0.7.4: Use osctiny.extensions.packages.Package.get_files() or osctiny.extensions.packages.Package.get_list() instead.

The API URL used by this method is (depending on the value of directory) identical to the one used by the above two methods.

get_history(project, meta=True, rev=None, **kwargs)

Get history of project

To get just a particular revision, use the rev argument.

Parameters:
  • project – name of project

  • meta (bool) – Switch between meta and non-meta (normally empty) revision history

  • rev – History revision ID

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_list(deleted=False)

Get list of projects

Parameters:

deleted (bool) – show deleted projects instead of existing

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_meta(project, rev=None)

Get project metadata

Changed in version 0.8.0: Added the rev parameter

Parameters:
  • project – name of project

  • rev (int) – optional revision ID

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

put_meta(project, metafile=None, title=None, description=None, bugowner=None, maintainer=None)

Edit project meta data or create a new project

If no metafile is provided, a default template is used.

Added in version 0.1.5.

Deprecated since version 0.7.2: Use set_meta() instead

Parameters:
  • project – name of project

  • metafile (str or ElementTree) – Complete metafile

  • title – Title for meta file

  • description – Description for meta file

  • bugowner – Bugowner for meta file

  • maintainer – Maintainer for meta file

Returns:

True, if successful. Otherwise API response

Return type:

bool or lxml.objectify.ObjectifiedElement

set_attribute(project, attribute, value)

Set or update an attribute of a project

Parameters:
  • project – project name

  • attribute – attribute name (can include prefix separated by colon)

  • value – attribute value or list of values

Returns:

True, if successful. Otherwise API response

Return type:

bool or lxml.objectify.ObjectifiedElement

Changed in version 0.7.0: Support attributes with multiple values

set_config(project, config=None, comment=None)

Set project config data

Added in version 0.7.10.

Parameters:
  • project – name of project

  • config (str) – Complete configuration to set

  • comment – Optional comment to use as commit message

Returns:

True, if successful. Otherwise, API response

Return type:

bool or lxml.objectify.ObjectifiedElement

set_meta(project, metafile=None, title=None, description=None, bugowner=None, maintainer=None, comment=None, force=False)

Edit project meta data or create a new project

If no metafile is provided, a default template is used.

Added in version 0.7.2.

Changed in version 0.7.8: Added an optional comment argument to be used as commit message

Changed in version 0.7.11: Added an optional force argument to allow changing the meta even when IBS reports repository dependency problems

Parameters:
  • project – name of project

  • metafile (str or ElementTree) – Complete metafile

  • title – Title for meta file

  • description – Description for meta file

  • bugowner – Bugowner for meta file

  • maintainer – Maintainer for meta file

  • comment – Optional comment to use as commit message

  • force – Whether to force a meta change, even if there are repo dependency errors

Returns:

True, if successful. Otherwise API response

Return type:

bool or lxml.objectify.ObjectifiedElement

Persons and groups extension

class osctiny.extensions.users.Group(osc_obj: Osc)

The BuildService group API is accessible through this object.

get(title)

Get details for group title

Parameters:

title – Title/name of the group

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_list(login=None)

Get all groups or all groups containing user login

Parameters:

login – Username to filter for

Return type:

lxml.objectify.ObjectifiedElement

class osctiny.extensions.users.Person(osc_obj: Osc)

The BuildService person API is accessible through this object.

get(userid)

Get details for user userid

Parameters:

userid – Username

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

Search extension

class osctiny.extensions.search.Search(osc_obj: Osc)

Osc extension providing methods for searching

search(path, xpath, **kwargs)

Search for objects in buildservice

Note

Shortcuts

There are shortcut method for the object types project, package and request. These only expect the xpath argument, e.g.:

Osc.search.project("starts-with(@name,'SUSE:Maintenance')")

Note

Pagination

Search results can be paginated using limit and offset, e.g.

Osc.search.project("starts-with(@name,'SUSE:Maintenance')",
                   limit=10, offset=30)
Parameters:
  • path – object type / relative URL

  • xpath – XPath expression to filter results

  • kwargs – Additional parameters to be passed to the underlying API

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

Staging extension

This extension provides access to the staging workflow of OpenBuildService.

Added in version 0.9.0.

class osctiny.extensions.staging.Staging(osc_obj: Osc)

Osc extension for interacting with staging workflows

accept(project: str, staging_project: str) bool

This accepts all staged requests and sets the project state back to ‘empty’

Parameters:
  • project – Project name

  • staging_project – Staging project name

Returns:

True, if successful.

Raises:

HTTPError – if comment was not saved correctly. The raised exception contains the full response object and API response.

add_staged_requests(project: str, staging_project: str, *request_ids: int) bool

Add requests to the staging project.

Parameters:
  • project – Project name

  • staging_project – Staging project name

  • request_ids – Request IDs

Returns:

True, if successful.

Raises:

HTTPError – if comment was not saved correctly. The raised exception contains the full response object and API response.

delete_excluded_requests(project: str, *requests: ExcludedRequest) bool

Remove requests from list of excluded requests

Parameters:
  • project – Project name

  • requests – Requests to exclude with optional reason/description

Returns:

True, if successful.

Raises:

HTTPError – if comment was not saved correctly. The raised exception contains the full response object and API response.

delete_staged_requests(project: str, staging_project: str, *request_ids: int) bool

Delete requests from the staging project

Parameters:
  • project – Project name

  • staging_project – Staging project name

  • request_ids – Request IDs

Returns:

True, if successful.

Raises:

HTTPError – if comment was not saved correctly. The raised exception contains the full response object and API response.

get_backlog(project: str) ObjectifiedElement

List the requests in the staging backlog

Parameters:

project – Project name

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_excluded_requests(project: str) ObjectifiedElement

List the requests excluded from a staging workflow

Parameters:

project – Project name

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_required_checks(project: str, repo: str | None = None, arch: str | None = None) ObjectifiedElement

Get list of required checks

If repo` and arch are specified, required checks from the built repository are returned. If only repo is specified, required checks from the repository are returned. Otherwise, required checks from the project are returned

Parameters:
  • project – (Staging) project name

  • repo – Repository name (optional)

  • arch – Architecture name (optional)

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_staged_requests(project: str, staging_project: str) ObjectifiedElement

List all the staged requests of a staging project

Parameters:
  • project – Project name

  • staging_project – Staging project name

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_staging_projects(project: str) ObjectifiedElement

List all the staging projects of a staging workflow.

Parameters:

project – Project name

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_status(project: str, staging_project: str, requests: bool = False, status: bool = False, history: bool = False) ObjectifiedElement

Get the overall state of a staging project

Parameters:
  • project – Project name

  • staging_project – Staging project name

  • requests – Include statistics about staged, untracked and obsolete requests as well as missing reviews

  • status – Include the overall state

  • history – Include the history of the staging project

Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

get_status_report(project: str, repo: str, build_id: str, arch: str | None = None) ObjectifiedElement

Get list of checks

If arch is specified, status report for built project is retrieved. Otherwise, status report for published project is retrieved.

Parameters:
Returns:

Objectified XML element

Return type:

lxml.objectify.ObjectifiedElement

set_excluded_requests(project: str, *requests: ExcludedRequest) bool

Exclude requests from the staging workflow.

Parameters:
  • project – Project name

  • requests – Requests to exclude with optional reason/description

Returns:

True, if successful.

Raises:

HTTPError – if comment was not saved correctly. The raised exception contains the full response object and API response.

set_required_checks(project: str, checks: List[str], repo: str | None = None, arch: str | None = None) bool

Submit a new or modified required checks list

If repo and arch are specified, required checks of built repository are updated. If only repo is specified, required checks of the repository are updated. Otherwise, required checks of the project are updated.

Parameters:
  • project – (Staging) project name

  • checks – List of check names

  • repo – Repository name (optional)

  • arch – Architecture name (optional)

Returns:

True, if successful.

Raises:

HTTPError – if comment was not saved correctly. The raised exception contains the full response object and API response.

set_status_report(project: str, repo: str, build_id: str, report: CheckReport, arch: str | None = None) bool

Submit a check to a status report

If arch is specified, the status report for built project is set. Otherwise, the status report for published project is set.

Parameters:
Returns:

True, if successful.

Raises:

HTTPError – if comment was not saved correctly. The raised exception contains the full response object and API response.

Models

Common model/type definitions

osctiny.models.E = <lxml.objectify.ElementMaker object>

XML maker without python type annotations

osctiny.models.IntOrString

Int or string with only numbers

alias of int | str

osctiny.models.ParamsType

Acceptable types for HTTP parameters

alias of bytes | str | StringIO | BytesIO | BufferedReader | dict | ObjectifiedElement

Models for requests

Added in version 0.10.0.

class osctiny.models.request.Action(type: ActionType, target: Target, person: Person | None = None, source: Source | None = None)

Request action

asxml() ObjectifiedElement
person: Person | None

Alias for field number 2

source: Source | None

Alias for field number 3

target: Target

Alias for field number 1

type: ActionType

Alias for field number 0

class osctiny.models.request.ActionType(*values)

Request action types as defined in OpenBuildService

ADD_ROLE = 'add_role'
CHANGE_DEVEL = 'change_devel'
DELETE = 'delete'
MAINTENANCE_INCIDENT = 'maintenance_incident'
MAINTENANCE_RELEASE = 'maintenance_release'
RELEASE = 'release'
SET_BUGOWNER = 'set_bugowner'
SUBMIT = 'submit'
class osctiny.models.request.By(*values)

Types by which reviews can be assigned

GROUP = 'by_group'
PACKAGE = 'by_package'
PROJECT = 'by_project'
USER = 'by_user'
class osctiny.models.request.Person(name: str)

Person model for use in actions

asxml() ObjectifiedElement
name: str

Alias for field number 0

class osctiny.models.request.Review(by: By, name: str)

Assign a review

asxml() ObjectifiedElement
by: By

Alias for field number 0

name: str

Alias for field number 1

class osctiny.models.request.Source(project: str, package: str, rev: str | None = None, repository: str | None = None)

Source for an action

asxml() ObjectifiedElement
package: str

Alias for field number 1

project: str

Alias for field number 0

repository: str | None

Alias for field number 3

rev: str | None

Alias for field number 2

class osctiny.models.request.Target(project: str, package: str | None = None, releaseproject: str | None = None, repository: str | None = None)

Target for an action

asxml() ObjectifiedElement
package: str | None

Alias for field number 1

project: str

Alias for field number 0

releaseproject: str | None

Alias for field number 2

repository: str | None

Alias for field number 3

Models for Staging

Added in version 0.9.0.

class osctiny.models.staging.CheckReport(name, required, state, short_description, url)
asdict() Dict[str, str]
asxml() ObjectifiedElement
name: str

Alias for field number 0

required: bool

Alias for field number 1

property required_str: str
short_description: str | None

Alias for field number 3

state: CheckState

Alias for field number 2

url: str | None

Alias for field number 4

class osctiny.models.staging.CheckState(*values)
ERROR = 'error'
FAILURE = 'failure'
PENDING = 'pending'
SUCCESS = 'success'
class osctiny.models.staging.ExcludedRequest(id, description)
asdict() Dict[str, str]
asxml() ObjectifiedElement
description: str | None

Alias for field number 1

id: int

Alias for field number 0

Utilities

Authentication handlers for 2FA

Added in version 0.6.0.

class osctiny.utils.auth.HttpSignatureAuth(username: str, password: str | None, ssh_key_file: Path)

Implementation of the “Signature authentication scheme”

Note

This seems to be a variation of the HTTP Message Signatures specification.

See also the blog post describing the implementation and the reference implementation for osc.

Note

  1. It is recommended to use SSH keys with a passphrase.

  2. If ssh-agent is running, the passphrase is not required at initialization of this class.

  3. If you use an SSH key without passphrase, you don’t need to specify it.

Parameters:
  • username – The username

  • password – Passphrase for SSH key

  • ssh_key_file – Path of SSH key

build_digest_header(method: str, url: str) str

Generate Authentication header

get_auth_header(r: Response) str

Extract the relevant header for Signature authentication

Parameters:

r – Response

Returns:

Header text

handle_401(r: Response, **kwargs) Response

Handle authentication in case of 401

Contents of method copied from requests.auth.HTTPDigestAuth.handle_401() and edited

split_headers(headers: str) List[str]

Split headers parameter from WWW-Authenticate Signature header

Parameters:

headers – Value of the headers parameter

ssh_sign() str

Solve the challenge via SSH signing

osctiny.utils.auth.get_auth_header_from_orignal_response(r: Response) str | None

Extract the “www-authenticate” header from the private original response attribute of a response

Added in version 0.7.6.

osctiny.utils.auth.get_auth_header_from_response(r: Response) str | None

Extract the “www-authenticate” header from the response

Added in version 0.7.6.

osctiny.utils.auth.is_ssh_key_readable(ssh_key_file: Path, password: str | None) Tuple[bool, str | None]

Check whether SSH signing is viable

Parameters:
  • ssh_key_file – Path to SSH key

  • password – Passphrase

Returns:

True, if SSH key is accessible

Added in version 0.6.3.

Changed in version 0.7.8:

  • Moved from HttpSignatureAuth.is_ssh_agent_available

Changed in version 0.7.10:

  • Return the error message, if key cannot be unlocked

Changed in version 0.7.12:

  • Instead of checking whether the key is readable, this function checks whether it can actually be used for signing

osctiny.utils.auth.ssh_sign(message: str, namespace: str, ssh_key_file: Path, password: str | None = None) str

Create an SSH signature for message

Parameters:
  • message – The message/data to sign

  • namespace – The purpose of the signature (see SSH docs for details)

  • ssh_key_file – Path to SSH key

  • password – Passphrase

Returns:

Signature

Added in version 0.7.12.

Exception base classes and utilities

exception osctiny.utils.errors.OscError

Base class for exceptions to be raised by osctiny

osctiny.utils.errors.get_http_error_details(error: HTTPError | Response) str

Extract user-friendly error message from exception

Added in version 0.8.0.

Common base classes

class osctiny.utils.base.ExtensionBase(osc_obj: Osc)

Base class for extensions of the Ocs entry point.

Changelog

Parser and generator for SUSE/OpenBuildService style changelog files.

This parser/generator is a reference implementation of the vc bash script from the openSUSE:Tools build package. See: https://build.opensuse.org/package/show/openSUSE:Tools/build

Added in version 0.1.11.

class osctiny.utils.changelog.ChangeLog

Provider of capabilities to parse and write a .changes file

Parsing and starting a new .changes file should be intuitive. In order to append or edit entries use this recipe:

cl = ChangeLog.parse(path="/path/to/file", generative=False)
cl.entries.append(Entry(...))
cl.write()
entry_factory

A class used to store entry data.

Example: Entry could be extended to provide a read-only property to find bug references inside the entry’s content.

entry_factory

alias of Entry

classmethod parse(path: TextIOBase | str | bytes, generative: bool = True) ChangeLog

Parse a changes file

The changes file to parse may be specified by it’s path or as an already open file handle (aka. subclass of io.TextIOBase).

Use this method to initialize a new instance of ChangeLog like this:

cl = ChangeLog.parse(path="/path/to/file")
for entry in cl.entries:
    print(entry)
Parameters:
  • path (str or open file/stream handle) – If a path is supplied as a string, the file will be opened for reading. If a subclass of io.TextIOBase is provided, this method assumes that it is opened for reading.

  • generative (bool) – If set to True (default), changelog entries are parsed on the fly using a generator. Otherwise all entries are parsed immediately and stored in an iterable.

Returns:

An instance of ChangeLog

Raises:

TypeError – if path is not a string or a subclass of io.TextIOBase

write(path: TextIOBase | str | bytes) None

Write entries to file/stream

This method can write to files and any other stream derived from io.IOBase.

Parameters:

path (str or io.IOBase) – Path to file or open, writable handle

class osctiny.utils.changelog.Entry(timestamp: datetime | None = None, packager: str | None = None, content: str = '')

Representation of a complete changelog entry

timestamp

Timestamp of the entry as a datetime.datetime object. If no value is provided during initialization, datetime.datetime.now() is used instead.

packager

Email and name of the packager. Valid formats are:

  • email@example.com

  • <email@example.com>

  • full name <email@example.com>

content

All lines until the beginning of the next entry; except empty lines at the beginning and end

property formatted_timestamp: str

Return properly formatted timestamp

Returns:

str

now() datetime

Return current UTC timestamp

Returns:

datetime.datetime

osctiny.utils.changelog.is_aware(timestamp: datetime) bool

Check whether timestamp is timezone aware

Parameters:

timestampdatetime.datetime

Returns:

True, if timestamp is tz-aware

Configuration utilities

This module provides a collection of utilities to access the configuration of osc in order to make it easier to create command line tools with OSC Tiny.

Added in version 0.4.0.

osctiny.utils.conf.get_config_path() Path

Return path of osc configuration file

Returns:

Path

Raises:

FileNotFoundError – if no config file found

osctiny.utils.conf.get_credentials(url: str | None = None) Tuple[str, str | None, Path | None]

Get credentials for Build Service instance identified by url

Important

If the osc package is not installed, this function will only try to extract the username and password from the configuration file.

Any credentials stored on a keyring will not be accessible!

Parameters:

url – URL of Build Service instance (including schema). If not specified, the value from the apiurl parameter in the config file will be used.

Returns:

(username, password, SSH private key path)

Raises:

ValueError – if config provides no credentials

Changed in version 0.6.3: If an SSH key is configured, this function will return None instead of a password.

Utilities for cookies

Added in version 0.10.2.

class osctiny.utils.cookies.CookieManager

Simplify handling of cookies

Return LWP cookie string with headers

Get path candidates where to expect a cookie file

classmethod get_jar() LWPCookieJar

Get cookies from a persistent osc cookiejar, if it exists

Changed in version 0.10.2: Converted from function get_cookie_jar

classmethod save_jar(jar: LWPCookieJar) None

Save cookies to a persistent osc cookiejar

Read cookie data from string instead of loading from file

Mapping types

This module provides a collection of mapping types with special behavior.

Added in version 0.3.0.

class osctiny.utils.mapping.LazyOscMappable(osc_obj, **kwargs)

Base class for lazy mappables

To define custom subclasses override the __missing__ method and set the missing key.

Parameters:

osc_obj (osctiny.osc.Osc) – An Osc instance to run queries

class osctiny.utils.mapping.Mappable(**kwargs)

Basic implementation of a dictionary

get(k[, d]) D[k] if k in D, else d.  d defaults to None.
keys() a set-like object providing a view on D's keys
values() an object providing a view on D's values

HTTP Session

Added in version 0.10.2.

class osctiny.utils.session.RetryPolicy(max_attempts: int = 6, backoff_factor: float = 0.125, backoff_max: float = 5.0)

Parameters for governing request retries

backoff_factor: float

Alias for field number 1

backoff_max: float

Alias for field number 2

max_attempts: int

Alias for field number 0

osctiny.utils.session.generate_retry_policy(policy: RetryPolicy) Retry

Generate retry policy for HTTP requests

osctiny.utils.session.generate_session_id(username: str, url: str) str

Generate a session ID unique to the user, remote host, process and thread.

osctiny.utils.session.init_session(auth: AuthBase, policy: RetryPolicy | None = None, verify: str | bool | None = None) Session

Factory to initialize a session object.

XML parsing

Added in version 0.8.0.

osctiny.utils.xml.get_objectified_xml(response: Response | str | bytes) ObjectifiedElement

Return API response as an XML object

Changed in version 0.1.6: Allow parsing of “huge” XML inputs

Changed in version 0.2.4: Allow response to be a string

Changed in version 0.8.0: Carved out from Osc class

Changed in version 0.9.0: Accepts also bytes

Parameters:

response – An API response or XML string

Rtype response:

requests.Response

Returns:

lxml.objectify.ObjectifiedElement

osctiny.utils.xml.get_xml_parser() XMLParser

Get a parser object

Changed in version 0.8.0: Carved out from the Osc class