INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Trim the cache down to max_size by evicting the least-recently-used entries.
def _purge(self): """ Trim the cache down to max_size by evicting the least-recently-used entries. """ if len(self.cache) <= self.max_size: return cache = self.cache refcount = self.refcount queue = self.queue max_size = self.max_size ...
Start worker process. Fork and start twisted application described in basedir buildbot.tac file. Print it's log messages to stdout for a while and try to figure out if start was successful. If quiet or nodaemon parameters are True, or we are running on a win32 system, will not fork and log will no...
def startWorker(basedir, quiet, nodaemon): """ Start worker process. Fork and start twisted application described in basedir buildbot.tac file. Print it's log messages to stdout for a while and try to figure out if start was successful. If quiet or nodaemon parameters are True, or we are runni...
Calculates the width of the specified text.
def textwidth(self, text, config): """Calculates the width of the specified text. """ surface = cairo.SVGSurface(None, 1280, 200) ctx = cairo.Context(surface) ctx.select_font_face(config['font_face'], cairo.FONT_SLANT_NORMAL, ...
Renders an SVG from the template, using the specified data
def makesvg(self, right_text, status=None, left_text=None, left_color=None, config=None): """Renders an SVG from the template, using the specified data """ right_color = config['color_scheme'].get(status, "#9f9f9f") # Grey left_text = left_text or config['left_text'] ...
This formats the results of the database operations for printing back to the caller @param op: operation to perform (add, remove, update, get) @type op: string @param results: results from db queries in perspective_commandline @type results: list @returns: string conta...
def formatResults(self, op, results): """ This formats the results of the database operations for printing back to the caller @param op: operation to perform (add, remove, update, get) @type op: string @param results: results from db queries in perspective_commandline ...
A method to allow posting data that is not generated and stored as build-data in the database. This method generates the `stats-yield-data` event to the mq layer which is then consumed in self.postData. @params data_name: (str) The unique name for identifying this data. post_dat...
def yieldMetricsValue(self, data_name, post_data, buildid): """ A method to allow posting data that is not generated and stored as build-data in the database. This method generates the `stats-yield-data` event to the mq layer which is then consumed in self.postData. @params ...
This performs the requested operations from the `buildbot user` call by calling the proper buildbot.db.users methods based on the operation. It yields a deferred instance with the results from the database methods. @param op: operation to perform (add, remove, update, get) @type...
def perspective_commandline(self, op, bb_username, bb_password, ids, info): """ This performs the requested operations from the `buildbot user` call by calling the proper buildbot.db.users methods based on the operation. It yields a deferred instance with the results from the dat...
helper to get a direct interface to _Plugins
def get_plugins(namespace, interface=None, check_extras=True, load_now=False): """ helper to get a direct interface to _Plugins """ return _DB.add_namespace(namespace, interface, check_extras, load_now)
register given namespace in global database of plugins in case it's already registered, return the registration
def add_namespace(self, namespace, interface=None, check_extras=True, load_now=False): """ register given namespace in global database of plugins in case it's already registered, return the registration """ tempo = self._namespaces.get(namespace) i...
get information about all plugins in registered namespaces
def info(self): """ get information about all plugins in registered namespaces """ result = dict() for name, namespace in self._namespaces.items(): result[name] = namespace.info_all() return result
Register a perspective factory PFACTORY to be executed when a PB connection arrives on PORTSTR with USERNAME/PASSWORD. Returns a Registration object which can be used to unregister later.
def register(self, portstr, username, password, pfactory): """ Register a perspective factory PFACTORY to be executed when a PB connection arrives on PORTSTR with USERNAME/PASSWORD. Returns a Registration object which can be used to unregister later. """ # do some basic ...
Helper method for testing; returns the TCP port used for this registration, even if it was specified as 0 and thus allocated by the OS.
def getPort(self): """ Helper method for testing; returns the TCP port used for this registration, even if it was specified as 0 and thus allocated by the OS. """ disp = self.pbmanager.dispatchers[self.portstr] return disp.port.getHost().port
Start shutting down
def gracefulShutdown(self): """Start shutting down""" if not self.bf.perspective: log.msg("No active connection, shutting down NOW") reactor.stop() return log.msg( "Telling the master we want to shutdown after any running builds are finished") ...
Start a timer to detect if the connection is hung.
def _startHungConnectionTimer(self): """ Start a timer to detect if the connection is hung. """ def hungConnection(): self._hung_callback() self._hungConnectionTimer = None self.transport.loseConnection() self._hungConnectionTimer = self._react...
Return a boolean whether the lock is available for claiming
def isAvailable(self, requester, access): """ Return a boolean whether the lock is available for claiming """ debuglog("%s isAvailable(%s, %s): self.owners=%r" % (self, requester, access, self.owners)) num_excl, num_counting = self._claimed_excl, self._claimed_counting ...
Claim the lock (lock must be available)
def claim(self, owner, access): """ Claim the lock (lock must be available) """ debuglog("%s claim(%s, %s)" % (self, owner, access.mode)) assert owner is not None assert self.isAvailable(owner, access), "ask for isAvailable() first" assert isinstance(access, LockAccess) ...
Release the lock
def release(self, owner, access): """ Release the lock """ assert isinstance(access, LockAccess) debuglog("%s release(%s, %s)" % (self, owner, access.mode)) if not self._removeOwner(owner, access): debuglog("%s already released" % self) return self._tryW...
Fire when the lock *might* be available. The caller will need to check with isAvailable() when the deferred fires. This loose form is used to avoid deadlocks. If we were interested in a stronger form, this would be named 'waitUntilAvailable', and the deferred would fire after the lock ha...
def waitUntilMaybeAvailable(self, owner, access): """Fire when the lock *might* be available. The caller will need to check with isAvailable() when the deferred fires. This loose form is used to avoid deadlocks. If we were interested in a stronger form, this would be named 'waitUntilAvai...
Get an L{AsyncLRUCache} object with the given name. If such an object does not exist, it will be created. Since the cache is permanent, this method can be called only once, e.g., in C{startService}, and it value stored indefinitely. @param cache_name: name of the cache (usually the na...
def get_cache(self, cache_name, miss_fn): """ Get an L{AsyncLRUCache} object with the given name. If such an object does not exist, it will be created. Since the cache is permanent, this method can be called only once, e.g., in C{startService}, and it value stored indefinitely....
Responds to events and starts the build process different implementations can decide on what methods they will accept :arguments: request the http request object
def render_POST(self, request): """ Responds to events and starts the build process different implementations can decide on what methods they will accept :arguments: request the http request object """ try: d = self.getAndSubmitC...
create and cache the handler object for this dialect
def makeHandler(self, dialect): """create and cache the handler object for this dialect""" if dialect not in self.dialects: m = "The dialect specified, '{}', wasn't whitelisted in change_hook".format(dialect) log.msg(m) log.msg( "Note: if dialect is 'b...
Take the logic from the change hook, and then delegate it to the proper handler We use the buildbot plugin mechanisms to find out about dialects and call getChanges() the return value is a list of changes if DIALECT is unspecified, a sample implementation is provided
def getChanges(self, request): """ Take the logic from the change hook, and then delegate it to the proper handler We use the buildbot plugin mechanisms to find out about dialects and call getChanges() the return value is a list of changes if DIALECT is unspec...
We need to convert a dictionary where keys and values are bytes, to unicode strings. This happens when a Python 2 worker sends a dictionary back to a Python 3 master.
def decode(data, encoding='utf-8', errors='strict'): """We need to convert a dictionary where keys and values are bytes, to unicode strings. This happens when a Python 2 worker sends a dictionary back to a Python 3 master. """ data_type = type(data) if data_type == bytes: return bytes2...
The login process failed, most likely because of an authorization failure (bad password), but it is also possible that we lost the new connection before we managed to send our credentials.
def failedToGetPerspective(self, why): """The login process failed, most likely because of an authorization failure (bad password), but it is also possible that we lost the new connection before we managed to send our credentials. """ log.msg("ReconnectingPBClientFactory.failedTo...
Parse the <master> argument. @param master_arg: the <master> argument to parse @return: tuple of master's host and port @raise UsageError: on errors parsing the argument
def validateMasterArgument(self, master_arg): """ Parse the <master> argument. @param master_arg: the <master> argument to parse @return: tuple of master's host and port @raise UsageError: on errors parsing the argument """ if master_arg[:5] == "http:": ...
A kind of create_or_update, that's between one or two queries per call
def setBuildProperty(self, bid, name, value, source): """ A kind of create_or_update, that's between one or two queries per call """ def thd(conn): bp_tbl = self.db.model.build_properties self.checkLength(bp_tbl.c.name, name) self.checkLength(bp_tbl.c.source, ...
Return a decoder function. If cfg is a string such as 'latin-1' or u'latin-1', then we return a new lambda, s.decode(). If cfg is already a lambda or function, then we return that.
def _decoderFromString(cfg): """ Return a decoder function. If cfg is a string such as 'latin-1' or u'latin-1', then we return a new lambda, s.decode(). If cfg is already a lambda or function, then we return that. """ if isinstance(cfg, (bytes, str)): ...
Easy to patch in tests.
def _isRepositoryReady(self): """Easy to patch in tests.""" return os.path.exists(os.path.join(self._absWorkdir(), '.hg'))
Return a deferred for (date, author, files, comments) of given rev. Deferred will be in error if rev is unknown.
def _getRevDetails(self, rev): """Return a deferred for (date, author, files, comments) of given rev. Deferred will be in error if rev is unknown. """ args = ['log', '-r', rev, os.linesep.join(( '--template={date|hgdate}', '{author}', "{files % '{file...
Have mercurial init the workdir as a repository (hg init) if needed. hg init will also create all needed intermediate directories.
def _initRepository(self): """Have mercurial init the workdir as a repository (hg init) if needed. hg init will also create all needed intermediate directories. """ if self._isRepositoryReady(): return defer.succeed(None) log.msg('hgpoller: initializing working dir f...
Return a deferred to set current revision in persistent state.
def _setCurrentRev(self, rev, branch='default'): """Return a deferred to set current revision in persistent state.""" self.lastRev[branch] = str(rev) return self.setState('lastRev', self.lastRev)
Return a deferred for branch head revision or None. We'll get an error if there is no head for this branch, which is probably a good thing, since it's probably a misspelling (if really buildbotting a branch that does not have any changeset yet, one shouldn't be surprised to get errors)
def _getHead(self, branch): """Return a deferred for branch head revision or None. We'll get an error if there is no head for this branch, which is probably a good thing, since it's probably a misspelling (if really buildbotting a branch that does not have any changeset yet, one...
Send info about pulled changes to the master and record current. HgPoller does the recording by moving the working dir to the head of the branch. We don't update the tree (unnecessary treatment and waste of space) instead, we simply store the current rev number in a file. Recall...
def _processChanges(self, unused_output): """Send info about pulled changes to the master and record current. HgPoller does the recording by moving the working dir to the head of the branch. We don't update the tree (unnecessary treatment and waste of space) instead, we simply s...
utility method to handle the result of getProcessOutputAndValue
def _convertNonZeroToFailure(self, res): "utility method to handle the result of getProcessOutputAndValue" (stdout, stderr, code) = res if code != 0: raise EnvironmentError( 'command failed with exit code %d: %s' % (code, stderr)) return (stdout, stderr, code)
utility method to stop the service when a failure occurs
def _stopOnFailure(self, f): "utility method to stop the service when a failure occurs" if self.running: d = defer.maybeDeferred(self.stopService) d.addErrback(log.err, 'while stopping broken HgPoller service') return f
Delete everything that shown up on status.
def purge(self, ignore_ignores): """Delete everything that shown up on status.""" command = ['status', '--xml'] if ignore_ignores: command.append('--no-ignore') d = self._dovccmd(command, collectStdout=True) @d.addCallback def parseAndRemove(stdout): ...
Checks if the given directory is a worker or a master and returns the appropriate run function.
def DetermineRunner(bbdir): '''Checks if the given directory is a worker or a master and returns the appropriate run function.''' tacfile = os.path.join(bbdir, 'buildbot.tac') if not os.path.exists(tacfile): # No tac-file - use master runner by default. import buildbot.scripts.runner ...
Delete everything that shown up on status.
def purge(self, ignore_ignores): """Delete everything that shown up on status.""" command = ['sync', '#none'] if ignore_ignores: command.append('--no-ignore') d = self._dovccmd(command, collectStdout=True) # add deferred to rm tree # then add defer to sync t...
Patches to manifest projects are a bit special. repo does not support a way to download them automatically, so we need to implement the boilerplate manually. This code separates the manifest patches from the other patches, and generates commands to import those manifest patches.
def filterManifestPatches(self): """ Patches to manifest projects are a bit special. repo does not support a way to download them automatically, so we need to implement the boilerplate manually. This code separates the manifest patches from the other patches, and generate...
also used by tests for expectations
def _getCleanupCommand(self): """also used by tests for expectations""" return textwrap.dedent("""\ set -v if [ -d .repo/manifests ] then # repo just refuse to run if manifest is messed up # so ensure we are in a known state ...
Return the object id for this master, for associating state with the master. @returns: ID, via Deferred
def getObjectId(self): """ Return the object id for this master, for associating state with the master. @returns: ID, via Deferred """ # try to get the cached value if self._object_id is not None: return defer.succeed(self._object_id) # faili...
private wrapper around C{self.db.state.getState}
def _getState(self, name, default=None): "private wrapper around C{self.db.state.getState}" d = self.getObjectId() @d.addCallback def get(objectid): return self.db.state.getState(objectid, name, default) return d
private wrapper around C{self.db.state.setState}
def _setState(self, name, value): "private wrapper around C{self.db.state.setState}" d = self.getObjectId() @d.addCallback def set(objectid): return self.db.state.setState(objectid, name, value) return d
Take a Change author and source and translate them into a User Object, storing the user in master.db, or returning None if the src is not specified. @param master: link to Buildmaster for database operations @type master: master.Buildmaster instance @param authors: Change author if string or Authz...
def createUserObject(master, author, src=None): """ Take a Change author and source and translate them into a User Object, storing the user in master.db, or returning None if the src is not specified. @param master: link to Buildmaster for database operations @type master: master.Buildmaster in...
This is a simple getter function that returns a user attribute that matches the contact_types argument, or returns None if no uid/match is found. @param master: BuildMaster used to query the database @type master: BuildMaster instance @param contact_types: list of contact attributes to look for in...
def getUserContact(master, contact_types, uid): """ This is a simple getter function that returns a user attribute that matches the contact_types argument, or returns None if no uid/match is found. @param master: BuildMaster used to query the database @type master: BuildMaster instance @pa...
Encrypts the incoming password after adding some salt to store it in the database. @param passwd: password portion of user credentials @type passwd: string @returns: encrypted/salted string
def encrypt(passwd): """ Encrypts the incoming password after adding some salt to store it in the database. @param passwd: password portion of user credentials @type passwd: string @returns: encrypted/salted string """ m = sha1() salt = hexlify(os.urandom(salt_len)) m.update(un...
Tests to see if the guess, after salting and hashing, matches the passwd from the database. @param guess: incoming password trying to be used for authentication @param passwd: already encrypted password from the database @returns: boolean
def check_passwd(guess, passwd): """ Tests to see if the guess, after salting and hashing, matches the passwd from the database. @param guess: incoming password trying to be used for authentication @param passwd: already encrypted password from the database @returns: boolean """ m = sh...
Returns the url to redirect the user to for user consent
def getLoginURL(self, redirect_url): """ Returns the url to redirect the user to for user consent """ p = Properties() p.master = self.master clientId = yield p.render(self.clientId) oauth_params = {'redirect_uri': self.loginUri, 'client_id...
make sure the result is backward compatible
def _handleLegacyResult(result): """ make sure the result is backward compatible """ if not isinstance(result, dict): warnings.warn('The Gerrit status callback uses the old way to ' 'communicate results. The outcome might be not what is ' 'expected.')...
Construct a command as a list of strings suitable for :func:`subprocess.call`.
def _gerritCmd(self, *args): '''Construct a command as a list of strings suitable for :func:`subprocess.call`. ''' if self.gerrit_identity_file is not None: options = ['-i', self.gerrit_identity_file] else: options = [] return ['ssh'] + options + [...
Try to start any builds that can be started right now. This function returns immediately, and promises to trigger those builders eventually. @param new_builders: names of new builders that should be given the opportunity to check for new requests.
def maybeStartBuildsOn(self, new_builders): """ Try to start any builds that can be started right now. This function returns immediately, and promises to trigger those builders eventually. @param new_builders: names of new builders that should be given the opportunity t...
This method must be called by user classes composite steps could create several logs, this mixin functions will write to the last one.
def addLogForRemoteCommands(self, logname): """This method must be called by user classes composite steps could create several logs, this mixin functions will write to the last one. """ self.rc_log = self.addLog(logname) return self.rc_log
generic RemoteCommand boilerplate
def runRemoteCommand(self, cmd, args, abandonOnFailure=True, evaluateCommand=lambda cmd: cmd.didFail()): """generic RemoteCommand boilerplate""" cmd = remotecommand.RemoteCommand(cmd, args) if hasattr(self, "rc_log"): cmd.useLog(self.rc_log, False) d ...
remove a directory from the worker
def runRmdir(self, dir, timeout=None, **kwargs): """ remove a directory from the worker """ cmd_args = {'dir': dir, 'logEnviron': self.logEnviron} if timeout: cmd_args['timeout'] = timeout return self.runRemoteCommand('rmdir', cmd_args, **kwargs)
remove a file from the worker
def runRmFile(self, path, timeout=None, **kwargs): """ remove a file from the worker """ cmd_args = {'path': path, 'logEnviron': self.logEnviron} if timeout: cmd_args['timeout'] = timeout if self.workerVersionIsOlderThan('rmfile', '3.1'): cmd_args['dir'] = os.path...
test whether path exists
def pathExists(self, path): """ test whether path exists""" def commandComplete(cmd): return not cmd.didFail() return self.runRemoteCommand('stat', {'file': path, 'logEnviron': self.logEnviron, }, aba...
create a directory and its parents
def runMkdir(self, _dir, **kwargs): """ create a directory and its parents""" return self.runRemoteCommand('mkdir', {'dir': _dir, 'logEnviron': self.logEnviron, }, **kwargs)
find files matching a shell-style pattern
def runGlob(self, path, **kwargs): """ find files matching a shell-style pattern""" def commandComplete(cmd): return cmd.updates['files'][-1] return self.runRemoteCommand('glob', {'path': path, 'logEnviron': self.logEnviron, }, ...
Returns old API ("slave") name for new name ("worker"). >>> assert _compat_name("Worker") == "Slave" >>> assert _compat_name("SomeWorkerStuff") == "SomeSlaveStuff" >>> assert _compat_name("SomeWorker", compat_name="SomeBuildSlave") == \ "SomeBuildSlave" If `compat_name` is not specified old na...
def _compat_name(new_name, compat_name=None): """Returns old API ("slave") name for new name ("worker"). >>> assert _compat_name("Worker") == "Slave" >>> assert _compat_name("SomeWorkerStuff") == "SomeSlaveStuff" >>> assert _compat_name("SomeWorker", compat_name="SomeBuildSlave") == \ "SomeBuil...
Hook that is ran when old API name is used. :param stacklevel: stack level relative to the caller's frame. Defaults to caller of the caller of this function.
def reportDeprecatedWorkerNameUsage(message, stacklevel=None, filename=None, lineno=None): """Hook that is ran when old API name is used. :param stacklevel: stack level relative to the caller's frame. Defaults to caller of the caller of this function. """ if fil...
Hook Twisted deprecation machinery to use custom warning class for Worker API deprecation warnings.
def setupWorkerTransition(): """Hook Twisted deprecation machinery to use custom warning class for Worker API deprecation warnings.""" default_warn_method = getWarningMethod() def custom_warn_method(message, category, stacklevel): if stacklevel is not None: stacklevel += 1 ...
Handles fallbacks for failure of fetch, wrapper for self._fetch
def _fetchOrFallback(self, _=None): """ Handles fallbacks for failure of fetch, wrapper for self._fetch """ res = yield self._fetch(None) if res == RC_SUCCESS: return res elif self.retryFetch: yield self._fetch(None) elif self.clobb...
Retry if clone failed
def _clone(self, shallowClone): """Retry if clone failed""" command = ['clone'] switchToBranch = False if self.supportsBranch and self.branch != 'HEAD': if self.branch.startswith('refs/'): # we can't choose this branch from 'git clone' directly; we ...
Perform full clone and checkout to the revision if specified In the case of shallow clones if any of the step fail abort whole build step.
def _fullClone(self, shallowClone=False): """Perform full clone and checkout to the revision if specified In the case of shallow clones if any of the step fail abort whole build step. """ res = yield self._clone(shallowClone) if res != RC_SUCCESS: return res ...
Wrapper for _fullClone(). In the case of failure, if clobberOnFailure is set to True remove the build directory and try a full clone again.
def _fullCloneOrFallback(self): """Wrapper for _fullClone(). In the case of failure, if clobberOnFailure is set to True remove the build directory and try a full clone again. """ res = yield self._fullClone() if res != RC_SUCCESS: if not self.clobberOnFailure: ...
Remove the work directory
def _doClobber(self): """Remove the work directory""" rc = yield self.runRmdir(self.workdir, timeout=self.timeout) if rc != RC_SUCCESS: raise RuntimeError("Failed to delete directory") return rc
Catch a POST request from BitBucket and start a build process Check the URL below if you require more information about payload https://confluence.atlassian.com/display/BITBUCKET/POST+Service+Management :param request: the http request Twisted object :param options: additional options
def getChanges(self, request): """Catch a POST request from BitBucket and start a build process Check the URL below if you require more information about payload https://confluence.atlassian.com/display/BITBUCKET/POST+Service+Management :param request: the http request Twisted object ...
This method returns Build's properties according to property filters. :param props: Properties as a dict (from db) :param filters: Desired properties keys as a list (from API URI)
def _generate_filtered_properties(self, props, filters): """ This method returns Build's properties according to property filters. :param props: Properties as a dict (from db) :param filters: Desired properties keys as a list (from API URI) """ # by default no properties...
get the value from vault secret backend
def get(self, entry): """ get the value from vault secret backend """ if self.apiVersion == 1: path = self.secretsmount + '/' + entry else: path = self.secretsmount + '/data/' + entry # note that the HTTP path contains v1 for both versions of the ...
Abstract the POST REST api documented here: https://gerrit.googlesource.com/plugins/verify-status/+/master/src/main/resources/Documentation/rest-api-changes.md :param change_id: The change_id for the change tested (can be in the long form e.g: myProject~master~I8473b95934b5732ac55d26311a706...
def createStatus(self, change_id, revision_id, name, value, abstain=None, rerun=None, comment=None, url=None, reporter=None, ...
Format the duration. This method could be overridden if really needed, as the duration format in gerrit is an arbitrary string. :param duration: duration in timedelta
def formatDuration(self, duration): """Format the duration. This method could be overridden if really needed, as the duration format in gerrit is an arbitrary string. :param duration: duration in timedelta """ days = duration.days hours, remainder = divmod(durati...
Get the gerrit changes This method could be overridden if really needed to accommodate for other custom steps method for fetching gerrit changes. :param props: an IProperty :return: (optionally via deferred) a list of dictionary with at list change_id, ...
def getGerritChanges(props): """ Get the gerrit changes This method could be overridden if really needed to accommodate for other custom steps method for fetching gerrit changes. :param props: an IProperty :return: (optionally via deferred) a list of dictionary...
Checks if the given directory is a buildbot worker or a master and returns the appropriate run function.
def DetermineRunner(bbdir): '''Checks if the given directory is a buildbot worker or a master and returns the appropriate run function.''' try: import buildbot_worker.scripts.runner tacfile = os.path.join(bbdir, 'buildbot.tac') if os.path.exists(tacfile): with open(tacfi...
Split CONTENT on a line boundary into a prefix smaller than 64k and a suffix containing the remainder, omitting the splitting newline.
def _splitBigChunk(self, content, logid): """ Split CONTENT on a line boundary into a prefix smaller than 64k and a suffix containing the remainder, omitting the splitting newline. """ # if it's small enough, just return it if len(content) < self.MAX_CHUNK_SIZE: ...
Update the cookie after session object was modified @param request: the request object which should get a new cookie
def updateSession(self, request): """ Update the cookie after session object was modified @param request: the request object which should get a new cookie """ # we actually need to copy some hardcoded constants from twisted :-( # Make sure we aren't creating a secure ses...
uid is now generated automatically according to the claims. This should actually only be used for cookie generation
def uid(self): """uid is now generated automatically according to the claims. This should actually only be used for cookie generation """ exp = datetime.datetime.utcnow() + self.expDelay claims = { 'user_info': self.user_info, # Note that we use JWT stand...
Make worker base directory if needed. @param basedir: worker base directory relative path @param quiet: if True, don't print info messages @raise CreateWorkerError: on error making base directory
def _makeBaseDir(basedir, quiet): """ Make worker base directory if needed. @param basedir: worker base directory relative path @param quiet: if True, don't print info messages @raise CreateWorkerError: on error making base directory """ if os.path.exists(basedir): if not quiet: ...
Create info/* files inside basedir. @param basedir: worker base directory relative path @param quiet: if True, don't print info messages @raise CreateWorkerError: on error making info directory or writing info files
def _makeInfoFiles(basedir, quiet): """ Create info/* files inside basedir. @param basedir: worker base directory relative path @param quiet: if True, don't print info messages @raise CreateWorkerError: on error making info directory or writing info files """ ...
Create buildbot.tac file. If buildbot.tac file already exists with different contents, create buildbot.tac.new instead. @param basedir: worker base directory relative path @param tac_file_contents: contents of buildbot.tac file to write @param quiet: if True, don't print info messages @raise Creat...
def _makeBuildbotTac(basedir, tac_file_contents, quiet): """ Create buildbot.tac file. If buildbot.tac file already exists with different contents, create buildbot.tac.new instead. @param basedir: worker base directory relative path @param tac_file_contents: contents of buildbot.tac file to write ...
Takes a git repository URL from Bitbucket and tries to determine the owner and repository name :param repourl: Bitbucket git repo in the form of git@bitbucket.com:OWNER/REPONAME.git https://bitbucket.com/OWNER/REPONAME.git ssh://git@bitbucket.com/OWNER...
def get_owner_and_repo(repourl): """ Takes a git repository URL from Bitbucket and tries to determine the owner and repository name :param repourl: Bitbucket git repo in the form of git@bitbucket.com:OWNER/REPONAME.git https://bitbucket.com/OWNER/REPONAME....
Called periodically by DBConnector, this method deletes changes older than C{changeHorizon}.
def pruneChanges(self, changeHorizon): """ Called periodically by DBConnector, this method deletes changes older than C{changeHorizon}. """ if not changeHorizon: return None def thd(conn): changes_tbl = self.db.model.changes # First,...
mostly comes from _twistd_unix.py which is not twisted public API :-/ except it returns an exception instead of exiting
def checkPidFile(pidfile): """ mostly comes from _twistd_unix.py which is not twisted public API :-/ except it returns an exception instead of exiting """ if os.path.exists(pidfile): try: with open(pidfile) as f: pid = int(f.read()) except ValueError: ...
Find the .buildbot/options file. Crawl from the current directory up towards the root, and also look in ~/.buildbot . The first directory that's owned by the user and has the file we're looking for wins. Windows skips the owned-by-user test. @rtype: dict @return: a dictionary o...
def loadOptionsFile(self, _here=None): """Find the .buildbot/options file. Crawl from the current directory up towards the root, and also look in ~/.buildbot . The first directory that's owned by the user and has the file we're looking for wins. Windows skips the owned-by-user test. ...
The login process failed, most likely because of an authorization failure (bad password), but it is also possible that we lost the new connection before we managed to send our credentials.
def failedToGetPerspective(self, why, broker): """The login process failed, most likely because of an authorization failure (bad password), but it is also possible that we lost the new connection before we managed to send our credentials. """ log.msg("ReconnectingPBClientFactory....
:param project_id: Project ID from GitLab :param branch: Branch name to create the status for. :param sha: Full sha to create the status for. :param state: one of the following 'pending', 'success', 'failed' or 'cancelled'. :param target_url: Target url to associate...
def createStatus(self, project_id, branch, sha, state, target_url=None, description=None, context=None): """ :param project_id: Project ID from GitLab :param branch: Branch name to create the status for. :param sha: Full sha to create the status ...
Construct a new L{BuildRequest} from a dictionary as returned by L{BuildRequestsConnectorComponent.getBuildRequest}. This method uses a cache, which may result in return of stale objects; for the most up-to-date information, use the database connector methods. @param master: cu...
def fromBrdict(cls, master, brdict): """ Construct a new L{BuildRequest} from a dictionary as returned by L{BuildRequestsConnectorComponent.getBuildRequest}. This method uses a cache, which may result in return of stale objects; for the most up-to-date information, use the datab...
Returns true if both buildrequest can be merged, via Deferred. This implements Buildbot's default collapse strategy.
def canBeCollapsed(master, br1, br2): """ Returns true if both buildrequest can be merged, via Deferred. This implements Buildbot's default collapse strategy. """ # short-circuit: if these are for the same buildset, collapse away if br1['buildsetid'] == br2['buildsetid']...
Returns one merged sourcestamp for every codebase
def mergeSourceStampsWith(self, others): """ Returns one merged sourcestamp for every codebase """ # get all codebases from all requests all_codebases = set(self.sources) for other in others: all_codebases |= set(other.sources) all_merged_sources = {} # walk ...
Return a reason for the merged build request.
def mergeReasons(self, others): """Return a reason for the merged build request.""" reasons = [] for req in [self] + others: if req.reason and req.reason not in reasons: reasons.append(req.reason) return ", ".join(reasons)
Convert C{bytes} to a native C{str}. On Python 3 and higher, str and bytes are not equivalent. In this case, decode the bytes, and return a native string. On Python 2 and lower, str and bytes are equivalent. In this case, just just return the native string. @param x: a string of type C{...
def bytes2NativeString(x, encoding='utf-8'): """ Convert C{bytes} to a native C{str}. On Python 3 and higher, str and bytes are not equivalent. In this case, decode the bytes, and return a native string. On Python 2 and lower, str and bytes are equivalent. In this case, just just ret...
Convert a unicode string to C{bytes}. @param x: a unicode string, of type C{unicode} on Python 2, or C{str} on Python 3. @param encoding: an optional codec, default: 'utf-8' @param errors: error handling scheme, default 'strict' @return: a string of type C{bytes}
def unicode2bytes(x, encoding='utf-8', errors='strict'): """ Convert a unicode string to C{bytes}. @param x: a unicode string, of type C{unicode} on Python 2, or C{str} on Python 3. @param encoding: an optional codec, default: 'utf-8' @param errors: error handling scheme, default 'str...
Convert a C{bytes} to a unicode string. @param x: a unicode string, of type C{unicode} on Python 2, or C{str} on Python 3. @param encoding: an optional codec, default: 'utf-8' @param errors: error handling scheme, default 'strict' @return: a unicode string of type C{unicode} on Python 2, ...
def bytes2unicode(x, encoding='utf-8', errors='strict'): """ Convert a C{bytes} to a unicode string. @param x: a unicode string, of type C{unicode} on Python 2, or C{str} on Python 3. @param encoding: an optional codec, default: 'utf-8' @param errors: error handling scheme, default 's...
Try to remove the old mock logs first.
def start(self): """ Try to remove the old mock logs first. """ if self.resultdir: for lname in self.mock_logfiles: self.logfiles[lname] = self.build.path_module.join(self.resultdir, lname) ...
\ Input is the json representation of: {'stream': "Content\ncontent"} Output is a generator yield "Content", and then "content"
def _handle_stream_line(line): """\ Input is the json representation of: {'stream': "Content\ncontent"} Output is a generator yield "Content", and then "content" """ # XXX This necessary processing is probably a bug from docker-py, # hence, might break if the bug is fixed, i.e. we should get dec...
Returns True if this build should be reported for this contact (eliminating duplicates), and also records the report for later
def shouldReportBuild(self, builder, buildnum): """Returns True if this build should be reported for this contact (eliminating duplicates), and also records the report for later""" for w, b, n in self.reported_builds: if b == builder and n == buildnum: return False ...
Returns list of arguments parsed by shlex.split() or raise UsageError if failed
def splitArgs(self, args): """Returns list of arguments parsed by shlex.split() or raise UsageError if failed""" try: return shlex.split(args) except ValueError as e: raise UsageError(e)
get a Contact instance for ``user`` on ``channel``
def getContact(self, user=None, channel=None): """ get a Contact instance for ``user`` on ``channel`` """ try: return self.contacts[(channel, user)] except KeyError: new_contact = self.contactClass(self, user=user, channel=channel) self.contacts[(channel, user...
An issue - failing, erroring etc test.
def issue(self, test, err): """An issue - failing, erroring etc test.""" self.step.setProgress('tests failed', len(self.failures) + len(self.errors))
Consumes the JSON as a python object and actually starts the build. :arguments: payload Python Object that represents the JSON sent by GitLab Service Hook.
def _process_change(self, payload, user, repo, repo_url, event, codebase=None): """ Consumes the JSON as a python object and actually starts the build. :arguments: payload Python Object that represents the JSON sent by GitLab Service ...
Consumes the merge_request JSON as a python object and turn it into a buildbot change. :arguments: payload Python Object that represents the JSON sent by GitLab Service Hook.
def _process_merge_request_change(self, payload, event, codebase=None): """ Consumes the merge_request JSON as a python object and turn it into a buildbot change. :arguments: payload Python Object that represents the JSON sent by GitLab Service Hook. ...