Code
stringlengths 103
85.9k
| Summary
listlengths 0
94
|
---|---|
Please provide a description of the function:def link(self, *args):
mr = RiakMapReduce(self.client)
mr.add(self.bucket.name, self.key)
return mr.link(*args) | [
"\n Start assembling a Map/Reduce operation.\n A shortcut for :meth:`~riak.mapreduce.RiakMapReduce.link`.\n\n :rtype: :class:`~riak.mapreduce.RiakMapReduce`\n "
]
|
Please provide a description of the function:def get_encoder(self, content_type):
if content_type in self._encoders:
return self._encoders[content_type]
else:
return self._client.get_encoder(content_type) | [
"\n Get the encoding function for the provided content type for\n this bucket.\n\n :param content_type: the requested media type\n :type content_type: str\n :param content_type: Content type requested\n "
]
|
Please provide a description of the function:def get_decoder(self, content_type):
if content_type in self._decoders:
return self._decoders[content_type]
else:
return self._client.get_decoder(content_type) | [
"\n Get the decoding function for the provided content type for\n this bucket.\n\n :param content_type: the requested media type\n :type content_type: str\n :rtype: function\n "
]
|
Please provide a description of the function:def new(self, key=None, data=None, content_type='application/json',
encoded_data=None):
from riak import RiakObject
if self.bucket_type.datatype:
return TYPES[self.bucket_type.datatype](bucket=self, key=key)
if PY2:
try:
if isinstance(data, string_types):
data = data.encode('ascii')
except UnicodeError:
raise TypeError('Unicode data values are not supported.')
obj = RiakObject(self._client, self, key)
obj.content_type = content_type
if data is not None:
obj.data = data
if encoded_data is not None:
obj.encoded_data = encoded_data
return obj | [
"A shortcut for manually instantiating a new\n :class:`~riak.riak_object.RiakObject` or a new\n :class:`~riak.datatypes.Datatype`, based on the presence and value\n of the :attr:`datatype <BucketType.datatype>` bucket property. When\n the bucket contains a :class:`~riak.datatypes.Datatype`, all\n arguments are ignored except ``key``, otherwise they are used to\n initialize the :class:`~riak.riak_object.RiakObject`.\n\n :param key: Name of the key. Leaving this to be None (default)\n will make Riak generate the key on store.\n :type key: str\n :param data: The data to store in a\n :class:`~riak.riak_object.RiakObject`, see\n :attr:`RiakObject.data <riak.riak_object.RiakObject.data>`.\n :type data: object\n :param content_type: The media type of the data stored in the\n :class:`~riak.riak_object.RiakObject`, see\n :attr:`RiakObject.content_type\n <riak.riak_object.RiakObject.content_type>`.\n :type content_type: str\n :param encoded_data: The encoded data to store in a\n :class:`~riak.riak_object.RiakObject`, see\n :attr:`RiakObject.encoded_data\n <riak.riak_object.RiakObject.encoded_data>`.\n :type encoded_data: str\n :rtype: :class:`~riak.riak_object.RiakObject` or\n :class:`~riak.datatypes.Datatype`\n\n "
]
|
Please provide a description of the function:def get(self, key, r=None, pr=None, timeout=None, include_context=None,
basic_quorum=None, notfound_ok=None, head_only=False):
from riak import RiakObject
if self.bucket_type.datatype:
return self._client.fetch_datatype(self, key, r=r, pr=pr,
timeout=timeout,
include_context=include_context,
basic_quorum=basic_quorum,
notfound_ok=notfound_ok)
else:
obj = RiakObject(self._client, self, key)
return obj.reload(r=r, pr=pr, timeout=timeout,
basic_quorum=basic_quorum,
notfound_ok=notfound_ok,
head_only=head_only) | [
"\n Retrieve a :class:`~riak.riak_object.RiakObject` or\n :class:`~riak.datatypes.Datatype`, based on the presence and value\n of the :attr:`datatype <BucketType.datatype>` bucket property.\n\n :param key: Name of the key.\n :type key: string\n :param r: R-Value of the request (defaults to bucket's R)\n :type r: integer\n :param pr: PR-Value of the request (defaults to bucket's PR)\n :type pr: integer\n :param timeout: a timeout value in milliseconds\n :type timeout: int\n :param include_context: if the bucket contains datatypes, include\n the opaque context in the result\n :type include_context: bool\n :param basic_quorum: whether to use the \"basic quorum\" policy\n for not-founds\n :type basic_quorum: bool\n :param notfound_ok: whether to treat not-found responses as successful\n :type notfound_ok: bool\n :param head_only: whether to fetch without value, so only metadata\n (only available on PB transport)\n :type head_only: bool\n :rtype: :class:`RiakObject <riak.riak_object.RiakObject>` or\n :class:`~riak.datatypes.Datatype`\n\n "
]
|
Please provide a description of the function:def multiget(self, keys, r=None, pr=None, timeout=None,
basic_quorum=None, notfound_ok=None,
head_only=False):
bkeys = [(self.bucket_type.name, self.name, key) for key in keys]
return self._client.multiget(bkeys, r=r, pr=pr, timeout=timeout,
basic_quorum=basic_quorum,
notfound_ok=notfound_ok,
head_only=head_only) | [
"\n Retrieves a list of keys belonging to this bucket in parallel.\n\n :param keys: the keys to fetch\n :type keys: list\n :param r: R-Value for the requests (defaults to bucket's R)\n :type r: integer\n :param pr: PR-Value for the requests (defaults to bucket's PR)\n :type pr: integer\n :param timeout: a timeout value in milliseconds\n :type timeout: int\n :param basic_quorum: whether to use the \"basic quorum\" policy\n for not-founds\n :type basic_quorum: bool\n :param notfound_ok: whether to treat not-found responses as successful\n :type notfound_ok: bool\n :param head_only: whether to fetch without value, so only metadata\n (only available on PB transport)\n :type head_only: bool\n :rtype: list of :class:`RiakObjects <riak.riak_object.RiakObject>`,\n :class:`Datatypes <riak.datatypes.Datatype>`, or tuples of\n bucket_type, bucket, key, and the exception raised on fetch\n "
]
|
Please provide a description of the function:def new_from_file(self, key, filename):
binary_data = None
with open(filename, 'rb') as f:
binary_data = f.read()
mimetype, encoding = mimetypes.guess_type(filename)
if encoding:
binary_data = bytearray(binary_data, encoding)
else:
binary_data = bytearray(binary_data)
if not mimetype:
mimetype = 'application/octet-stream'
if PY2:
return self.new(key, encoded_data=binary_data,
content_type=mimetype)
else:
return self.new(key, encoded_data=bytes(binary_data),
content_type=mimetype) | [
"Create a new Riak object in the bucket, using the contents of\n the specified file. This is a shortcut for :meth:`new`, where the\n ``encoded_data`` and ``content_type`` are set for you.\n\n .. warning:: This is not supported for buckets that contain\n :class:`Datatypes <riak.datatypes.Datatype>`.\n\n :param key: the key of the new object\n :type key: string\n :param filename: the file to read the contents from\n :type filename: string\n :rtype: :class:`RiakObject <riak.riak_object.RiakObject>`\n "
]
|
Please provide a description of the function:def search(self, query, index=None, **params):
search_index = index or self.name
return self._client.fulltext_search(search_index, query, **params) | [
"\n Queries a search index over objects in this bucket/index. See\n :meth:`RiakClient.fulltext_search()\n <riak.client.RiakClient.fulltext_search>` for more details.\n\n :param query: the search query\n :type query: string\n :param index: the index to search over. Defaults to the bucket's name.\n :type index: string or None\n :param params: additional query flags\n :type params: dict\n "
]
|
Please provide a description of the function:def get_index(self, index, startkey, endkey=None, return_terms=None,
max_results=None, continuation=None, timeout=None,
term_regex=None):
return self._client.get_index(self, index, startkey, endkey,
return_terms=return_terms,
max_results=max_results,
continuation=continuation,
timeout=timeout, term_regex=term_regex) | [
"\n Queries a secondary index over objects in this bucket,\n returning keys or index/key pairs. See\n :meth:`RiakClient.get_index()\n <riak.client.RiakClient.get_index>` for more details.\n "
]
|
Please provide a description of the function:def get_counter(self, key, **kwargs):
return self._client.get_counter(self, key, **kwargs) | [
"\n Gets the value of a counter stored in this bucket. See\n :meth:`RiakClient.get_counter()\n <riak.client.RiakClient.get_counter>` for options.\n\n .. deprecated:: 2.1.0 (Riak 2.0) Riak 1.4-style counters are\n deprecated in favor of the :class:`~riak.datatypes.Counter`\n datatype.\n\n :param key: the key of the counter\n :type key: string\n :rtype: int\n "
]
|
Please provide a description of the function:def update_counter(self, key, value, **kwargs):
return self._client.update_counter(self, key, value, **kwargs) | [
"\n Updates the value of a counter stored in this bucket. Positive\n values increment the counter, negative values decrement. See\n :meth:`RiakClient.update_counter()\n <riak.client.RiakClient.update_counter>` for options.\n\n .. deprecated:: 2.1.0 (Riak 2.0) Riak 1.4-style counters are\n deprecated in favor of the :class:`~riak.datatypes.Counter`\n datatype.\n\n :param key: the key of the counter\n :type key: string\n :param value: the amount to increment or decrement\n :type value: integer\n "
]
|
Please provide a description of the function:def get_buckets(self, timeout=None):
return self._client.get_buckets(bucket_type=self, timeout=timeout) | [
"\n Get the list of buckets under this bucket-type as\n :class:`RiakBucket <riak.bucket.RiakBucket>` instances.\n\n .. warning:: Do not use this in production, as it requires\n traversing through all keys stored in a cluster.\n\n .. note:: This request is automatically retried :attr:`retries`\n times if it fails due to network error.\n\n :param timeout: a timeout value in milliseconds\n :type timeout: int\n :rtype: list of :class:`RiakBucket <riak.bucket.RiakBucket>`\n instances\n "
]
|
Please provide a description of the function:def stream_buckets(self, timeout=None):
return self._client.stream_buckets(bucket_type=self, timeout=timeout) | [
"\n Streams the list of buckets under this bucket-type. This is a\n generator method that should be iterated over.\n\n The caller must close the stream when finished. See\n :meth:`RiakClient.stream_buckets()\n <riak.client.RiakClient.stream_buckets>` for more details.\n\n .. warning:: Do not use this in production, as it requires\n traversing through all keys stored in a cluster.\n\n :param timeout: a timeout value in milliseconds\n :type timeout: int\n :rtype: iterator that yields lists of :class:`RiakBucket\n <riak.bucket.RiakBucket>` instances\n "
]
|
Please provide a description of the function:def incr(self, d):
with self.lock:
self.p = self.value() + d | [
"\n Increases the value by the argument.\n\n :param d: the value to increase by\n :type d: float\n "
]
|
Please provide a description of the function:def value(self):
with self.lock:
now = time.time()
dt = now - self.t0
self.t0 = now
self.p = self.p * (math.pow(self.e, self.r * dt))
return self.p | [
"\n Returns the current value (adjusted for the time decay)\n\n :rtype: float\n "
]
|
Please provide a description of the function:def make_random_client_id(self):
if PY2:
return ('py_%s' %
base64.b64encode(str(random.randint(1, 0x40000000))))
else:
return ('py_%s' %
base64.b64encode(bytes(str(random.randint(1, 0x40000000)),
'ascii'))) | [
"\n Returns a random client identifier\n "
]
|
Please provide a description of the function:def make_fixed_client_id(self):
machine = platform.node()
process = os.getpid()
thread = threading.currentThread().getName()
return base64.b64encode('%s|%s|%s' % (machine, process, thread)) | [
"\n Returns a unique identifier for the current machine/process/thread.\n "
]
|
Please provide a description of the function:def get(self, robj, r=None, pr=None, timeout=None, basic_quorum=None,
notfound_ok=None, head_only=False):
raise NotImplementedError | [
"\n Fetches an object.\n "
]
|
Please provide a description of the function:def put(self, robj, w=None, dw=None, pw=None, return_body=None,
if_none_match=None, timeout=None):
raise NotImplementedError | [
"\n Stores an object.\n "
]
|
Please provide a description of the function:def delete(self, robj, rw=None, r=None, w=None, dw=None, pr=None,
pw=None, timeout=None):
raise NotImplementedError | [
"\n Deletes an object.\n "
]
|
Please provide a description of the function:def get_index(self, bucket, index, startkey, endkey=None,
return_terms=None, max_results=None, continuation=None,
timeout=None, term_regex=None):
raise NotImplementedError | [
"\n Performs a secondary index query.\n "
]
|
Please provide a description of the function:def stream_index(self, bucket, index, startkey, endkey=None,
return_terms=None, max_results=None, continuation=None,
timeout=None):
raise NotImplementedError | [
"\n Streams a secondary index query.\n "
]
|
Please provide a description of the function:def update_counter(self, bucket, key, value, w=None, dw=None, pw=None,
returnvalue=False):
raise NotImplementedError | [
"\n Updates a counter by the given value.\n "
]
|
Please provide a description of the function:def fetch_datatype(self, bucket, key, r=None, pr=None, basic_quorum=None,
notfound_ok=None, timeout=None, include_context=None):
raise NotImplementedError | [
"\n Fetches a Riak Datatype.\n "
]
|
Please provide a description of the function:def update_datatype(self, datatype, w=None, dw=None, pw=None,
return_body=None, timeout=None, include_context=None):
raise NotImplementedError | [
"\n Updates a Riak Datatype by sending local operations to the server.\n "
]
|
Please provide a description of the function:def _search_mapred_emu(self, index, query):
phases = []
if not self.phaseless_mapred():
phases.append({'language': 'erlang',
'module': 'riak_kv_mapreduce',
'function': 'reduce_identity',
'keep': True})
mr_result = self.mapred({'module': 'riak_search',
'function': 'mapred_search',
'arg': [index, query]},
phases)
result = {'num_found': len(mr_result),
'max_score': 0.0,
'docs': []}
for bucket, key, data in mr_result:
if u'score' in data and data[u'score'][0] > result['max_score']:
result['max_score'] = data[u'score'][0]
result['docs'].append({u'id': key})
return result | [
"\n Emulates a search request via MapReduce. Used in the case\n where the transport supports MapReduce but has no native\n search capability.\n "
]
|
Please provide a description of the function:def _get_index_mapred_emu(self, bucket, index, startkey, endkey=None):
phases = []
if not self.phaseless_mapred():
phases.append({'language': 'erlang',
'module': 'riak_kv_mapreduce',
'function': 'reduce_identity',
'keep': True})
if endkey:
result = self.mapred({'bucket': bucket,
'index': index,
'start': startkey,
'end': endkey},
phases)
else:
result = self.mapred({'bucket': bucket,
'index': index,
'key': startkey},
phases)
return [key for resultbucket, key in result] | [
"\n Emulates a secondary index request via MapReduce. Used in the\n case where the transport supports MapReduce but has no native\n secondary index query capability.\n "
]
|
Please provide a description of the function:def _parse_body(self, robj, response, expected_statuses):
# If no response given, then return.
if response is None:
return None
status, headers, data = response
# Check if the server is down(status==0)
if not status:
m = 'Could not contact Riak Server: http://{0}:{1}!'.format(
self._node.host, self._node.http_port)
raise RiakError(m)
# Make sure expected code came back
self.check_http_code(status, expected_statuses)
if 'x-riak-vclock' in headers:
robj.vclock = VClock(headers['x-riak-vclock'], 'base64')
# If 404(Not Found), then clear the object.
if status == 404:
robj.siblings = []
return None
# If 201 Created, we need to extract the location and set the
# key on the object.
elif status == 201:
robj.key = headers['location'].strip().split('/')[-1]
# If 300(Siblings), apply the siblings to the object
elif status == 300:
ctype, params = parse_header(headers['content-type'])
if ctype == 'multipart/mixed':
if six.PY3:
data = bytes_to_str(data)
boundary = re.compile('\r?\n--%s(?:--)?\r?\n' %
re.escape(params['boundary']))
parts = [message_from_string(p)
for p in re.split(boundary, data)[1:-1]]
robj.siblings = [self._parse_sibling(RiakContent(robj),
part.items(),
part.get_payload())
for part in parts]
# Invoke sibling-resolution logic
if robj.resolver is not None:
robj.resolver(robj)
return robj
else:
raise Exception('unexpected sibling response format: {0}'.
format(ctype))
robj.siblings = [self._parse_sibling(RiakContent(robj),
headers.items(),
data)]
return robj | [
"\n Parse the body of an object response and populate the object.\n "
]
|
Please provide a description of the function:def _parse_sibling(self, sibling, headers, data):
sibling.exists = True
# Parse the headers...
for header, value in headers:
header = header.lower()
if header == 'content-type':
sibling.content_type, sibling.charset = \
self._parse_content_type(value)
elif header == 'etag':
sibling.etag = value
elif header == 'link':
sibling.links = self._parse_links(value)
elif header == 'last-modified':
sibling.last_modified = mktime_tz(parsedate_tz(value))
elif header.startswith('x-riak-meta-'):
metakey = header.replace('x-riak-meta-', '')
sibling.usermeta[metakey] = value
elif header.startswith('x-riak-index-'):
field = header.replace('x-riak-index-', '')
reader = csv.reader([value], skipinitialspace=True)
for line in reader:
for token in line:
token = decode_index_value(field, token)
sibling.add_index(field, token)
elif header == 'x-riak-deleted':
sibling.exists = False
sibling.encoded_data = data
return sibling | [
"\n Parses a single sibling out of a response.\n "
]
|
Please provide a description of the function:def _to_link_header(self, link):
try:
bucket, key, tag = link
except ValueError:
raise RiakError("Invalid link tuple %s" % link)
tag = tag if tag is not None else bucket
url = self.object_path(bucket, key)
header = '<%s>; riaktag="%s"' % (url, tag)
return header | [
"\n Convert the link tuple to a link header string. Used internally.\n "
]
|
Please provide a description of the function:def _build_put_headers(self, robj, if_none_match=False):
# Construct the headers...
if robj.charset is not None:
content_type = ('%s; charset="%s"' %
(robj.content_type, robj.charset))
else:
content_type = robj.content_type
headers = MultiDict({'Content-Type': content_type,
'X-Riak-ClientId': self._client_id})
# Add the vclock if it exists...
if robj.vclock is not None:
headers['X-Riak-Vclock'] = robj.vclock.encode('base64')
# Create the header from metadata
self._add_links_for_riak_object(robj, headers)
for key in robj.usermeta.keys():
headers['X-Riak-Meta-%s' % key] = robj.usermeta[key]
for field, value in robj.indexes:
key = 'X-Riak-Index-%s' % field
if key in headers:
headers[key] += ", " + str(value)
else:
headers[key] = str(value)
if if_none_match:
headers['If-None-Match'] = '*'
return headers | [
"Build the headers for a POST/PUT request."
]
|
Please provide a description of the function:def _normalize_json_search_response(self, json):
result = {}
if 'facet_counts' in json:
result['facet_counts'] = json[u'facet_counts']
if 'grouped' in json:
result['grouped'] = json[u'grouped']
if 'stats' in json:
result['stats'] = json[u'stats']
if u'response' in json:
result['num_found'] = json[u'response'][u'numFound']
result['max_score'] = float(json[u'response'][u'maxScore'])
docs = []
for doc in json[u'response'][u'docs']:
resdoc = {}
if u'_yz_rk' in doc:
# Is this a Riak 2.0 result?
resdoc = doc
else:
# Riak Search 1.0 Legacy assumptions about format
resdoc[u'id'] = doc[u'id']
if u'fields' in doc:
for k, v in six.iteritems(doc[u'fields']):
resdoc[k] = v
docs.append(resdoc)
result['docs'] = docs
return result | [
"\n Normalizes a JSON search response so that PB and HTTP have the\n same return value\n "
]
|
Please provide a description of the function:def _normalize_xml_search_response(self, xml):
target = XMLSearchResult()
parser = ElementTree.XMLParser(target=target)
parser.feed(xml)
return parser.close() | [
"\n Normalizes an XML search response so that PB and HTTP have the\n same return value\n "
]
|
Please provide a description of the function:def _parse_content_type(self, value):
content_type, params = parse_header(value)
if 'charset' in params:
charset = params['charset']
else:
charset = None
return content_type, charset | [
"\n Split the content-type header into two parts:\n 1) Actual main/sub encoding type\n 2) charset\n\n :param value: Complete MIME content-type string\n "
]
|
Please provide a description of the function:def connect(self):
HTTPConnection.connect(self)
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) | [
"\n Set TCP_NODELAY on socket\n "
]
|
Please provide a description of the function:def connect(self):
sock = socket.create_connection((self.host, self.port), self.timeout)
if not USE_STDLIB_SSL:
ssl_ctx = configure_pyopenssl_context(self.credentials)
# attempt to upgrade the socket to TLS
cxn = OpenSSL.SSL.Connection(ssl_ctx, sock)
cxn.set_connect_state()
while True:
try:
cxn.do_handshake()
except OpenSSL.SSL.WantReadError:
select.select([sock], [], [])
continue
except OpenSSL.SSL.Error as e:
raise SecurityError('bad handshake - ' + str(e))
break
self.sock = RiakWrappedSocket(cxn, sock)
self.credentials._check_revoked_cert(self.sock)
else:
ssl_ctx = configure_ssl_context(self.credentials)
if self.timeout is not None:
sock.settimeout(self.timeout)
self.sock = ssl.SSLSocket(sock=sock,
keyfile=self.credentials.pkey_file,
certfile=self.credentials.cert_file,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=self.credentials.cacert_file,
ciphers=self.credentials.ciphers,
server_hostname=self.host)
self.sock.context = ssl_ctx | [
"\n Connect to a host on a given (SSL) port using PyOpenSSL.\n "
]
|
Please provide a description of the function:def retryable(fn, protocol=None):
def wrapper(self, *args, **kwargs):
pool = self._choose_pool(protocol)
def thunk(transport):
return fn(self, transport, *args, **kwargs)
return self._with_retries(pool, thunk)
wrapper.__doc__ = fn.__doc__
wrapper.__repr__ = fn.__repr__
return wrapper | [
"\n Wraps a client operation that can be retried according to the set\n :attr:`RiakClient.retries`. Used internally.\n "
]
|
Please provide a description of the function:def retry_count(self, retries):
if not isinstance(retries, int):
raise TypeError("retries must be an integer")
old_retries, self.retries = self.retries, retries
try:
yield
finally:
self.retries = old_retries | [
"\n retry_count(retries)\n\n Modifies the number of retries for the scope of the ``with``\n statement (in the current thread).\n\n Example::\n\n with client.retry_count(10):\n client.ping()\n "
]
|
Please provide a description of the function:def _with_retries(self, pool, fn):
skip_nodes = []
def _skip_bad_nodes(transport):
return transport._node not in skip_nodes
retry_count = self.retries - 1
first_try = True
current_try = 0
while True:
try:
with pool.transaction(
_filter=_skip_bad_nodes,
yield_resource=True) as resource:
transport = resource.object
try:
return fn(transport)
except (IOError, HTTPException, ConnectionClosed) as e:
resource.errored = True
if _is_retryable(e):
transport._node.error_rate.incr(1)
skip_nodes.append(transport._node)
if first_try:
continue
else:
raise BadResource(e)
else:
raise
except BadResource as e:
if current_try < retry_count:
resource.errored = True
current_try += 1
continue
else:
# Re-raise the inner exception
raise e.args[0]
finally:
first_try = False | [
"\n Performs the passed function with retries against the given pool.\n\n :param pool: the connection pool to use\n :type pool: Pool\n :param fn: the function to pass a transport\n :type fn: function\n "
]
|
Please provide a description of the function:def _choose_pool(self, protocol=None):
if not protocol:
protocol = self.protocol
if protocol == 'http':
pool = self._http_pool
elif protocol == 'tcp' or protocol == 'pbc':
pool = self._tcp_pool
else:
raise ValueError("invalid protocol %s" % protocol)
if pool is None or self._closed:
# NB: GH-500, this can happen if client is closed
raise RuntimeError("Client is closed.")
return pool | [
"\n Selects a connection pool according to the default protocol\n and the passed one.\n\n :param protocol: the protocol to use\n :type protocol: string\n :rtype: Pool\n "
]
|
Please provide a description of the function:def default_encoder(obj):
if isinstance(obj, bytes):
return json.dumps(bytes_to_str(obj),
ensure_ascii=False).encode("utf-8")
else:
return json.dumps(obj, ensure_ascii=False).encode("utf-8") | [
"\n Default encoder for JSON datatypes, which returns UTF-8 encoded\n json instead of the default bloated backslash u XXXX escaped ASCII strings.\n "
]
|
Please provide a description of the function:def bucket(self, name, bucket_type='default'):
if not isinstance(name, string_types):
raise TypeError('Bucket name must be a string')
if isinstance(bucket_type, string_types):
bucket_type = self.bucket_type(bucket_type)
elif not isinstance(bucket_type, BucketType):
raise TypeError('bucket_type must be a string '
'or riak.bucket.BucketType')
b = RiakBucket(self, name, bucket_type)
return self._setdefault_handle_none(
self._buckets, (bucket_type, name), b) | [
"\n Get the bucket by the specified name. Since buckets always exist,\n this will always return a\n :class:`RiakBucket <riak.bucket.RiakBucket>`.\n\n If you are using a bucket that is contained in a bucket type, it is\n preferable to access it from the bucket type object::\n\n # Preferred:\n client.bucket_type(\"foo\").bucket(\"bar\")\n\n # Equivalent, but not preferred:\n client.bucket(\"bar\", bucket_type=\"foo\")\n\n :param name: the bucket name\n :type name: str\n :param bucket_type: the parent bucket-type\n :type bucket_type: :class:`BucketType <riak.bucket.BucketType>`\n or str\n :rtype: :class:`RiakBucket <riak.bucket.RiakBucket>`\n\n "
]
|
Please provide a description of the function:def bucket_type(self, name):
if not isinstance(name, string_types):
raise TypeError('BucketType name must be a string')
btype = BucketType(self, name)
return self._setdefault_handle_none(
self._bucket_types, name, btype) | [
"\n Gets the bucket-type by the specified name. Bucket-types do\n not always exist (unlike buckets), but this will always return\n a :class:`BucketType <riak.bucket.BucketType>` object.\n\n :param name: the bucket-type name\n :type name: str\n :rtype: :class:`BucketType <riak.bucket.BucketType>`\n "
]
|
Please provide a description of the function:def table(self, name):
if not isinstance(name, string_types):
raise TypeError('Table name must be a string')
if name in self._tables:
return self._tables[name]
else:
table = Table(self, name)
self._tables[name] = table
return table | [
"\n Gets the table by the specified name. Tables do\n not always exist (unlike buckets), but this will always return\n a :class:`Table <riak.table.Table>` object.\n\n :param name: the table name\n :type name: str\n :rtype: :class:`Table <riak.table.Table>`\n "
]
|
Please provide a description of the function:def close(self):
if not self._closed:
self._closed = True
self._stop_multi_pools()
if self._http_pool is not None:
self._http_pool.clear()
self._http_pool = None
if self._tcp_pool is not None:
self._tcp_pool.clear()
self._tcp_pool = None | [
"\n Iterate through all of the connections and close each one.\n "
]
|
Please provide a description of the function:def _create_credentials(self, n):
if not n:
return n
elif isinstance(n, SecurityCreds):
return n
elif isinstance(n, dict):
return SecurityCreds(**n)
else:
raise TypeError("%s is not a valid security configuration"
% repr(n)) | [
"\n Create security credentials, if necessary.\n "
]
|
Please provide a description of the function:def _choose_node(self, nodes=None):
if not nodes:
nodes = self.nodes
# Prefer nodes which have gone a reasonable time without
# errors
def _error_rate(node):
return node.error_rate.value()
good = [n for n in nodes if _error_rate(n) < 0.1]
if len(good) is 0:
# Fall back to a minimally broken node
return min(nodes, key=_error_rate)
else:
return random.choice(good) | [
"\n Chooses a random node from the list of nodes in the client,\n taking into account each node's recent error rate.\n :rtype RiakNode\n "
]
|
Please provide a description of the function:def _request(self, method, uri, headers={}, body='', stream=False):
response = None
headers.setdefault('Accept',
'multipart/mixed, application/json, */*;q=0.5')
if self._client._credentials:
self._security_auth_headers(self._client._credentials.username,
self._client._credentials.password,
headers)
try:
self._connection.request(method, uri, body, headers)
try:
response = self._connection.getresponse(buffering=True)
except TypeError:
response = self._connection.getresponse()
if stream:
# The caller is responsible for fully reading the
# response and closing it when streaming.
response_body = response
else:
response_body = response.read()
finally:
if response and not stream:
response.close()
return response.status, response.msg, response_body | [
"\n Given a Method, URL, Headers, and Body, perform and HTTP\n request, and return a 3-tuple containing the response status,\n response headers (as httplib.HTTPMessage), and response body.\n "
]
|
Please provide a description of the function:def _connect(self):
timeout = None
if self._options is not None and 'timeout' in self._options:
timeout = self._options['timeout']
if self._client._credentials:
self._connection = self._connection_class(
host=self._node.host,
port=self._node.http_port,
credentials=self._client._credentials,
timeout=timeout)
else:
self._connection = self._connection_class(
host=self._node.host,
port=self._node.http_port,
timeout=timeout)
# Forces the population of stats and resources before any
# other requests are made.
self.server_version | [
"\n Use the appropriate connection class; optionally with security.\n "
]
|
Please provide a description of the function:def _security_auth_headers(self, username, password, headers):
userColonPassword = username + ":" + password
b64UserColonPassword = base64. \
b64encode(str_to_bytes(userColonPassword)).decode("ascii")
headers['Authorization'] = 'Basic %s' % b64UserColonPassword | [
"\n Add in the requisite HTTP Authentication Headers\n\n :param username: Riak Security Username\n :type str\n :param password: Riak Security Password\n :type str\n :param headers: Dictionary of headers\n :type dict\n "
]
|
Please provide a description of the function:def new(self, rows, columns=None):
from riak.ts_object import TsObject
return TsObject(self._client, self, rows, columns) | [
"\n A shortcut for manually instantiating a new\n :class:`~riak.ts_object.TsObject`\n\n :param rows: An list of lists with timeseries data\n :type rows: list\n :param columns: An list of Column names and types. Optional.\n :type columns: list\n :rtype: :class:`~riak.ts_object.TsObject`\n "
]
|
Please provide a description of the function:def query(self, query, interpolations=None):
return self._client.ts_query(self, query, interpolations) | [
"\n Queries a timeseries table.\n\n :param query: The timeseries query.\n :type query: string\n :rtype: :class:`TsObject <riak.ts_object.TsObject>`\n "
]
|
Please provide a description of the function:def getConfigDirectory():
if platform.system() == 'Windows':
return os.path.join(os.environ['APPDATA'], 'ue4cli')
else:
return os.path.join(os.environ['HOME'], '.config', 'ue4cli') | [
"\n\t\tDetermines the platform-specific config directory location for ue4cli\n\t\t"
]
|
Please provide a description of the function:def setConfigKey(key, value):
configFile = ConfigurationManager._configFile()
return JsonDataManager(configFile).setKey(key, value) | [
"\n\t\tSets the config data value for the specified dictionary key\n\t\t"
]
|
Please provide a description of the function:def clearCache():
if os.path.exists(CachedDataManager._cacheDir()) == True:
shutil.rmtree(CachedDataManager._cacheDir()) | [
"\n\t\tClears any cached data we have stored about specific engine versions\n\t\t"
]
|
Please provide a description of the function:def getCachedDataKey(engineVersionHash, key):
cacheFile = CachedDataManager._cacheFileForHash(engineVersionHash)
return JsonDataManager(cacheFile).getKey(key) | [
"\n\t\tRetrieves the cached data value for the specified engine version hash and dictionary key\n\t\t"
]
|
Please provide a description of the function:def setCachedDataKey(engineVersionHash, key, value):
cacheFile = CachedDataManager._cacheFileForHash(engineVersionHash)
return JsonDataManager(cacheFile).setKey(key, value) | [
"\n\t\tSets the cached data value for the specified engine version hash and dictionary key\n\t\t"
]
|
Please provide a description of the function:def writeFile(filename, data):
with open(filename, 'wb') as f:
f.write(data.encode('utf-8')) | [
"\n\t\tWrites data to a file\n\t\t"
]
|
Please provide a description of the function:def patchFile(filename, replacements):
patched = Utility.readFile(filename)
# Perform each of the replacements in the supplied dictionary
for key in replacements:
patched = patched.replace(key, replacements[key])
Utility.writeFile(filename, patched) | [
"\n\t\tApplies the supplied list of replacements to a file\n\t\t"
]
|
Please provide a description of the function:def escapePathForShell(path):
if platform.system() == 'Windows':
return '"{}"'.format(path.replace('"', '""'))
else:
return shellescape.quote(path) | [
"\n\t\tEscapes a filesystem path for use as a command-line argument\n\t\t"
]
|
Please provide a description of the function:def stripArgs(args, blacklist):
blacklist = [b.lower() for b in blacklist]
return list([arg for arg in args if arg.lower() not in blacklist]) | [
"\n\t\tRemoves any arguments in the supplied list that are contained in the specified blacklist\n\t\t"
]
|
Please provide a description of the function:def capture(command, input=None, cwd=None, shell=False, raiseOnError=False):
# Attempt to execute the child process
proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, shell=shell, universal_newlines=True)
(stdout, stderr) = proc.communicate(input)
# If the child process failed and we were asked to raise an exception, do so
if raiseOnError == True and proc.returncode != 0:
raise Exception(
'child process ' + str(command) +
' failed with exit code ' + str(proc.returncode) +
'\nstdout: "' + stdout + '"' +
'\nstderr: "' + stderr + '"'
)
return CommandOutput(proc.returncode, stdout, stderr) | [
"\n\t\tExecutes a child process and captures its output\n\t\t"
]
|
Please provide a description of the function:def run(command, cwd=None, shell=False, raiseOnError=False):
returncode = subprocess.call(command, cwd=cwd, shell=shell)
if raiseOnError == True and returncode != 0:
raise Exception('child process ' + str(command) + ' failed with exit code ' + str(returncode))
return returncode | [
"\n\t\tExecutes a child process and waits for it to complete\n\t\t"
]
|
Please provide a description of the function:def setEngineRootOverride(self, rootDir):
# Set the new root directory
ConfigurationManager.setConfigKey('rootDirOverride', os.path.abspath(rootDir))
# Check that the specified directory is valid and warn the user if it is not
try:
self.getEngineVersion()
except:
print('Warning: the specified directory does not appear to contain a valid version of the Unreal Engine.') | [
"\n\t\tSets a user-specified directory as the root engine directory, overriding any auto-detection\n\t\t"
]
|
Please provide a description of the function:def getEngineRoot(self):
if not hasattr(self, '_engineRoot'):
self._engineRoot = self._getEngineRoot()
return self._engineRoot | [
"\n\t\tReturns the root directory location of the latest installed version of UE4\n\t\t"
]
|
Please provide a description of the function:def getEngineVersion(self, outputFormat = 'full'):
version = self._getEngineVersionDetails()
formats = {
'major': version['MajorVersion'],
'minor': version['MinorVersion'],
'patch': version['PatchVersion'],
'full': '{}.{}.{}'.format(version['MajorVersion'], version['MinorVersion'], version['PatchVersion']),
'short': '{}.{}'.format(version['MajorVersion'], version['MinorVersion'])
}
# Verify that the requested output format is valid
if outputFormat not in formats:
raise Exception('unreconised version output format "{}"'.format(outputFormat))
return formats[outputFormat] | [
"\n\t\tReturns the version number of the latest installed version of UE4\n\t\t"
]
|
Please provide a description of the function:def getEngineChangelist(self):
# Newer versions of the engine use the key "CompatibleChangelist", older ones use "Changelist"
version = self._getEngineVersionDetails()
if 'CompatibleChangelist' in version:
return int(version['CompatibleChangelist'])
else:
return int(version['Changelist']) | [
"\n\t\tReturns the compatible Perforce changelist identifier for the latest installed version of UE4\n\t\t"
]
|
Please provide a description of the function:def isInstalledBuild(self):
sentinelFile = os.path.join(self.getEngineRoot(), 'Engine', 'Build', 'InstalledBuild.txt')
return os.path.exists(sentinelFile) | [
"\n\t\tDetermines if the Engine is an Installed Build\n\t\t"
]
|
Please provide a description of the function:def getEditorBinary(self, cmdVersion=False):
return os.path.join(self.getEngineRoot(), 'Engine', 'Binaries', self.getPlatformIdentifier(), 'UE4Editor' + self._editorPathSuffix(cmdVersion)) | [
"\n\t\tDetermines the location of the UE4Editor binary\n\t\t"
]
|
Please provide a description of the function:def getProjectDescriptor(self, dir):
for project in glob.glob(os.path.join(dir, '*.uproject')):
return os.path.realpath(project)
# No project detected
raise UnrealManagerException('could not detect an Unreal project in the current directory') | [
"\n\t\tDetects the .uproject descriptor file for the Unreal project in the specified directory\n\t\t"
]
|
Please provide a description of the function:def getPluginDescriptor(self, dir):
for plugin in glob.glob(os.path.join(dir, '*.uplugin')):
return os.path.realpath(plugin)
# No plugin detected
raise UnrealManagerException('could not detect an Unreal plugin in the current directory') | [
"\n\t\tDetects the .uplugin descriptor file for the Unreal plugin in the specified directory\n\t\t"
]
|
Please provide a description of the function:def getDescriptor(self, dir):
try:
return self.getProjectDescriptor(dir)
except:
try:
return self.getPluginDescriptor(dir)
except:
raise UnrealManagerException('could not detect an Unreal project or plugin in the directory "{}"'.format(dir)) | [
"\n\t\tDetects the descriptor file for either an Unreal project or an Unreal plugin in the specified directory\n\t\t"
]
|
Please provide a description of the function:def listThirdPartyLibs(self, configuration = 'Development'):
interrogator = self._getUE4BuildInterrogator()
return interrogator.list(self.getPlatformIdentifier(), configuration, self._getLibraryOverrides()) | [
"\n\t\tLists the supported Unreal-bundled third-party libraries\n\t\t"
]
|
Please provide a description of the function:def getThirdpartyLibs(self, libs, configuration = 'Development', includePlatformDefaults = True):
if includePlatformDefaults == True:
libs = self._defaultThirdpartyLibs() + libs
interrogator = self._getUE4BuildInterrogator()
return interrogator.interrogate(self.getPlatformIdentifier(), configuration, libs, self._getLibraryOverrides()) | [
"\n\t\tRetrieves the ThirdPartyLibraryDetails instance for Unreal-bundled versions of the specified third-party libraries\n\t\t"
]
|
Please provide a description of the function:def getThirdPartyLibCompilerFlags(self, libs):
fmt = PrintingFormat.singleLine()
if libs[0] == '--multiline':
fmt = PrintingFormat.multiLine()
libs = libs[1:]
platformDefaults = True
if libs[0] == '--nodefaults':
platformDefaults = False
libs = libs[1:]
details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults)
return details.getCompilerFlags(self.getEngineRoot(), fmt) | [
"\n\t\tRetrieves the compiler flags for building against the Unreal-bundled versions of the specified third-party libraries\n\t\t"
]
|
Please provide a description of the function:def getThirdPartyLibLinkerFlags(self, libs):
fmt = PrintingFormat.singleLine()
if libs[0] == '--multiline':
fmt = PrintingFormat.multiLine()
libs = libs[1:]
includeLibs = True
if (libs[0] == '--flagsonly'):
includeLibs = False
libs = libs[1:]
platformDefaults = True
if libs[0] == '--nodefaults':
platformDefaults = False
libs = libs[1:]
details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults)
return details.getLinkerFlags(self.getEngineRoot(), fmt, includeLibs) | [
"\n\t\tRetrieves the linker flags for building against the Unreal-bundled versions of the specified third-party libraries\n\t\t"
]
|
Please provide a description of the function:def getThirdPartyLibCmakeFlags(self, libs):
fmt = PrintingFormat.singleLine()
if libs[0] == '--multiline':
fmt = PrintingFormat.multiLine()
libs = libs[1:]
platformDefaults = True
if libs[0] == '--nodefaults':
platformDefaults = False
libs = libs[1:]
details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults)
CMakeCustomFlags.processLibraryDetails(details)
return details.getCMakeFlags(self.getEngineRoot(), fmt) | [
"\n\t\tRetrieves the CMake invocation flags for building against the Unreal-bundled versions of the specified third-party libraries\n\t\t"
]
|
Please provide a description of the function:def getThirdPartyLibIncludeDirs(self, libs):
platformDefaults = True
if libs[0] == '--nodefaults':
platformDefaults = False
libs = libs[1:]
details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults)
return details.getIncludeDirectories(self.getEngineRoot(), delimiter='\n') | [
"\n\t\tRetrieves the list of include directories for building against the Unreal-bundled versions of the specified third-party libraries\n\t\t"
]
|
Please provide a description of the function:def getThirdPartyLibFiles(self, libs):
platformDefaults = True
if libs[0] == '--nodefaults':
platformDefaults = False
libs = libs[1:]
details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults)
return details.getLibraryFiles(self.getEngineRoot(), delimiter='\n') | [
"\n\t\tRetrieves the list of library files for building against the Unreal-bundled versions of the specified third-party libraries\n\t\t"
]
|
Please provide a description of the function:def getThirdPartyLibDefinitions(self, libs):
platformDefaults = True
if libs[0] == '--nodefaults':
platformDefaults = False
libs = libs[1:]
details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults)
return details.getPreprocessorDefinitions(self.getEngineRoot(), delimiter='\n') | [
"\n\t\tRetrieves the list of preprocessor definitions for building against the Unreal-bundled versions of the specified third-party libraries\n\t\t"
]
|
Please provide a description of the function:def generateProjectFiles(self, dir=os.getcwd(), args=[]):
# If the project is a pure Blueprint project, then we cannot generate project files
if os.path.exists(os.path.join(dir, 'Source')) == False:
Utility.printStderr('Pure Blueprint project, nothing to generate project files for.')
return
# Generate the project files
genScript = self.getGenerateScript()
projectFile = self.getProjectDescriptor(dir)
Utility.run([genScript, '-project=' + projectFile, '-game', '-engine'] + args, cwd=os.path.dirname(genScript), raiseOnError=True) | [
"\n\t\tGenerates IDE project files for the Unreal project in the specified directory\n\t\t"
]
|
Please provide a description of the function:def cleanDescriptor(self, dir=os.getcwd()):
# Verify that an Unreal project or plugin exists in the specified directory
descriptor = self.getDescriptor(dir)
# Because performing a clean will also delete the engine build itself when using
# a source build, we simply delete the `Binaries` and `Intermediate` directories
shutil.rmtree(os.path.join(dir, 'Binaries'), ignore_errors=True)
shutil.rmtree(os.path.join(dir, 'Intermediate'), ignore_errors=True)
# If we are cleaning a project, also clean any plugins
if self.isProject(descriptor):
projectPlugins = glob.glob(os.path.join(dir, 'Plugins', '*'))
for pluginDir in projectPlugins:
self.cleanDescriptor(pluginDir) | [
"\n\t\tCleans the build artifacts for the Unreal project or plugin in the specified directory\n\t\t"
]
|
Please provide a description of the function:def buildDescriptor(self, dir=os.getcwd(), configuration='Development', args=[], suppressOutput=False):
# Verify that an Unreal project or plugin exists in the specified directory
descriptor = self.getDescriptor(dir)
descriptorType = 'project' if self.isProject(descriptor) else 'plugin'
# If the project or plugin is Blueprint-only, there is no C++ code to build
if os.path.exists(os.path.join(dir, 'Source')) == False:
Utility.printStderr('Pure Blueprint {}, nothing to build.'.format(descriptorType))
return
# Verify that the specified build configuration is valid
if configuration not in self.validBuildConfigurations():
raise UnrealManagerException('invalid build configuration "' + configuration + '"')
# Generate the arguments to pass to UBT
target = self.getDescriptorName(descriptor) + 'Editor' if self.isProject(descriptor) else 'UE4Editor'
baseArgs = ['-{}='.format(descriptorType) + descriptor]
# Perform the build
self._runUnrealBuildTool(target, self.getPlatformIdentifier(), configuration, baseArgs + args, capture=suppressOutput) | [
"\n\t\tBuilds the editor modules for the Unreal project or plugin in the specified directory, using the specified build configuration\n\t\t"
]
|
Please provide a description of the function:def runEditor(self, dir=os.getcwd(), debug=False, args=[]):
projectFile = self.getProjectDescriptor(dir) if dir is not None else ''
extraFlags = ['-debug'] + args if debug == True else args
Utility.run([self.getEditorBinary(True), projectFile, '-stdout', '-FullStdOutLogOutput'] + extraFlags, raiseOnError=True) | [
"\n\t\tRuns the editor for the Unreal project in the specified directory (or without a project if dir is None)\n\t\t"
]
|
Please provide a description of the function:def runUAT(self, args):
Utility.run([self.getRunUATScript()] + args, cwd=self.getEngineRoot(), raiseOnError=True) | [
"\n\t\tRuns the Unreal Automation Tool with the supplied arguments\n\t\t"
]
|
Please provide a description of the function:def packageProject(self, dir=os.getcwd(), configuration='Shipping', extraArgs=[]):
# Verify that the specified build configuration is valid
if configuration not in self.validBuildConfigurations():
raise UnrealManagerException('invalid build configuration "' + configuration + '"')
# Strip out the `-NoCompileEditor` flag if the user has specified it, since the Development version
# of the Editor modules for the project are needed in order to run the commandlet that cooks content
extraArgs = Utility.stripArgs(extraArgs, ['-nocompileeditor'])
# Prevent the user from specifying multiple `-platform=` or `-targetplatform=` arguments,
# and use the current host platform if no platform argument was explicitly specified
platformArgs = Utility.findArgs(extraArgs, ['-platform=', '-targetplatform='])
platform = Utility.getArgValue(platformArgs[0]) if len(platformArgs) > 0 else self.getPlatformIdentifier()
extraArgs = Utility.stripArgs(extraArgs, platformArgs) + ['-platform={}'.format(platform)]
# If we are packaging a Shipping build, do not include debug symbols
if configuration == 'Shipping':
extraArgs.append('-nodebuginfo')
# Do not create a .pak file when packaging for HTML5
pakArg = '-package' if platform.upper() == 'HTML5' else '-pak'
# Invoke UAT to package the build
distDir = os.path.join(os.path.abspath(dir), 'dist')
self.runUAT([
'BuildCookRun',
'-utf8output',
'-clientconfig=' + configuration,
'-serverconfig=' + configuration,
'-project=' + self.getProjectDescriptor(dir),
'-noP4',
'-cook',
'-allmaps',
'-build',
'-stage',
'-prereqs',
pakArg,
'-archive',
'-archivedirectory=' + distDir
] + extraArgs) | [
"\n\t\tPackages a build of the Unreal project in the specified directory, using common packaging options\n\t\t"
]
|
Please provide a description of the function:def packagePlugin(self, dir=os.getcwd(), extraArgs=[]):
# Invoke UAT to package the build
distDir = os.path.join(os.path.abspath(dir), 'dist')
self.runUAT([
'BuildPlugin',
'-Plugin=' + self.getPluginDescriptor(dir),
'-Package=' + distDir
] + extraArgs) | [
"\n\t\tPackages a build of the Unreal plugin in the specified directory, suitable for use as a prebuilt Engine module\n\t\t"
]
|
Please provide a description of the function:def packageDescriptor(self, dir=os.getcwd(), args=[]):
# Verify that an Unreal project or plugin exists in the specified directory
descriptor = self.getDescriptor(dir)
# Perform the packaging step
if self.isProject(descriptor):
self.packageProject(dir, args[0] if len(args) > 0 else 'Shipping', args[1:])
else:
self.packagePlugin(dir, args) | [
"\n\t\tPackages a build of the Unreal project or plugin in the specified directory\n\t\t"
]
|
Please provide a description of the function:def runAutomationCommands(self, projectFile, commands, capture=False):
'''
Invokes the Automation Test commandlet for the specified project with the supplied automation test commands
'''
# IMPORTANT IMPLEMENTATION NOTE:
# We need to format the command as a string and execute it using a shell in order to
# ensure the "-ExecCmds" argument will be parsed correctly under Windows. This is because
# the WinMain() function uses GetCommandLineW() to retrieve the raw command-line string,
# rather than using an argv-style structure. The string is then passed to FParse::Value(),
# which checks for the presence of a quote character after the equals sign to determine if
# whitespace should be stripped or preserved. Without the quote character, the spaces in the
# argument payload will be stripped out, corrupting our list of automation commands and
# preventing them from executing correctly.
command = '{} {}'.format(Utility.escapePathForShell(self.getEditorBinary(True)), Utility.escapePathForShell(projectFile))
command += ' -game -buildmachine -stdout -fullstdoutlogoutput -forcelogflush -unattended -nopause -nullrhi -nosplash'
command += ' -ExecCmds="automation {};quit"'.format(';'.join(commands))
if capture == True:
return Utility.capture(command, shell=True)
else:
Utility.run(command, shell=True) | []
|
Please provide a description of the function:def _getEngineRoot(self):
override = ConfigurationManager.getConfigKey('rootDirOverride')
if override != None:
Utility.printStderr('Using user-specified engine root: ' + override)
return override
else:
return self._detectEngineRoot() | [
"\n\t\tRetrieves the user-specified engine root directory override (if set), or else performs auto-detection\n\t\t"
]
|
Please provide a description of the function:def _getEngineVersionDetails(self):
versionFile = os.path.join(self.getEngineRoot(), 'Engine', 'Build', 'Build.version')
return json.loads(Utility.readFile(versionFile)) | [
"\n\t\tParses the JSON version details for the latest installed version of UE4\n\t\t"
]
|
Please provide a description of the function:def _getEngineVersionHash(self):
versionDetails = self._getEngineVersionDetails()
hash = hashlib.sha256()
hash.update(json.dumps(versionDetails, sort_keys=True, indent=0).encode('utf-8'))
return hash.hexdigest() | [
"\n\t\tComputes the SHA-256 hash of the JSON version details for the latest installed version of UE4\n\t\t"
]
|
Please provide a description of the function:def _runUnrealBuildTool(self, target, platform, configuration, args, capture=False):
platform = self._transformBuildToolPlatform(platform)
arguments = [self.getBuildScript(), target, platform, configuration] + args
if capture == True:
return Utility.capture(arguments, cwd=self.getEngineRoot(), raiseOnError=True)
else:
Utility.run(arguments, cwd=self.getEngineRoot(), raiseOnError=True) | [
"\n\t\tInvokes UnrealBuildTool with the specified parameters\n\t\t"
]
|
Please provide a description of the function:def _getUE4BuildInterrogator(self):
ubtLambda = lambda target, platform, config, args: self._runUnrealBuildTool(target, platform, config, args, True)
interrogator = UE4BuildInterrogator(self.getEngineRoot(), self._getEngineVersionDetails(), self._getEngineVersionHash(), ubtLambda)
return interrogator | [
"\n\t\tUses UE4BuildInterrogator to interrogate UnrealBuildTool about third-party library details\n\t\t"
]
|
Please provide a description of the function:def getKey(self, key):
data = self.getDictionary()
if key in data:
return data[key]
else:
return None | [
"\n\t\tRetrieves the value for the specified dictionary key\n\t\t"
]
|
Please provide a description of the function:def getDictionary(self):
if os.path.exists(self.jsonFile):
return json.loads(Utility.readFile(self.jsonFile))
else:
return {} | [
"\n\t\tRetrieves the entire data dictionary\n\t\t"
]
|
Please provide a description of the function:def setKey(self, key, value):
data = self.getDictionary()
data[key] = value
self.setDictionary(data) | [
"\n\t\tSets the value for the specified dictionary key\n\t\t"
]
|
Please provide a description of the function:def setDictionary(self, data):
# Create the directory containing the JSON file if it doesn't already exist
jsonDir = os.path.dirname(self.jsonFile)
if os.path.exists(jsonDir) == False:
os.makedirs(jsonDir)
# Store the dictionary
Utility.writeFile(self.jsonFile, json.dumps(data)) | [
"\n\t\tOverwrites the entire dictionary\n\t\t"
]
|
Please provide a description of the function:def list(self, platformIdentifier, configuration, libOverrides = {}):
modules = self._getThirdPartyLibs(platformIdentifier, configuration)
return sorted([m['Name'] for m in modules] + [key for key in libOverrides]) | [
"\n\t\tReturns the list of supported UE4-bundled third-party libraries\n\t\t"
]
|
Please provide a description of the function:def interrogate(self, platformIdentifier, configuration, libraries, libOverrides = {}):
# Determine which libraries need their modules parsed by UBT, and which are override-only
libModules = list([lib for lib in libraries if lib not in libOverrides])
# Check that we have at least one module to parse
details = ThirdPartyLibraryDetails()
if len(libModules) > 0:
# Retrieve the list of third-party library modules from UnrealBuildTool
modules = self._getThirdPartyLibs(platformIdentifier, configuration)
# Filter the list of modules to include only those that were requested
modules = [m for m in modules if m['Name'] in libModules]
# Emit a warning if any of the requested modules are not supported
names = [m['Name'] for m in modules]
unsupported = ['"' + m + '"' for m in libModules if m not in names]
if len(unsupported) > 0:
Utility.printStderr('Warning: unsupported libraries ' + ','.join(unsupported))
# Some libraries are listed as just the filename without the leading directory (especially prevalent under Windows)
for module in modules:
if len(module['PublicAdditionalLibraries']) > 0 and len(module['PublicLibraryPaths']) > 0:
libPath = (self._absolutePaths(module['PublicLibraryPaths']))[0]
libs = list([lib.replace('\\', '/') for lib in module['PublicAdditionalLibraries']])
libs = list([os.path.join(libPath, lib) if '/' not in lib else lib for lib in libs])
module['PublicAdditionalLibraries'] = libs
# Flatten the lists of paths
fields = [
'Directory',
'PublicAdditionalLibraries',
'PublicLibraryPaths',
'PublicSystemIncludePaths',
'PublicIncludePaths',
'PrivateIncludePaths',
'PublicDefinitions'
]
flattened = {}
for field in fields:
transform = (lambda l: self._absolutePaths(l)) if field != 'Definitions' else None
flattened[field] = self._flatten(field, modules, transform)
# Compose the prefix directories from the module root directories, the header and library paths, and their direct parent directories
libraryDirectories = flattened['PublicLibraryPaths']
headerDirectories = flattened['PublicSystemIncludePaths'] + flattened['PublicIncludePaths'] + flattened['PrivateIncludePaths']
modulePaths = flattened['Directory']
prefixDirectories = list(set(flattened['Directory'] + headerDirectories + libraryDirectories + [os.path.dirname(p) for p in headerDirectories + libraryDirectories]))
# Wrap the results in a ThirdPartyLibraryDetails instance, converting any relative directory paths into absolute ones
details = ThirdPartyLibraryDetails(
prefixDirs = prefixDirectories,
includeDirs = headerDirectories,
linkDirs = libraryDirectories,
definitions = flattened['PublicDefinitions'],
libs = flattened['PublicAdditionalLibraries']
)
# Apply any overrides
overridesToApply = list([libOverrides[lib] for lib in libraries if lib in libOverrides])
for override in overridesToApply:
details.merge(override)
return details | [
"\n\t\tInterrogates UnrealBuildTool about the build flags for the specified third-party libraries\n\t\t"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.