docstring
stringlengths 52
499
| function
stringlengths 67
35.2k
| __index_level_0__
int64 52.6k
1.16M
|
---|---|---|
Trigger a job explicitly.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabJobPlayError: If the job could not be triggered | def play(self, **kwargs):
path = '%s/%s/play' % (self.manager.path, self.get_id())
self.manager.gitlab.http_post(path) | 163,383 |
Erase the job (remove job artifacts and trace).
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabJobEraseError: If the job could not be erased | def erase(self, **kwargs):
path = '%s/%s/erase' % (self.manager.path, self.get_id())
self.manager.gitlab.http_post(path) | 163,384 |
Prevent artifacts from being deleted when expiration is set.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the request could not be performed | def keep_artifacts(self, **kwargs):
path = '%s/%s/artifacts/keep' % (self.manager.path, self.get_id())
self.manager.gitlab.http_post(path) | 163,385 |
Generate the commit diff.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the diff could not be retrieved
Returns:
list: The changes done in this commit | def diff(self, **kwargs):
path = '%s/%s/diff' % (self.manager.path, self.get_id())
return self.manager.gitlab.http_get(path, **kwargs) | 163,387 |
Cherry-pick a commit into a branch.
Args:
branch (str): Name of target branch
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCherryPickError: If the cherry-pick could not be performed | def cherry_pick(self, branch, **kwargs):
path = '%s/%s/cherry_pick' % (self.manager.path, self.get_id())
post_data = {'branch': branch}
self.manager.gitlab.http_post(path, post_data=post_data, **kwargs) | 163,388 |
List the references the commit is pushed to.
Args:
type (str): The scope of references ('branch', 'tag' or 'all')
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the references could not be retrieved
Returns:
list: The references the commit is pushed to. | def refs(self, type='all', **kwargs):
path = '%s/%s/refs' % (self.manager.path, self.get_id())
data = {'type': type}
return self.manager.gitlab.http_get(path, query_data=data, **kwargs) | 163,389 |
List the merge requests related to the commit.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the references could not be retrieved
Returns:
list: The merge requests related to the commit. | def merge_requests(self, **kwargs):
path = '%s/%s/merge_requests' % (self.manager.path, self.get_id())
return self.manager.gitlab.http_get(path, **kwargs) | 163,390 |
Stop the environment.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabStopError: If the operation failed | def stop(self, **kwargs):
path = '%s/%s/stop' % (self.manager.path, self.get_id())
self.manager.gitlab.http_post(path, **kwargs) | 163,391 |
Enable a deploy key for a project.
Args:
key_id (int): The ID of the key to enable
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabProjectDeployKeyError: If the key could not be enabled | def enable(self, key_id, **kwargs):
path = '%s/%s/enable' % (self.path, key_id)
self.gitlab.http_post(path, **kwargs) | 163,392 |
Create a new object.
Args:
data (dict): parameters to send to the server to create the
resource
**kwargs: Extra options to send to the server (e.g. sudo)
Returns:
RESTObject, RESTObject: The source and target issues
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server cannot perform the request | def create(self, data, **kwargs):
self._check_missing_create_attrs(data)
server_data = self.gitlab.http_post(self.path, post_data=data,
**kwargs)
source_issue = ProjectIssue(self._parent.manager,
server_data['source_issue'])
target_issue = ProjectIssue(self._parent.manager,
server_data['target_issue'])
return source_issue, target_issue | 163,394 |
Move the issue to another project.
Args:
to_project_id(int): ID of the target project
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabUpdateError: If the issue could not be moved | def move(self, to_project_id, **kwargs):
path = '%s/%s/move' % (self.manager.path, self.get_id())
data = {'to_project_id': to_project_id}
server_data = self.manager.gitlab.http_post(path, post_data=data,
**kwargs)
self._update_attrs(server_data) | 163,395 |
List merge requests that will close the issue when merged.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetErrot: If the merge requests could not be retrieved
Returns:
list: The list of merge requests. | def closed_by(self, **kwargs):
path = '%s/%s/closed_by' % (self.manager.path, self.get_id())
return self.manager.gitlab.http_get(path, **kwargs) | 163,396 |
Change MR-level allowed approvers and approver groups.
Args:
approver_ids (list): User IDs that can approve MRs
approver_group_ids (list): Group IDs whose members can approve MRs
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabUpdateError: If the server failed to perform the request | def set_approvers(self, approver_ids=[], approver_group_ids=[], **kwargs):
path = '%s/%s/approvers' % (self._parent.manager.path,
self._parent.get_id())
data = {'approver_ids': approver_ids,
'approver_group_ids': approver_group_ids}
self.gitlab.http_put(path, post_data=data, **kwargs) | 163,398 |
Cancel merge when the pipeline succeeds.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabMROnBuildSuccessError: If the server could not handle the
request | def cancel_merge_when_pipeline_succeeds(self, **kwargs):
path = ('%s/%s/cancel_merge_when_pipeline_succeeds' %
(self.manager.path, self.get_id()))
server_data = self.manager.gitlab.http_put(path, **kwargs)
self._update_attrs(server_data) | 163,399 |
List the merge request changes.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabListError: If the list could not be retrieved
Returns:
RESTObjectList: List of changes | def changes(self, **kwargs):
path = '%s/%s/changes' % (self.manager.path, self.get_id())
return self.manager.gitlab.http_get(path, **kwargs) | 163,401 |
List the merge request pipelines.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabListError: If the list could not be retrieved
Returns:
RESTObjectList: List of changes | def pipelines(self, **kwargs):
path = '%s/%s/pipelines' % (self.manager.path, self.get_id())
return self.manager.gitlab.http_get(path, **kwargs) | 163,402 |
Approve the merge request.
Args:
sha (str): Head SHA of MR
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabMRApprovalError: If the approval failed | def approve(self, sha=None, **kwargs):
path = '%s/%s/approve' % (self.manager.path, self.get_id())
data = {}
if sha:
data['sha'] = sha
server_data = self.manager.gitlab.http_post(path, post_data=data,
**kwargs)
self._update_attrs(server_data) | 163,403 |
Unapprove the merge request.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabMRApprovalError: If the unapproval failed | def unapprove(self, **kwargs):
path = '%s/%s/unapprove' % (self.manager.path, self.get_id())
data = {}
server_data = self.manager.gitlab.http_post(path, post_data=data,
**kwargs)
self._update_attrs(server_data) | 163,404 |
Delete a Label on the server.
Args:
name: The name of the label
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server cannot perform the request | def delete(self, name, **kwargs):
self.gitlab.http_delete(self.path, query_data={'name': name}, **kwargs) | 163,408 |
Save the changes made to the file to the server.
The object is updated to match what the server returns.
Args:
branch (str): Branch in which the file will be updated
commit_message (str): Message to send with the commit
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabUpdateError: If the server cannot perform the request | def save(self, branch, commit_message, **kwargs):
self.branch = branch
self.commit_message = commit_message
self.file_path = self.file_path.replace('/', '%2F')
super(ProjectFile, self).save(**kwargs) | 163,409 |
Delete the file from the server.
Args:
branch (str): Branch from which the file will be removed
commit_message (str): Commit message for the deletion
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server cannot perform the request | def delete(self, branch, commit_message, **kwargs):
file_path = self.get_id().replace('/', '%2F')
self.manager.delete(file_path, branch, commit_message, **kwargs) | 163,410 |
Retrieve a single file.
Args:
file_path (str): Path of the file to retrieve
ref (str): Name of the branch, tag or commit
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the file could not be retrieved
Returns:
object: The generated RESTObject | def get(self, file_path, ref, **kwargs):
file_path = file_path.replace('/', '%2F')
return GetMixin.get(self, file_path, ref=ref, **kwargs) | 163,411 |
Update an object on the server.
Args:
id: ID of the object to update (can be None if not required)
new_data: the update data for the object
**kwargs: Extra options to send to the server (e.g. sudo)
Returns:
dict: The new object data (*not* a RESTObject)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabUpdateError: If the server cannot perform the request | def update(self, file_path, new_data={}, **kwargs):
data = new_data.copy()
file_path = file_path.replace('/', '%2F')
data['file_path'] = file_path
path = '%s/%s' % (self.path, file_path)
self._check_missing_update_attrs(data)
return self.gitlab.http_put(path, post_data=data, **kwargs) | 163,413 |
Delete a file on the server.
Args:
file_path (str): Path of the file to remove
branch (str): Branch from which the file will be removed
commit_message (str): Commit message for the deletion
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server cannot perform the request | def delete(self, file_path, branch, commit_message, **kwargs):
path = '%s/%s' % (self.path, file_path.replace('/', '%2F'))
data = {'branch': branch, 'commit_message': commit_message}
self.gitlab.http_delete(path, query_data=data, **kwargs) | 163,414 |
Update the owner of a pipeline schedule.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabOwnershipError: If the request failed | def take_ownership(self, **kwargs):
path = '%s/%s/take_ownership' % (self.manager.path, self.get_id())
server_data = self.manager.gitlab.http_post(path, **kwargs)
self._update_attrs(server_data) | 163,417 |
Update an object on the server.
Args:
id: ID of the object to update (can be None if not required)
new_data: the update data for the object
**kwargs: Extra options to send to the server (e.g. sudo)
Returns:
dict: The new object data (*not* a RESTObject)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabUpdateError: If the server cannot perform the request | def update(self, id=None, new_data={}, **kwargs):
super(ProjectServiceManager, self).update(id, new_data, **kwargs)
self.id = id | 163,419 |
Return a file by blob SHA.
Args:
sha(str): ID of the blob
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server failed to perform the request
Returns:
dict: The blob content and metadata | def repository_blob(self, sha, **kwargs):
path = '/projects/%s/repository/blobs/%s' % (self.get_id(), sha)
return self.manager.gitlab.http_get(path, **kwargs) | 163,422 |
Return a diff between two branches/commits.
Args:
from_(str): Source branch/SHA
to(str): Destination branch/SHA
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server failed to perform the request
Returns:
str: The diff | def repository_compare(self, from_, to, **kwargs):
path = '/projects/%s/repository/compare' % self.get_id()
query_data = {'from': from_, 'to': to}
return self.manager.gitlab.http_get(path, query_data=query_data,
**kwargs) | 163,423 |
Create a forked from/to relation between existing projects.
Args:
forked_from_id (int): The ID of the project that was forked from
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the relation could not be created | def create_fork_relation(self, forked_from_id, **kwargs):
path = '/projects/%s/fork/%s' % (self.get_id(), forked_from_id)
self.manager.gitlab.http_post(path, **kwargs) | 163,425 |
Delete a forked relation between existing projects.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server failed to perform the request | def delete_fork_relation(self, **kwargs):
path = '/projects/%s/fork' % self.get_id()
self.manager.gitlab.http_delete(path, **kwargs) | 163,426 |
Delete merged branches.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server failed to perform the request | def delete_merged_branches(self, **kwargs):
path = '/projects/%s/repository/merged_branches' % self.get_id()
self.manager.gitlab.http_delete(path, **kwargs) | 163,427 |
Get languages used in the project with percentage value.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server failed to perform the request | def languages(self, **kwargs):
path = '/projects/%s/languages' % self.get_id()
return self.manager.gitlab.http_get(path, **kwargs) | 163,428 |
Share the project with a group.
Args:
group_id (int): ID of the group.
group_access (int): Access level for the group.
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server failed to perform the request | def share(self, group_id, group_access, expires_at=None, **kwargs):
path = '/projects/%s/share' % self.get_id()
data = {'group_id': group_id,
'group_access': group_access,
'expires_at': expires_at}
self.manager.gitlab.http_post(path, post_data=data, **kwargs) | 163,429 |
Delete a shared project link within a group.
Args:
group_id (int): ID of the group.
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server failed to perform the request | def unshare(self, group_id, **kwargs):
path = '/projects/%s/share/%s' % (self.get_id(), group_id)
self.manager.gitlab.http_delete(path, **kwargs) | 163,430 |
Start the housekeeping task.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabHousekeepingError: If the server failed to perform the
request | def housekeeping(self, **kwargs):
path = '/projects/%s/housekeeping' % self.get_id()
self.manager.gitlab.http_post(path, **kwargs) | 163,432 |
Search the project resources matching the provided string.'
Args:
scope (str): Scope of the search
search (str): Search string
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabSearchError: If the server failed to perform the request
Returns:
GitlabList: A list of dicts describing the resources found. | def search(self, scope, search, **kwargs):
data = {'scope': scope, 'search': search}
path = '/projects/%s/search' % self.get_id()
return self.manager.gitlab.http_list(path, query_data=data, **kwargs) | 163,435 |
Start the pull mirroring process for the project.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server failed to perform the request | def mirror_pull(self, **kwargs):
path = '/projects/%s/mirror/pull' % self.get_id()
self.manager.gitlab.http_post(path, **kwargs) | 163,436 |
Transfer a project to the given namespace ID
Args:
to_namespace (str): ID or path of the namespace to transfer the
project to
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTransferProjectError: If the project could not be transfered | def transfer_project(self, to_namespace, **kwargs):
path = '/projects/%s/transfer' % (self.id,)
self.manager.gitlab.http_put(path,
post_data={"namespace": to_namespace},
**kwargs) | 163,437 |
Validates authentication credentials for a registered Runner.
Args:
token (str): The runner's authentication token
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabVerifyError: If the server failed to verify the token | def verify(self, token, **kwargs):
path = '/runners/verify'
post_data = {'token': token}
self.gitlab.http_post(path, post_data=post_data, **kwargs) | 163,440 |
Mark the todo as done.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTodoError: If the server failed to perform the request | def mark_as_done(self, **kwargs):
path = '%s/%s/mark_as_done' % (self.manager.path, self.id)
server_data = self.manager.gitlab.http_post(path, **kwargs)
self._update_attrs(server_data) | 163,441 |
Mark all the todos as done.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTodoError: If the server failed to perform the request
Returns:
int: The number of todos maked done | def mark_all_as_done(self, **kwargs):
result = self.gitlab.http_post('/todos/mark_as_done', **kwargs)
try:
return int(result)
except ValueError:
return 0 | 163,442 |
Get the status of the geo node.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server failed to perform the request
Returns:
dict: The status of the geo node | def status(self, **kwargs):
path = '/geo_nodes/%s/status' % self.get_id()
return self.manager.gitlab.http_get(path, **kwargs) | 163,443 |
Retrieve a single object.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Returns:
object: The generated RESTObject
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server cannot perform the request | def get(self, id=None, **kwargs):
server_data = self.gitlab.http_get(self.path, **kwargs)
if server_data is None:
return None
return self._obj_cls(self, server_data) | 163,462 |
Refresh a single object from server.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Returns None (updates the object)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server cannot perform the request | def refresh(self, **kwargs):
if self._id_attr:
path = '%s/%s' % (self.manager.path, self.id)
else:
path = self.manager.path
server_data = self.manager.gitlab.http_get(path, **kwargs)
self._update_attrs(server_data) | 163,463 |
Update an object on the server.
Args:
id: ID of the object to update (can be None if not required)
new_data: the update data for the object
**kwargs: Extra options to send to the server (e.g. sudo)
Returns:
dict: The new object data (*not* a RESTObject)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabUpdateError: If the server cannot perform the request | def update(self, id=None, new_data={}, **kwargs):
if id is None:
path = self.path
else:
path = '%s/%s' % (self.path, id)
self._check_missing_update_attrs(new_data)
files = {}
# We get the attributes that need some special transformation
types = getattr(self, '_types', {})
if types:
# Duplicate data to avoid messing with what the user sent us
new_data = new_data.copy()
for attr_name, type_cls in types.items():
if attr_name in new_data.keys():
type_obj = type_cls(new_data[attr_name])
# if the type if FileAttribute we need to pass the data as
# file
if issubclass(type_cls, g_types.FileAttribute):
k = type_obj.get_file_name(attr_name)
files[attr_name] = (k, new_data.pop(attr_name))
else:
new_data[attr_name] = type_obj.get_for_api()
http_method = self._get_update_method()
return http_method(path, post_data=new_data, files=files, **kwargs) | 163,469 |
Create or update the object.
Args:
key (str): The key of the object to create/update
value (str): The value to set for the object
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabSetError: If an error occured
Returns:
obj: The created/updated attribute | def set(self, key, value, **kwargs):
path = '%s/%s' % (self.path, key.replace('/', '%2F'))
data = {'value': value}
server_data = self.gitlab.http_put(path, post_data=data, **kwargs)
return self._obj_cls(self, server_data) | 163,470 |
Delete an object on the server.
Args:
id: ID of the object to delete
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server cannot perform the request | def delete(self, id, **kwargs):
if id is None:
path = self.path
else:
if not isinstance(id, int):
id = id.replace('/', '%2F')
path = '%s/%s' % (self.path, id)
self.gitlab.http_delete(path, **kwargs) | 163,471 |
Save the changes made to the object to the server.
The object is updated to match what the server returns.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raise:
GitlabAuthenticationError: If authentication is not correct
GitlabUpdateError: If the server cannot perform the request | def save(self, **kwargs):
updated_data = self._get_updated_data()
# Nothing to update. Server fails if sent an empty dict.
if not updated_data:
return
# call the manager
obj_id = self.get_id()
server_data = self.manager.update(obj_id, updated_data, **kwargs)
if server_data is not None:
self._update_attrs(server_data) | 163,473 |
Get the user agent detail.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server cannot perform the request | def user_agent_detail(self, **kwargs):
path = '%s/%s/user_agent_detail' % (self.manager.path, self.get_id())
return self.manager.gitlab.http_get(path, **kwargs) | 163,474 |
Approve an access request.
Args:
access_level (int): The access level for the user
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabUpdateError: If the server fails to perform the request | def approve(self, access_level=gitlab.DEVELOPER_ACCESS, **kwargs):
path = '%s/%s/approve' % (self.manager.path, self.id)
data = {'access_level': access_level}
server_data = self.manager.gitlab.http_put(path, post_data=data,
**kwargs)
self._update_attrs(server_data) | 163,475 |
Create a todo associated to the object.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTodoError: If the todo cannot be set | def todo(self, **kwargs):
path = '%s/%s/todo' % (self.manager.path, self.get_id())
self.manager.gitlab.http_post(path, **kwargs) | 163,476 |
Get time stats for the object.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTimeTrackingError: If the time tracking update cannot be done | def time_stats(self, **kwargs):
# Use the existing time_stats attribute if it exist, otherwise make an
# API call
if 'time_stats' in self.attributes:
return self.attributes['time_stats']
path = '%s/%s/time_stats' % (self.manager.path, self.get_id())
return self.manager.gitlab.http_get(path, **kwargs) | 163,477 |
Set an estimated time of work for the object.
Args:
duration (str): Duration in human format (e.g. 3h30)
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTimeTrackingError: If the time tracking update cannot be done | def time_estimate(self, duration, **kwargs):
path = '%s/%s/time_estimate' % (self.manager.path, self.get_id())
data = {'duration': duration}
return self.manager.gitlab.http_post(path, post_data=data, **kwargs) | 163,478 |
Resets estimated time for the object to 0 seconds.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTimeTrackingError: If the time tracking update cannot be done | def reset_time_estimate(self, **kwargs):
path = '%s/%s/reset_time_estimate' % (self.manager.path, self.get_id())
return self.manager.gitlab.http_post(path, **kwargs) | 163,479 |
Resets the time spent working on the object.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTimeTrackingError: If the time tracking update cannot be done | def reset_spent_time(self, **kwargs):
path = '%s/%s/reset_spent_time' % (self.manager.path, self.get_id())
return self.manager.gitlab.http_post(path, **kwargs) | 163,480 |
Preview link_url and image_url after interpolation.
Args:
link_url (str): URL of the badge link
image_url (str): URL of the badge image
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabRenderError: If the rendering failed
Returns:
dict: The rendering properties | def render(self, link_url, image_url, **kwargs):
path = '%s/render' % self.path
data = {'link_url': link_url, 'image_url': image_url}
return self.gitlab.http_get(path, data, **kwargs) | 163,482 |
Create a Gitlab connection from configuration files.
Args:
gitlab_id (str): ID of the configuration section.
config_files list[str]: List of paths to configuration files.
Returns:
(gitlab.Gitlab): A Gitlab connection.
Raises:
gitlab.config.GitlabDataError: If the configuration is not correct. | def from_config(cls, gitlab_id=None, config_files=None):
config = gitlab.config.GitlabConfigParser(gitlab_id=gitlab_id,
config_files=config_files)
return cls(config.url, private_token=config.private_token,
oauth_token=config.oauth_token,
ssl_verify=config.ssl_verify, timeout=config.timeout,
http_username=config.http_username,
http_password=config.http_password,
api_version=config.api_version,
per_page=config.per_page) | 163,497 |
Validate a gitlab CI configuration.
Args:
content (txt): The .gitlab-ci.yml content
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabVerifyError: If the validation could not be done
Returns:
tuple: (True, []) if the file is valid, (False, errors(list))
otherwise | def lint(self, content, **kwargs):
post_data = {'content': content}
data = self.http_post('/ci/lint', post_data=post_data, **kwargs)
return (data['status'] == 'valid', data['errors']) | 163,501 |
Add a new license.
Args:
license (str): The license string
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabPostError: If the server cannot perform the request
Returns:
dict: The new license information | def set_license(self, license, **kwargs):
data = {'license': license}
return self.http_post('/license', post_data=data, **kwargs) | 163,503 |
Search GitLab resources matching the provided string.'
Args:
scope (str): Scope of the search
search (str): Search string
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabSearchError: If the server failed to perform the request
Returns:
GitlabList: A list of dicts describing the resources found. | def search(self, scope, search, **kwargs):
data = {'scope': scope, 'search': search}
return self.http_list('/search', query_data=data, **kwargs) | 163,516 |
Adds a send_message function to the Dispatcher's
dictionary of functions indexed by connection.
Args:
connection (str): A locally unique identifier
provided by the receiver of messages.
send_message (fn): The method that should be called
by the dispatcher to respond to messages which
arrive via connection. | def add_send_message(self, connection, send_message):
self._send_message[connection] = send_message
LOGGER.debug("Added send_message function "
"for connection %s", connection) | 163,538 |
Adds a send_last_message function to the Dispatcher's
dictionary of functions indexed by connection.
Args:
connection (str): A locally unique identifier
provided by the receiver of messages.
send_last_message (fn): The method that should be called
by the dispatcher to respond to messages which
arrive via connection, when the connection should be closed
after the message has been sent. | def add_send_last_message(self, connection, send_last_message):
self._send_last_message[connection] = send_last_message
LOGGER.debug("Added send_last_message function "
"for connection %s", connection) | 163,539 |
Removes a send_message function previously registered
with the Dispatcher.
Args:
connection (str): A locally unique identifier provided
by the receiver of messages. | def remove_send_message(self, connection):
if connection in self._send_message:
del self._send_message[connection]
LOGGER.debug("Removed send_message function "
"for connection %s", connection)
else:
LOGGER.warning("Attempted to remove send_message "
"function for connection %s, but no "
"send_message function was registered",
connection) | 163,540 |
Removes a send_last_message function previously registered
with the Dispatcher.
Args:
connection (str): A locally unique identifier provided
by the receiver of messages. | def remove_send_last_message(self, connection):
if connection in self._send_last_message:
del self._send_last_message[connection]
LOGGER.debug("Removed send_last_message function "
"for connection %s", connection)
else:
LOGGER.warning("Attempted to remove send_last_message "
"function for connection %s, but no "
"send_last_message function was registered",
connection) | 163,541 |
Get a single Role by name.
Args:
name (str): The name of the Role.
Returns:
(:obj:`Role`): The Role that matches the name or None. | def get_role(self, name):
address = _create_role_address(name)
role_list_bytes = None
try:
role_list_bytes = self._state_view.get(address=address)
except KeyError:
return None
if role_list_bytes is not None:
role_list = _create_from_bytes(role_list_bytes,
identity_pb2.RoleList)
for role in role_list.roles:
if role.name == name:
return role
return None | 163,564 |
Get a single Policy by name.
Args:
name (str): The name of the Policy.
Returns:
(:obj:`Policy`) The Policy that matches the name. | def get_policy(self, name):
address = _create_policy_address(name)
policy_list_bytes = None
try:
policy_list_bytes = self._state_view.get(address=address)
except KeyError:
return None
if policy_list_bytes is not None:
policy_list = _create_from_bytes(policy_list_bytes,
identity_pb2.PolicyList)
for policy in policy_list.policies:
if policy.name == name:
return policy
return None | 163,566 |
Returns an ordered list of batches to inject at the beginning of the
block. Can also return None if no batches should be injected.
Args:
previous_block (Block): The previous block.
Returns:
A list of batches to inject. | def block_start(self, previous_block):
previous_header_bytes = previous_block.header
previous_header = BlockHeader()
previous_header.ParseFromString(previous_header_bytes)
block_info = BlockInfo(
block_num=previous_header.block_num,
previous_block_id=previous_header.previous_block_id,
signer_public_key=previous_header.signer_public_key,
header_signature=previous_block.header_signature,
timestamp=int(time.time()))
return [self.create_batch(block_info)] | 163,570 |
Loads a private key from the key directory, based on a validator's
identity.
Args:
key_dir (str): The path to the key directory.
key_name (str): The name of the key to load.
Returns:
Signer: the cryptographic signer for the key | def load_identity_signer(key_dir, key_name):
key_path = os.path.join(key_dir, '{}.priv'.format(key_name))
if not os.path.exists(key_path):
raise LocalConfigurationError(
"No such signing key file: {}".format(key_path))
if not os.access(key_path, os.R_OK):
raise LocalConfigurationError(
"Key file is not readable: {}".format(key_path))
LOGGER.info('Loading signing key: %s', key_path)
try:
with open(key_path, 'r') as key_file:
private_key_str = key_file.read().strip()
except IOError as e:
raise LocalConfigurationError(
"Could not load key file: {}".format(str(e)))
try:
private_key = Secp256k1PrivateKey.from_hex(private_key_str)
except signing.ParseError as e:
raise LocalConfigurationError(
"Invalid key in file {}: {}".format(key_path, str(e)))
context = signing.create_context('secp256k1')
crypto_factory = CryptoFactory(context)
return crypto_factory.new_signer(private_key) | 163,588 |
Adds argument parser for the status command
Args:
subparsers: Add parsers to this subparser object
parent_parser: The parent argparse.ArgumentParser object | def add_status_parser(subparsers, parent_parser):
parser = subparsers.add_parser(
'status',
help='Displays information about validator status',
description="Provides a subcommand to show a validator\'s status")
grand_parsers = parser.add_subparsers(title='subcommands',
dest='subcommand')
grand_parsers.required = True
add_status_show_parser(grand_parsers, parent_parser) | 163,590 |
Get the next available processor of a particular type and increment
its occupancy counter.
Args:
processor_type (ProcessorType): The processor type associated with
a zmq identity.
Returns:
(Processor): Information about the transaction processor | def get_next_of_type(self, processor_type):
with self._condition:
if processor_type not in self:
self.wait_for_registration(processor_type)
try:
processor = self[processor_type].next_processor()
except NoProcessorVacancyError:
processor = self.wait_for_vacancy(processor_type)
processor.inc_occupancy()
return processor | 163,595 |
Either create a new ProcessorIterator, if none exists for a
ProcessorType, or add the Processor to the ProcessorIterator.
Args:
key (ProcessorType): The type of transactions this transaction
processor can handle.
value (Processor): Information about the transaction processor. | def __setitem__(self, key, value):
with self._condition:
if key not in self._processors:
proc_iterator = self._proc_iter_class()
proc_iterator.add_processor(value)
self._processors[key] = proc_iterator
else:
self._processors[key].add_processor(value)
if value.connection_id not in self._identities:
self._identities[value.connection_id] = [key]
else:
self._identities[value.connection_id].append(key)
self._condition.notify_all() | 163,597 |
Removes all of the Processors for
a particular transaction processor zeromq identity.
Args:
processor_identity (str): The zeromq identity of the transaction
processor. | def remove(self, processor_identity):
with self._condition:
processor_types = self._identities.get(processor_identity)
if processor_types is None:
LOGGER.warning("transaction processor with identity %s tried "
"to unregister but was not registered",
processor_identity)
return
for processor_type in processor_types:
if processor_type not in self._processors:
LOGGER.warning("processor type %s not a known processor "
"type but is associated with identity %s",
processor_type,
processor_identity)
continue
self._processors[processor_type].remove_processor(
processor_identity=processor_identity)
if not self._processors[processor_type]:
del self._processors[processor_type] | 163,598 |
Waits for a particular processor type to register or until
is_cancelled is True. is_cancelled cannot be part of this class
since we aren't cancelling all waiting for a processor_type,
but just this particular wait.
Args:
processor_type (ProcessorType): The family, and version of
the transaction processor.
Returns:
None | def wait_for_registration(self, processor_type):
with self._condition:
self._condition.wait_for(lambda: (
processor_type in self
or self._cancelled_event.is_set()))
if self._cancelled_event.is_set():
raise WaitCancelledException() | 163,599 |
Waits for a particular processor type to have the capacity to
handle additional transactions or until is_cancelled is True.
Args:
processor_type (ProcessorType): The family, and version of
the transaction processor.
Returns:
Processor | def wait_for_vacancy(self, processor_type):
with self._condition:
self._condition.wait_for(lambda: (
self._processor_available(processor_type)
or self._cancelled_event.is_set()))
if self._cancelled_event.is_set():
raise WaitCancelledException()
processor = self[processor_type].next_processor()
return processor | 163,600 |
Creates a SettingsView, given a StateView for merkle tree access.
Args:
state_view (:obj:`StateView`): a state view | def __init__(self, state_view):
self._state_view = state_view
# The public method for get_settings should have its results memoized
# via an lru_cache. Typical use of the decorator results in the
# cache being global, which can cause views to return incorrect
# values across state root hash boundaries.
self.get_setting = lru_cache(maxsize=128)(self._get_setting) | 163,618 |
Get the setting stored at the given key.
Args:
key (str): the setting key
default_value (str, optional): The default value, if none is
found. Defaults to None.
value_type (function, optional): The type of a setting value.
Defaults to `str`.
Returns:
str: The value of the setting if found, default_value
otherwise. | def _get_setting(self, key, default_value=None, value_type=str):
try:
state_entry = self._state_view.get(
SettingsView.setting_address(key))
except KeyError:
return default_value
if state_entry is not None:
setting = Setting()
setting.ParseFromString(state_entry)
for setting_entry in setting.entries:
if setting_entry.key == key:
return value_type(setting_entry.value)
return default_value | 163,619 |
Creates a StateView for the given state root hash.
Args:
state_root_hash (str): The state root hash of the state view
to return. If None, returns the state view for the
Returns:
StateView: state view locked to the given root hash. | def create_view(self, state_root_hash=None):
# Create a default Merkle database and if we have a state root hash,
# update the Merkle database's root to that
if state_root_hash is None:
state_root_hash = INIT_ROOT_KEY
merkle_db = MerkleDatabase(self._database,
merkle_root=state_root_hash)
return StateView(merkle_db) | 163,689 |
Get a list of events associated with all the blocks.
Args:
blocks (list of BlockWrapper): The blocks to search for events that
match each subscription.
subscriptions (list of EventSubscriptions): EventFilter and
event type to filter events.
Returns (list of Events): The Events associated which each block id.
Raises:
KeyError A receipt is missing from the receipt store. | def get_events_for_blocks(self, blocks, subscriptions):
events = []
for blkw in blocks:
events.extend(self.get_events_for_block(blkw, subscriptions))
return events | 163,699 |
Returns a consensus module by name.
Args:
module_name (str): The name of the module to load.
Returns:
module: The consensus module.
Raises:
UnknownConsensusModuleError: Raised if the given module_name does
not correspond to a consensus implementation. | def get_consensus_module(module_name):
module_package = module_name
if module_name == 'genesis':
module_package = (
'sawtooth_validator.journal.consensus.genesis.'
'genesis_consensus'
)
elif module_name == 'devmode':
module_package = (
'sawtooth_validator.journal.consensus.dev_mode.'
'dev_mode_consensus'
)
try:
return importlib.import_module(module_package)
except ImportError:
raise UnknownConsensusModuleError(
'Consensus module "{}" does not exist.'.format(module_name)) | 163,708 |
Returns the consensus_module based on the consensus module set by
the "sawtooth_settings" transaction family.
Args:
block_id (str): the block id associated with the current state_view
state_view (:obj:`StateView`): the current state view to use for
setting values
Raises:
UnknownConsensusModuleError: Thrown when an invalid consensus
module has been configured. | def get_configured_consensus_module(block_id, state_view):
settings_view = SettingsView(state_view)
default_consensus = \
'genesis' if block_id == NULL_BLOCK_IDENTIFIER else 'devmode'
consensus_module_name = settings_view.get_setting(
'sawtooth.consensus.algorithm', default_value=default_consensus)
return ConsensusFactory.get_consensus_module(
consensus_module_name) | 163,709 |
Retrieves a value associated with a key from the database
Args:
key (str): The key to retrieve | def get(self, key, index=None):
records = self.get_multi([key], index=index)
try:
return records[0][1] # return the value from the key/value tuple
except IndexError:
return None | 163,721 |
Constructs this handler on a given validator connection.
Args:
connection (messaging.Connection): the validator connection | def __init__(self, connection):
self._connection = connection
self._latest_state_delta_event = None
self._subscribers = []
self._subscriber_lock = asyncio.Lock()
self._delta_task = None
self._listening = False
self._accepting = True
self._connection.on_connection_state_change(
ConnectionEvent.DISCONNECTED,
self._handle_disconnect)
self._connection.on_connection_state_change(
ConnectionEvent.RECONNECTED,
self._handle_reconnection) | 163,724 |
Handles requests for new subscription websockets.
Args:
request (aiohttp.Request): the incoming request
Returns:
aiohttp.web.WebSocketResponse: the websocket response, when the
resulting websocket is closed | async def subscriptions(self, request):
if not self._accepting:
return web.Response(status=503)
web_sock = web.WebSocketResponse()
await web_sock.prepare(request)
async for msg in web_sock:
if msg.type == aiohttp.WSMsgType.TEXT:
await self._handle_message(web_sock, msg.data)
elif msg.type == aiohttp.WSMsgType.ERROR:
LOGGER.warning(
'Web socket connection closed with exception %s',
web_sock.exception())
await web_sock.close()
await self._handle_unsubscribe(web_sock)
return web_sock | 163,726 |
Adds arguments parsers for the batch list, batch show and batch status
commands
Args:
subparsers: Add parsers to this subparser object
parent_parser: The parent argparse.ArgumentParser object | def add_batch_parser(subparsers, parent_parser):
parser = subparsers.add_parser(
'batch',
help='Displays information about batches and submit new batches',
description='Provides subcommands to display Batch information and '
'submit Batches to the validator via the REST API.')
grand_parsers = parser.add_subparsers(title='subcommands',
dest='subcommand')
grand_parsers.required = True
add_batch_list_parser(grand_parsers, parent_parser)
add_batch_show_parser(grand_parsers, parent_parser)
add_batch_status_parser(grand_parsers, parent_parser)
add_batch_submit_parser(grand_parsers, parent_parser) | 163,756 |
Runs the batch list, batch show or batch status command, printing output
to the console
Args:
args: The parsed arguments sent to the command at runtime | def do_batch(args):
if args.subcommand == 'list':
do_batch_list(args)
if args.subcommand == 'show':
do_batch_show(args)
if args.subcommand == 'status':
do_batch_status(args)
if args.subcommand == 'submit':
do_batch_submit(args) | 163,761 |
Runs the batch-status command, printing output to the console
Args:
args: The parsed arguments sent to the command at runtime | def do_batch_status(args):
rest_client = RestClient(args.url, args.user)
batch_ids = args.batch_ids.split(',')
if args.wait and args.wait > 0:
statuses = rest_client.get_statuses(batch_ids, args.wait)
else:
statuses = rest_client.get_statuses(batch_ids)
if args.format == 'yaml':
fmt.print_yaml(statuses)
elif args.format == 'json':
fmt.print_json(statuses)
else:
raise AssertionError('Missing handler: {}'.format(args.format)) | 163,764 |
Runs the batch list or batch show command, printing output to the
console
Args:
args: The parsed arguments sent to the command at runtime | def do_state(args):
rest_client = RestClient(args.url, args.user)
if args.subcommand == 'list':
response = rest_client.list_state(args.subtree, args.head)
leaves = response['data']
head = response['head']
keys = ('address', 'size', 'data')
headers = tuple(k.upper() for k in keys)
def parse_leaf_row(leaf, decode=True):
decoded = b64decode(leaf['data'])
return (
leaf['address'],
len(decoded),
str(decoded) if decode else leaf['data'])
if args.format == 'default':
fmt.print_terminal_table(headers, leaves, parse_leaf_row)
print('HEAD BLOCK: "{}"'.format(head))
elif args.format == 'csv':
fmt.print_csv(headers, leaves, parse_leaf_row)
print('(data for head block: "{}")'.format(head))
elif args.format == 'json' or args.format == 'yaml':
state_data = {
'head': head,
'data': [{k: d for k, d in zip(keys, parse_leaf_row(l, False))}
for l in leaves]}
if args.format == 'yaml':
fmt.print_yaml(state_data)
elif args.format == 'json':
fmt.print_json(state_data)
else:
raise AssertionError('Missing handler: {}'.format(args.format))
else:
raise AssertionError('Missing handler: {}'.format(args.format))
if args.subcommand == 'show':
output = rest_client.get_leaf(args.address, args.head)
if output is not None:
print('DATA: "{}"'.format(b64decode(output['data'])))
print('HEAD: "{}"'.format(output['head']))
else:
raise CliException('No data available at {}'.format(args.address)) | 163,791 |
Computes the merkle root of the state changes in the context
corresponding with _last_valid_batch_c_id as applied to
_previous_state_hash.
Args:
required_state_root (str): The merkle root that these txns
should equal.
Returns:
state_hash (str): The merkle root calculated from the previous
state hash and the state changes from the context_id | def _compute_merkle_root(self, required_state_root):
state_hash = None
if self._previous_valid_batch_c_id is not None:
publishing_or_genesis = self._always_persist or \
required_state_root is None
state_hash = self._squash(
state_root=self._previous_state_hash,
context_ids=[self._previous_valid_batch_c_id],
persist=self._always_persist, clean_up=publishing_or_genesis)
if self._always_persist is True:
return state_hash
if state_hash == required_state_root:
self._squash(state_root=self._previous_state_hash,
context_ids=[self._previous_valid_batch_c_id],
persist=True, clean_up=True)
return state_hash | 163,805 |
Deserialize a byte string into a BlockWrapper
Args:
value (bytes): the byte string to deserialze
Returns:
BlockWrapper: a block wrapper instance | def deserialize_block(value):
# Block id strings are stored under batch/txn ids for reference.
# Only Blocks, not ids or Nones, should be returned by _get_block.
block = Block()
block.ParseFromString(value)
return BlockWrapper(
block=block) | 163,817 |
Returns all blocks with the given set of block_ids.
If a block id in the provided iterable does not exist in the block
store, it is ignored.
Args:
block_ids (:iterable:str): an iterable of block ids
Returns
list of block wrappers found for the given block ids | def get_blocks(self, block_ids):
return list(
filter(
lambda b: b is not None,
map(self._get_block_by_id_or_none, block_ids))) | 163,820 |
Returns a Transaction object from the block store by its id.
Params:
transaction_id (str): The header_signature of the desired txn
Returns:
Transaction: The specified transaction
Raises:
ValueError: The transaction is not in the block store | def get_transaction(self, transaction_id):
payload = self._get_data_by_id(
transaction_id, 'commit_store_get_transaction')
txn = Transaction()
txn.ParseFromString(payload)
return txn | 163,823 |
Uses headers and a row of example data to generate a format string
for printing a single row of data.
Args:
headers (tuple of strings): The headers for each column of data
example_row (tuple): A representative tuple of strings or ints
Returns
string: A format string with a size for each column | def format_terminal_row(headers, example_row):
def format_column(col):
if isinstance(col, str):
return '{{:{w}.{w}}}'
return '{{:<{w}}}'
widths = [max(len(h), len(str(d))) for h, d in zip(headers, example_row)]
# Truncate last column to fit terminal width
original_last_width = widths[-1]
if sys.stdout.isatty():
widths[-1] = max(
len(headers[-1]),
# console width - width of other columns and gutters - 3 for '...'
tty.width() - sum(w + 2 for w in widths[0:-1]) - 3)
# Build format string
cols = [format_column(c).format(w=w) for c, w in zip(example_row, widths)]
format_string = ' '.join(cols)
if original_last_width > widths[-1]:
format_string += '...'
return format_string | 163,826 |
Adds a batch id to the invalid cache along with the id of the
transaction that was rejected and any error message or extended data.
Removes that batch id from the pending set. The cache is only
temporary, and the batch info will be purged after one hour.
Args:
txn_id (str): The id of the invalid batch
message (str, optional): Message explaining why batch is invalid
extended_data (bytes, optional): Additional error data | def notify_txn_invalid(self, txn_id, message=None, extended_data=None):
invalid_txn_info = {'id': txn_id}
if message is not None:
invalid_txn_info['message'] = message
if extended_data is not None:
invalid_txn_info['extended_data'] = extended_data
with self._lock:
for batch_id, txn_ids in self._batch_info.items():
if txn_id in txn_ids:
if batch_id not in self._invalid:
self._invalid[batch_id] = [invalid_txn_info]
else:
self._invalid[batch_id].append(invalid_txn_info)
self._pending.discard(batch_id)
self._update_observers(batch_id, ClientBatchStatus.INVALID)
return | 163,839 |
Adds a Batch id to the pending cache, with its transaction ids.
Args:
batch (str): The id of the pending batch | def notify_batch_pending(self, batch):
txn_ids = {t.header_signature for t in batch.transactions}
with self._lock:
self._pending.add(batch.header_signature)
self._batch_info[batch.header_signature] = txn_ids
self._update_observers(batch.header_signature,
ClientBatchStatus.PENDING) | 163,840 |
Returns the status enum for a batch.
Args:
batch_id (str): The id of the batch to get the status for
Returns:
int: The status enum | def get_status(self, batch_id):
with self._lock:
if self._batch_committed(batch_id):
return ClientBatchStatus.COMMITTED
if batch_id in self._invalid:
return ClientBatchStatus.INVALID
if batch_id in self._pending:
return ClientBatchStatus.PENDING
return ClientBatchStatus.UNKNOWN | 163,841 |
Returns a statuses dict for the requested batches.
Args:
batch_ids (list of str): The ids of the batches to get statuses for
Returns:
dict: A dict with keys of batch ids, and values of status enums | def get_statuses(self, batch_ids):
with self._lock:
return {b: self.get_status(b) for b in batch_ids} | 163,842 |
Allows a component to register to be notified when a set of
batches is no longer PENDING. Expects to be able to call the
"notify_batches_finished" method on the registered component, sending
the statuses of the batches.
Args:
observer (object): Must implement "notify_batches_finished" method
batch_ids (list of str): The ids of the batches to watch | def watch_statuses(self, observer, batch_ids):
with self._lock:
statuses = self.get_statuses(batch_ids)
if self._has_no_pendings(statuses):
observer.notify_batches_finished(statuses)
else:
self._observers[observer] = statuses | 163,844 |
Returns the value in this context, or None, for each address in
addresses. Useful for gets on the context manager.
Args:
addresses (list of str): The addresses to return values for, if
within this context.
Returns:
results (list of bytes): The values in state for these addresses. | def get(self, addresses):
with self._lock:
results = []
for add in addresses:
self.validate_read(add)
results.append(self._get(add))
return results | 163,858 |
Returns the value set in this context, or None, for each address in
addresses.
Args:
addresses (list of str): The addresses to return values for, if set
within this context.
Returns:
(list): bytes set at the address or None | def get_if_set(self, addresses):
with self._lock:
results = []
for add in addresses:
results.append(self._get_if_set(add))
return results | 163,859 |
Returns a list of addresses that have been deleted, or None if it
hasn't been deleted.
Args:
addresses (list of str): The addresses to check if deleted.
Returns:
(list of str): The addresses, if deleted, or None. | def get_if_deleted(self, addresses):
with self._lock:
results = []
for add in addresses:
results.append(self._get_if_deleted(add))
return results | 163,860 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.