id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
232,300 | readbeyond/aeneas | aeneas/vad.py | VAD._compute_runs | def _compute_runs(self, array):
"""
Compute runs as a list of arrays,
each containing the indices of a contiguous run.
:param array: the data array
:type array: numpy 1D array
:rtype: list of numpy 1D arrays
"""
if len(array) < 1:
return []
return numpy.split(array, numpy.where(numpy.diff(array) != 1)[0] + 1) | python | def _compute_runs(self, array):
"""
Compute runs as a list of arrays,
each containing the indices of a contiguous run.
:param array: the data array
:type array: numpy 1D array
:rtype: list of numpy 1D arrays
"""
if len(array) < 1:
return []
return numpy.split(array, numpy.where(numpy.diff(array) != 1)[0] + 1) | [
"def",
"_compute_runs",
"(",
"self",
",",
"array",
")",
":",
"if",
"len",
"(",
"array",
")",
"<",
"1",
":",
"return",
"[",
"]",
"return",
"numpy",
".",
"split",
"(",
"array",
",",
"numpy",
".",
"where",
"(",
"numpy",
".",
"diff",
"(",
"array",
")",
"!=",
"1",
")",
"[",
"0",
"]",
"+",
"1",
")"
] | Compute runs as a list of arrays,
each containing the indices of a contiguous run.
:param array: the data array
:type array: numpy 1D array
:rtype: list of numpy 1D arrays | [
"Compute",
"runs",
"as",
"a",
"list",
"of",
"arrays",
"each",
"containing",
"the",
"indices",
"of",
"a",
"contiguous",
"run",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/vad.py#L134-L145 |
232,301 | readbeyond/aeneas | aeneas/vad.py | VAD._rolling_window | def _rolling_window(self, array, size):
"""
Compute rolling windows of width ``size`` of the given array.
Return a numpy 2D stride array,
where rows are the windows, each of ``size`` elements.
:param array: the data array
:type array: numpy 1D array (n)
:param int size: the width of each window
:rtype: numpy 2D stride array (n // size, size)
"""
shape = array.shape[:-1] + (array.shape[-1] - size + 1, size)
strides = array.strides + (array.strides[-1],)
return numpy.lib.stride_tricks.as_strided(array, shape=shape, strides=strides) | python | def _rolling_window(self, array, size):
"""
Compute rolling windows of width ``size`` of the given array.
Return a numpy 2D stride array,
where rows are the windows, each of ``size`` elements.
:param array: the data array
:type array: numpy 1D array (n)
:param int size: the width of each window
:rtype: numpy 2D stride array (n // size, size)
"""
shape = array.shape[:-1] + (array.shape[-1] - size + 1, size)
strides = array.strides + (array.strides[-1],)
return numpy.lib.stride_tricks.as_strided(array, shape=shape, strides=strides) | [
"def",
"_rolling_window",
"(",
"self",
",",
"array",
",",
"size",
")",
":",
"shape",
"=",
"array",
".",
"shape",
"[",
":",
"-",
"1",
"]",
"+",
"(",
"array",
".",
"shape",
"[",
"-",
"1",
"]",
"-",
"size",
"+",
"1",
",",
"size",
")",
"strides",
"=",
"array",
".",
"strides",
"+",
"(",
"array",
".",
"strides",
"[",
"-",
"1",
"]",
",",
")",
"return",
"numpy",
".",
"lib",
".",
"stride_tricks",
".",
"as_strided",
"(",
"array",
",",
"shape",
"=",
"shape",
",",
"strides",
"=",
"strides",
")"
] | Compute rolling windows of width ``size`` of the given array.
Return a numpy 2D stride array,
where rows are the windows, each of ``size`` elements.
:param array: the data array
:type array: numpy 1D array (n)
:param int size: the width of each window
:rtype: numpy 2D stride array (n // size, size) | [
"Compute",
"rolling",
"windows",
"of",
"width",
"size",
"of",
"the",
"given",
"array",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/vad.py#L148-L162 |
232,302 | pysam-developers/pysam | pysam/utils.py | PysamDispatcher.usage | def usage(self):
'''return the samtools usage information for this command'''
retval, stderr, stdout = _pysam_dispatch(
self.collection,
self.dispatch,
is_usage=True,
catch_stdout=True)
# some tools write usage to stderr, such as mpileup
if stderr:
return stderr
else:
return stdout | python | def usage(self):
'''return the samtools usage information for this command'''
retval, stderr, stdout = _pysam_dispatch(
self.collection,
self.dispatch,
is_usage=True,
catch_stdout=True)
# some tools write usage to stderr, such as mpileup
if stderr:
return stderr
else:
return stdout | [
"def",
"usage",
"(",
"self",
")",
":",
"retval",
",",
"stderr",
",",
"stdout",
"=",
"_pysam_dispatch",
"(",
"self",
".",
"collection",
",",
"self",
".",
"dispatch",
",",
"is_usage",
"=",
"True",
",",
"catch_stdout",
"=",
"True",
")",
"# some tools write usage to stderr, such as mpileup",
"if",
"stderr",
":",
"return",
"stderr",
"else",
":",
"return",
"stdout"
] | return the samtools usage information for this command | [
"return",
"the",
"samtools",
"usage",
"information",
"for",
"this",
"command"
] | 9961bebd4cd1f2bf5e42817df25699a6e6344b5a | https://github.com/pysam-developers/pysam/blob/9961bebd4cd1f2bf5e42817df25699a6e6344b5a/pysam/utils.py#L93-L104 |
232,303 | pysam-developers/pysam | pysam/Pileup.py | iterate | def iterate(infile):
'''iterate over ``samtools pileup -c`` formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type :class:`pysam.Pileup.PileupSubstitution`
or :class:`pysam.Pileup.PileupIndel`.
.. note::
The parser converts to 0-based coordinates
'''
conv_subst = (str, lambda x: int(x) - 1, str,
str, int, int, int, int, str, str)
conv_indel = (str, lambda x: int(x) - 1, str, str, int,
int, int, int, str, str, int, int, int)
for line in infile:
d = line[:-1].split()
if d[2] == "*":
try:
yield PileupIndel(*[x(y) for x, y in zip(conv_indel, d)])
except TypeError:
raise pysam.SamtoolsError("parsing error in line: `%s`" % line)
else:
try:
yield PileupSubstitution(*[x(y) for x, y in zip(conv_subst, d)])
except TypeError:
raise pysam.SamtoolsError("parsing error in line: `%s`" % line) | python | def iterate(infile):
'''iterate over ``samtools pileup -c`` formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type :class:`pysam.Pileup.PileupSubstitution`
or :class:`pysam.Pileup.PileupIndel`.
.. note::
The parser converts to 0-based coordinates
'''
conv_subst = (str, lambda x: int(x) - 1, str,
str, int, int, int, int, str, str)
conv_indel = (str, lambda x: int(x) - 1, str, str, int,
int, int, int, str, str, int, int, int)
for line in infile:
d = line[:-1].split()
if d[2] == "*":
try:
yield PileupIndel(*[x(y) for x, y in zip(conv_indel, d)])
except TypeError:
raise pysam.SamtoolsError("parsing error in line: `%s`" % line)
else:
try:
yield PileupSubstitution(*[x(y) for x, y in zip(conv_subst, d)])
except TypeError:
raise pysam.SamtoolsError("parsing error in line: `%s`" % line) | [
"def",
"iterate",
"(",
"infile",
")",
":",
"conv_subst",
"=",
"(",
"str",
",",
"lambda",
"x",
":",
"int",
"(",
"x",
")",
"-",
"1",
",",
"str",
",",
"str",
",",
"int",
",",
"int",
",",
"int",
",",
"int",
",",
"str",
",",
"str",
")",
"conv_indel",
"=",
"(",
"str",
",",
"lambda",
"x",
":",
"int",
"(",
"x",
")",
"-",
"1",
",",
"str",
",",
"str",
",",
"int",
",",
"int",
",",
"int",
",",
"int",
",",
"str",
",",
"str",
",",
"int",
",",
"int",
",",
"int",
")",
"for",
"line",
"in",
"infile",
":",
"d",
"=",
"line",
"[",
":",
"-",
"1",
"]",
".",
"split",
"(",
")",
"if",
"d",
"[",
"2",
"]",
"==",
"\"*\"",
":",
"try",
":",
"yield",
"PileupIndel",
"(",
"*",
"[",
"x",
"(",
"y",
")",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"conv_indel",
",",
"d",
")",
"]",
")",
"except",
"TypeError",
":",
"raise",
"pysam",
".",
"SamtoolsError",
"(",
"\"parsing error in line: `%s`\"",
"%",
"line",
")",
"else",
":",
"try",
":",
"yield",
"PileupSubstitution",
"(",
"*",
"[",
"x",
"(",
"y",
")",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"conv_subst",
",",
"d",
")",
"]",
")",
"except",
"TypeError",
":",
"raise",
"pysam",
".",
"SamtoolsError",
"(",
"\"parsing error in line: `%s`\"",
"%",
"line",
")"
] | iterate over ``samtools pileup -c`` formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type :class:`pysam.Pileup.PileupSubstitution`
or :class:`pysam.Pileup.PileupIndel`.
.. note::
The parser converts to 0-based coordinates | [
"iterate",
"over",
"samtools",
"pileup",
"-",
"c",
"formatted",
"file",
"."
] | 9961bebd4cd1f2bf5e42817df25699a6e6344b5a | https://github.com/pysam-developers/pysam/blob/9961bebd4cd1f2bf5e42817df25699a6e6344b5a/pysam/Pileup.py#L35-L64 |
232,304 | pysam-developers/pysam | pysam/Pileup.py | vcf2pileup | def vcf2pileup(vcf, sample):
'''convert vcf record to pileup record.'''
chromosome = vcf.contig
pos = vcf.pos
reference = vcf.ref
allelles = [reference] + vcf.alt
data = vcf[sample]
# get genotype
genotypes = data["GT"]
if len(genotypes) > 1:
raise ValueError("only single genotype per position, %s" % (str(vcf)))
genotypes = genotypes[0]
# not a variant
if genotypes[0] == ".":
return None
genotypes = [allelles[int(x)] for x in genotypes if x != "/"]
# snp_quality is "genotype quality"
snp_quality = consensus_quality = data.get("GQ", [0])[0]
mapping_quality = vcf.info.get("MQ", [0])[0]
coverage = data.get("DP", 0)
if len(reference) > 1 or max([len(x) for x in vcf.alt]) > 1:
# indel
genotype, offset = translateIndelGenotypeFromVCF(genotypes, reference)
return PileupIndel(chromosome,
pos + offset,
"*",
genotype,
consensus_quality,
snp_quality,
mapping_quality,
coverage,
genotype,
"<" * len(genotype),
0,
0,
0)
else:
genotype = encodeGenotype("".join(genotypes))
read_bases = ""
base_qualities = ""
return PileupSubstitution(chromosome, pos, reference,
genotype, consensus_quality,
snp_quality, mapping_quality,
coverage, read_bases,
base_qualities) | python | def vcf2pileup(vcf, sample):
'''convert vcf record to pileup record.'''
chromosome = vcf.contig
pos = vcf.pos
reference = vcf.ref
allelles = [reference] + vcf.alt
data = vcf[sample]
# get genotype
genotypes = data["GT"]
if len(genotypes) > 1:
raise ValueError("only single genotype per position, %s" % (str(vcf)))
genotypes = genotypes[0]
# not a variant
if genotypes[0] == ".":
return None
genotypes = [allelles[int(x)] for x in genotypes if x != "/"]
# snp_quality is "genotype quality"
snp_quality = consensus_quality = data.get("GQ", [0])[0]
mapping_quality = vcf.info.get("MQ", [0])[0]
coverage = data.get("DP", 0)
if len(reference) > 1 or max([len(x) for x in vcf.alt]) > 1:
# indel
genotype, offset = translateIndelGenotypeFromVCF(genotypes, reference)
return PileupIndel(chromosome,
pos + offset,
"*",
genotype,
consensus_quality,
snp_quality,
mapping_quality,
coverage,
genotype,
"<" * len(genotype),
0,
0,
0)
else:
genotype = encodeGenotype("".join(genotypes))
read_bases = ""
base_qualities = ""
return PileupSubstitution(chromosome, pos, reference,
genotype, consensus_quality,
snp_quality, mapping_quality,
coverage, read_bases,
base_qualities) | [
"def",
"vcf2pileup",
"(",
"vcf",
",",
"sample",
")",
":",
"chromosome",
"=",
"vcf",
".",
"contig",
"pos",
"=",
"vcf",
".",
"pos",
"reference",
"=",
"vcf",
".",
"ref",
"allelles",
"=",
"[",
"reference",
"]",
"+",
"vcf",
".",
"alt",
"data",
"=",
"vcf",
"[",
"sample",
"]",
"# get genotype",
"genotypes",
"=",
"data",
"[",
"\"GT\"",
"]",
"if",
"len",
"(",
"genotypes",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"only single genotype per position, %s\"",
"%",
"(",
"str",
"(",
"vcf",
")",
")",
")",
"genotypes",
"=",
"genotypes",
"[",
"0",
"]",
"# not a variant",
"if",
"genotypes",
"[",
"0",
"]",
"==",
"\".\"",
":",
"return",
"None",
"genotypes",
"=",
"[",
"allelles",
"[",
"int",
"(",
"x",
")",
"]",
"for",
"x",
"in",
"genotypes",
"if",
"x",
"!=",
"\"/\"",
"]",
"# snp_quality is \"genotype quality\"",
"snp_quality",
"=",
"consensus_quality",
"=",
"data",
".",
"get",
"(",
"\"GQ\"",
",",
"[",
"0",
"]",
")",
"[",
"0",
"]",
"mapping_quality",
"=",
"vcf",
".",
"info",
".",
"get",
"(",
"\"MQ\"",
",",
"[",
"0",
"]",
")",
"[",
"0",
"]",
"coverage",
"=",
"data",
".",
"get",
"(",
"\"DP\"",
",",
"0",
")",
"if",
"len",
"(",
"reference",
")",
">",
"1",
"or",
"max",
"(",
"[",
"len",
"(",
"x",
")",
"for",
"x",
"in",
"vcf",
".",
"alt",
"]",
")",
">",
"1",
":",
"# indel",
"genotype",
",",
"offset",
"=",
"translateIndelGenotypeFromVCF",
"(",
"genotypes",
",",
"reference",
")",
"return",
"PileupIndel",
"(",
"chromosome",
",",
"pos",
"+",
"offset",
",",
"\"*\"",
",",
"genotype",
",",
"consensus_quality",
",",
"snp_quality",
",",
"mapping_quality",
",",
"coverage",
",",
"genotype",
",",
"\"<\"",
"*",
"len",
"(",
"genotype",
")",
",",
"0",
",",
"0",
",",
"0",
")",
"else",
":",
"genotype",
"=",
"encodeGenotype",
"(",
"\"\"",
".",
"join",
"(",
"genotypes",
")",
")",
"read_bases",
"=",
"\"\"",
"base_qualities",
"=",
"\"\"",
"return",
"PileupSubstitution",
"(",
"chromosome",
",",
"pos",
",",
"reference",
",",
"genotype",
",",
"consensus_quality",
",",
"snp_quality",
",",
"mapping_quality",
",",
"coverage",
",",
"read_bases",
",",
"base_qualities",
")"
] | convert vcf record to pileup record. | [
"convert",
"vcf",
"record",
"to",
"pileup",
"record",
"."
] | 9961bebd4cd1f2bf5e42817df25699a6e6344b5a | https://github.com/pysam-developers/pysam/blob/9961bebd4cd1f2bf5e42817df25699a6e6344b5a/pysam/Pileup.py#L198-L253 |
232,305 | pysam-developers/pysam | pysam/Pileup.py | iterate_from_vcf | def iterate_from_vcf(infile, sample):
'''iterate over a vcf-formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type
:class:`pysam.Pileup.PileupSubstitution` or
:class:`pysam.Pileup.PileupIndel`.
Positions without a snp will be skipped.
This method is wasteful and written to support same legacy code
that expects samtools pileup output.
Better use the vcf parser directly.
'''
vcf = pysam.VCF()
vcf.connect(infile)
if sample not in vcf.getsamples():
raise KeyError("sample %s not vcf file")
for row in vcf.fetch():
result = vcf2pileup(row, sample)
if result:
yield result | python | def iterate_from_vcf(infile, sample):
'''iterate over a vcf-formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type
:class:`pysam.Pileup.PileupSubstitution` or
:class:`pysam.Pileup.PileupIndel`.
Positions without a snp will be skipped.
This method is wasteful and written to support same legacy code
that expects samtools pileup output.
Better use the vcf parser directly.
'''
vcf = pysam.VCF()
vcf.connect(infile)
if sample not in vcf.getsamples():
raise KeyError("sample %s not vcf file")
for row in vcf.fetch():
result = vcf2pileup(row, sample)
if result:
yield result | [
"def",
"iterate_from_vcf",
"(",
"infile",
",",
"sample",
")",
":",
"vcf",
"=",
"pysam",
".",
"VCF",
"(",
")",
"vcf",
".",
"connect",
"(",
"infile",
")",
"if",
"sample",
"not",
"in",
"vcf",
".",
"getsamples",
"(",
")",
":",
"raise",
"KeyError",
"(",
"\"sample %s not vcf file\"",
")",
"for",
"row",
"in",
"vcf",
".",
"fetch",
"(",
")",
":",
"result",
"=",
"vcf2pileup",
"(",
"row",
",",
"sample",
")",
"if",
"result",
":",
"yield",
"result"
] | iterate over a vcf-formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type
:class:`pysam.Pileup.PileupSubstitution` or
:class:`pysam.Pileup.PileupIndel`.
Positions without a snp will be skipped.
This method is wasteful and written to support same legacy code
that expects samtools pileup output.
Better use the vcf parser directly. | [
"iterate",
"over",
"a",
"vcf",
"-",
"formatted",
"file",
"."
] | 9961bebd4cd1f2bf5e42817df25699a6e6344b5a | https://github.com/pysam-developers/pysam/blob/9961bebd4cd1f2bf5e42817df25699a6e6344b5a/pysam/Pileup.py#L256-L282 |
232,306 | pysam-developers/pysam | devtools/import.py | _update_pysam_files | def _update_pysam_files(cf, destdir):
'''update pysam files applying redirection of ouput'''
basename = os.path.basename(destdir)
for filename in cf:
if not filename:
continue
dest = filename + ".pysam.c"
with open(filename, encoding="utf-8") as infile:
lines = "".join(infile.readlines())
with open(dest, "w", encoding="utf-8") as outfile:
outfile.write('#include "{}.pysam.h"\n\n'.format(basename))
subname, _ = os.path.splitext(os.path.basename(filename))
if subname in MAIN.get(basename, []):
lines = re.sub(r"int main\(", "int {}_main(".format(
basename), lines)
else:
lines = re.sub(r"int main\(", "int {}_{}_main(".format(
basename, subname), lines)
lines = re.sub("stderr", "{}_stderr".format(basename), lines)
lines = re.sub("stdout", "{}_stdout".format(basename), lines)
lines = re.sub(r" printf\(", " fprintf({}_stdout, ".format(basename), lines)
lines = re.sub(r"([^kf])puts\(", r"\1{}_puts(".format(basename), lines)
lines = re.sub(r"putchar\(([^)]+)\)",
r"fputc(\1, {}_stdout)".format(basename), lines)
fn = os.path.basename(filename)
# some specific fixes:
SPECIFIC_SUBSTITUTIONS = {
"bam_md.c": (
'sam_open_format("-", mode_w',
'sam_open_format({}_stdout_fn, mode_w'.format(basename)),
"phase.c": (
'putc("ACGT"[f->seq[j] == 1? (c&3, {}_stdout) : (c>>16&3)]);'.format(basename),
'putc("ACGT"[f->seq[j] == 1? (c&3) : (c>>16&3)], {}_stdout);'.format(basename)),
"cut_target.c": (
'putc(33 + (cns[j]>>8>>2, {}_stdout));'.format(basename),
'putc(33 + (cns[j]>>8>>2), {}_stdout);'.format(basename))
}
if fn in SPECIFIC_SUBSTITUTIONS:
lines = lines.replace(
SPECIFIC_SUBSTITUTIONS[fn][0],
SPECIFIC_SUBSTITUTIONS[fn][1])
outfile.write(lines)
with open(os.path.join("import", "pysam.h")) as inf, \
open(os.path.join(destdir, "{}.pysam.h".format(basename)), "w") as outf:
outf.write(re.sub("@pysam@", basename, inf.read()))
with open(os.path.join("import", "pysam.c")) as inf, \
open(os.path.join(destdir, "{}.pysam.c".format(basename)), "w") as outf:
outf.write(re.sub("@pysam@", basename, inf.read())) | python | def _update_pysam_files(cf, destdir):
'''update pysam files applying redirection of ouput'''
basename = os.path.basename(destdir)
for filename in cf:
if not filename:
continue
dest = filename + ".pysam.c"
with open(filename, encoding="utf-8") as infile:
lines = "".join(infile.readlines())
with open(dest, "w", encoding="utf-8") as outfile:
outfile.write('#include "{}.pysam.h"\n\n'.format(basename))
subname, _ = os.path.splitext(os.path.basename(filename))
if subname in MAIN.get(basename, []):
lines = re.sub(r"int main\(", "int {}_main(".format(
basename), lines)
else:
lines = re.sub(r"int main\(", "int {}_{}_main(".format(
basename, subname), lines)
lines = re.sub("stderr", "{}_stderr".format(basename), lines)
lines = re.sub("stdout", "{}_stdout".format(basename), lines)
lines = re.sub(r" printf\(", " fprintf({}_stdout, ".format(basename), lines)
lines = re.sub(r"([^kf])puts\(", r"\1{}_puts(".format(basename), lines)
lines = re.sub(r"putchar\(([^)]+)\)",
r"fputc(\1, {}_stdout)".format(basename), lines)
fn = os.path.basename(filename)
# some specific fixes:
SPECIFIC_SUBSTITUTIONS = {
"bam_md.c": (
'sam_open_format("-", mode_w',
'sam_open_format({}_stdout_fn, mode_w'.format(basename)),
"phase.c": (
'putc("ACGT"[f->seq[j] == 1? (c&3, {}_stdout) : (c>>16&3)]);'.format(basename),
'putc("ACGT"[f->seq[j] == 1? (c&3) : (c>>16&3)], {}_stdout);'.format(basename)),
"cut_target.c": (
'putc(33 + (cns[j]>>8>>2, {}_stdout));'.format(basename),
'putc(33 + (cns[j]>>8>>2), {}_stdout);'.format(basename))
}
if fn in SPECIFIC_SUBSTITUTIONS:
lines = lines.replace(
SPECIFIC_SUBSTITUTIONS[fn][0],
SPECIFIC_SUBSTITUTIONS[fn][1])
outfile.write(lines)
with open(os.path.join("import", "pysam.h")) as inf, \
open(os.path.join(destdir, "{}.pysam.h".format(basename)), "w") as outf:
outf.write(re.sub("@pysam@", basename, inf.read()))
with open(os.path.join("import", "pysam.c")) as inf, \
open(os.path.join(destdir, "{}.pysam.c".format(basename)), "w") as outf:
outf.write(re.sub("@pysam@", basename, inf.read())) | [
"def",
"_update_pysam_files",
"(",
"cf",
",",
"destdir",
")",
":",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"destdir",
")",
"for",
"filename",
"in",
"cf",
":",
"if",
"not",
"filename",
":",
"continue",
"dest",
"=",
"filename",
"+",
"\".pysam.c\"",
"with",
"open",
"(",
"filename",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"infile",
":",
"lines",
"=",
"\"\"",
".",
"join",
"(",
"infile",
".",
"readlines",
"(",
")",
")",
"with",
"open",
"(",
"dest",
",",
"\"w\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"outfile",
":",
"outfile",
".",
"write",
"(",
"'#include \"{}.pysam.h\"\\n\\n'",
".",
"format",
"(",
"basename",
")",
")",
"subname",
",",
"_",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
")",
"if",
"subname",
"in",
"MAIN",
".",
"get",
"(",
"basename",
",",
"[",
"]",
")",
":",
"lines",
"=",
"re",
".",
"sub",
"(",
"r\"int main\\(\"",
",",
"\"int {}_main(\"",
".",
"format",
"(",
"basename",
")",
",",
"lines",
")",
"else",
":",
"lines",
"=",
"re",
".",
"sub",
"(",
"r\"int main\\(\"",
",",
"\"int {}_{}_main(\"",
".",
"format",
"(",
"basename",
",",
"subname",
")",
",",
"lines",
")",
"lines",
"=",
"re",
".",
"sub",
"(",
"\"stderr\"",
",",
"\"{}_stderr\"",
".",
"format",
"(",
"basename",
")",
",",
"lines",
")",
"lines",
"=",
"re",
".",
"sub",
"(",
"\"stdout\"",
",",
"\"{}_stdout\"",
".",
"format",
"(",
"basename",
")",
",",
"lines",
")",
"lines",
"=",
"re",
".",
"sub",
"(",
"r\" printf\\(\"",
",",
"\" fprintf({}_stdout, \"",
".",
"format",
"(",
"basename",
")",
",",
"lines",
")",
"lines",
"=",
"re",
".",
"sub",
"(",
"r\"([^kf])puts\\(\"",
",",
"r\"\\1{}_puts(\"",
".",
"format",
"(",
"basename",
")",
",",
"lines",
")",
"lines",
"=",
"re",
".",
"sub",
"(",
"r\"putchar\\(([^)]+)\\)\"",
",",
"r\"fputc(\\1, {}_stdout)\"",
".",
"format",
"(",
"basename",
")",
",",
"lines",
")",
"fn",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"# some specific fixes:",
"SPECIFIC_SUBSTITUTIONS",
"=",
"{",
"\"bam_md.c\"",
":",
"(",
"'sam_open_format(\"-\", mode_w'",
",",
"'sam_open_format({}_stdout_fn, mode_w'",
".",
"format",
"(",
"basename",
")",
")",
",",
"\"phase.c\"",
":",
"(",
"'putc(\"ACGT\"[f->seq[j] == 1? (c&3, {}_stdout) : (c>>16&3)]);'",
".",
"format",
"(",
"basename",
")",
",",
"'putc(\"ACGT\"[f->seq[j] == 1? (c&3) : (c>>16&3)], {}_stdout);'",
".",
"format",
"(",
"basename",
")",
")",
",",
"\"cut_target.c\"",
":",
"(",
"'putc(33 + (cns[j]>>8>>2, {}_stdout));'",
".",
"format",
"(",
"basename",
")",
",",
"'putc(33 + (cns[j]>>8>>2), {}_stdout);'",
".",
"format",
"(",
"basename",
")",
")",
"}",
"if",
"fn",
"in",
"SPECIFIC_SUBSTITUTIONS",
":",
"lines",
"=",
"lines",
".",
"replace",
"(",
"SPECIFIC_SUBSTITUTIONS",
"[",
"fn",
"]",
"[",
"0",
"]",
",",
"SPECIFIC_SUBSTITUTIONS",
"[",
"fn",
"]",
"[",
"1",
"]",
")",
"outfile",
".",
"write",
"(",
"lines",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"\"import\"",
",",
"\"pysam.h\"",
")",
")",
"as",
"inf",
",",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"destdir",
",",
"\"{}.pysam.h\"",
".",
"format",
"(",
"basename",
")",
")",
",",
"\"w\"",
")",
"as",
"outf",
":",
"outf",
".",
"write",
"(",
"re",
".",
"sub",
"(",
"\"@pysam@\"",
",",
"basename",
",",
"inf",
".",
"read",
"(",
")",
")",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"\"import\"",
",",
"\"pysam.c\"",
")",
")",
"as",
"inf",
",",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"destdir",
",",
"\"{}.pysam.c\"",
".",
"format",
"(",
"basename",
")",
")",
",",
"\"w\"",
")",
"as",
"outf",
":",
"outf",
".",
"write",
"(",
"re",
".",
"sub",
"(",
"\"@pysam@\"",
",",
"basename",
",",
"inf",
".",
"read",
"(",
")",
")",
")"
] | update pysam files applying redirection of ouput | [
"update",
"pysam",
"files",
"applying",
"redirection",
"of",
"ouput"
] | 9961bebd4cd1f2bf5e42817df25699a6e6344b5a | https://github.com/pysam-developers/pysam/blob/9961bebd4cd1f2bf5e42817df25699a6e6344b5a/devtools/import.py#L83-L134 |
232,307 | pysam-developers/pysam | pysam/__init__.py | get_include | def get_include():
'''return a list of include directories.'''
dirname = os.path.abspath(os.path.join(os.path.dirname(__file__)))
#
# Header files may be stored in different relative locations
# depending on installation mode (e.g., `python setup.py install`,
# `python setup.py develop`. The first entry in each list is
# where develop-mode headers can be found.
#
htslib_possibilities = [os.path.join(dirname, '..', 'htslib'),
os.path.join(dirname, 'include', 'htslib')]
samtool_possibilities = [os.path.join(dirname, '..', 'samtools'),
os.path.join(dirname, 'include', 'samtools')]
includes = [dirname]
for header_locations in [htslib_possibilities, samtool_possibilities]:
for header_location in header_locations:
if os.path.exists(header_location):
includes.append(os.path.abspath(header_location))
break
return includes | python | def get_include():
'''return a list of include directories.'''
dirname = os.path.abspath(os.path.join(os.path.dirname(__file__)))
#
# Header files may be stored in different relative locations
# depending on installation mode (e.g., `python setup.py install`,
# `python setup.py develop`. The first entry in each list is
# where develop-mode headers can be found.
#
htslib_possibilities = [os.path.join(dirname, '..', 'htslib'),
os.path.join(dirname, 'include', 'htslib')]
samtool_possibilities = [os.path.join(dirname, '..', 'samtools'),
os.path.join(dirname, 'include', 'samtools')]
includes = [dirname]
for header_locations in [htslib_possibilities, samtool_possibilities]:
for header_location in header_locations:
if os.path.exists(header_location):
includes.append(os.path.abspath(header_location))
break
return includes | [
"def",
"get_include",
"(",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
")",
"#",
"# Header files may be stored in different relative locations",
"# depending on installation mode (e.g., `python setup.py install`,",
"# `python setup.py develop`. The first entry in each list is",
"# where develop-mode headers can be found.",
"#",
"htslib_possibilities",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"'..'",
",",
"'htslib'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"'include'",
",",
"'htslib'",
")",
"]",
"samtool_possibilities",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"'..'",
",",
"'samtools'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"'include'",
",",
"'samtools'",
")",
"]",
"includes",
"=",
"[",
"dirname",
"]",
"for",
"header_locations",
"in",
"[",
"htslib_possibilities",
",",
"samtool_possibilities",
"]",
":",
"for",
"header_location",
"in",
"header_locations",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"header_location",
")",
":",
"includes",
".",
"append",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"header_location",
")",
")",
"break",
"return",
"includes"
] | return a list of include directories. | [
"return",
"a",
"list",
"of",
"include",
"directories",
"."
] | 9961bebd4cd1f2bf5e42817df25699a6e6344b5a | https://github.com/pysam-developers/pysam/blob/9961bebd4cd1f2bf5e42817df25699a6e6344b5a/pysam/__init__.py#L53-L75 |
232,308 | pysam-developers/pysam | pysam/__init__.py | get_libraries | def get_libraries():
'''return a list of libraries to link against.'''
# Note that this list does not include libcsamtools.so as there are
# numerous name conflicts with libchtslib.so.
dirname = os.path.abspath(os.path.join(os.path.dirname(__file__)))
pysam_libs = ['libctabixproxies',
'libcfaidx',
'libcsamfile',
'libcvcf',
'libcbcf',
'libctabix']
if pysam.config.HTSLIB == "builtin":
pysam_libs.append('libchtslib')
so = sysconfig.get_config_var('SO')
return [os.path.join(dirname, x + so) for x in pysam_libs] | python | def get_libraries():
'''return a list of libraries to link against.'''
# Note that this list does not include libcsamtools.so as there are
# numerous name conflicts with libchtslib.so.
dirname = os.path.abspath(os.path.join(os.path.dirname(__file__)))
pysam_libs = ['libctabixproxies',
'libcfaidx',
'libcsamfile',
'libcvcf',
'libcbcf',
'libctabix']
if pysam.config.HTSLIB == "builtin":
pysam_libs.append('libchtslib')
so = sysconfig.get_config_var('SO')
return [os.path.join(dirname, x + so) for x in pysam_libs] | [
"def",
"get_libraries",
"(",
")",
":",
"# Note that this list does not include libcsamtools.so as there are",
"# numerous name conflicts with libchtslib.so.",
"dirname",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
")",
"pysam_libs",
"=",
"[",
"'libctabixproxies'",
",",
"'libcfaidx'",
",",
"'libcsamfile'",
",",
"'libcvcf'",
",",
"'libcbcf'",
",",
"'libctabix'",
"]",
"if",
"pysam",
".",
"config",
".",
"HTSLIB",
"==",
"\"builtin\"",
":",
"pysam_libs",
".",
"append",
"(",
"'libchtslib'",
")",
"so",
"=",
"sysconfig",
".",
"get_config_var",
"(",
"'SO'",
")",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"x",
"+",
"so",
")",
"for",
"x",
"in",
"pysam_libs",
"]"
] | return a list of libraries to link against. | [
"return",
"a",
"list",
"of",
"libraries",
"to",
"link",
"against",
"."
] | 9961bebd4cd1f2bf5e42817df25699a6e6344b5a | https://github.com/pysam-developers/pysam/blob/9961bebd4cd1f2bf5e42817df25699a6e6344b5a/pysam/__init__.py#L85-L100 |
232,309 | nerdvegas/rez | src/rez/vendor/pygraph/classes/digraph.py | digraph.has_edge | def has_edge(self, edge):
"""
Return whether an edge exists.
@type edge: tuple
@param edge: Edge.
@rtype: boolean
@return: Truth-value for edge existence.
"""
u, v = edge
return (u, v) in self.edge_properties | python | def has_edge(self, edge):
"""
Return whether an edge exists.
@type edge: tuple
@param edge: Edge.
@rtype: boolean
@return: Truth-value for edge existence.
"""
u, v = edge
return (u, v) in self.edge_properties | [
"def",
"has_edge",
"(",
"self",
",",
"edge",
")",
":",
"u",
",",
"v",
"=",
"edge",
"return",
"(",
"u",
",",
"v",
")",
"in",
"self",
".",
"edge_properties"
] | Return whether an edge exists.
@type edge: tuple
@param edge: Edge.
@rtype: boolean
@return: Truth-value for edge existence. | [
"Return",
"whether",
"an",
"edge",
"exists",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/classes/digraph.py#L214-L225 |
232,310 | nerdvegas/rez | src/rez/package_serialise.py | dump_package_data | def dump_package_data(data, buf, format_=FileFormat.py, skip_attributes=None):
"""Write package data to `buf`.
Args:
data (dict): Data source - must conform to `package_serialise_schema`.
buf (file-like object): Destination stream.
format_ (`FileFormat`): Format to dump data in.
skip_attributes (list of str): List of attributes to not print.
"""
if format_ == FileFormat.txt:
raise ValueError("'txt' format not supported for packages.")
data_ = dict((k, v) for k, v in data.iteritems() if v is not None)
data_ = package_serialise_schema.validate(data_)
skip = set(skip_attributes or [])
items = []
for key in package_key_order:
if key not in skip:
value = data_.pop(key, None)
if value is not None:
items.append((key, value))
# remaining are arbitrary keys
for key, value in data_.iteritems():
if key not in skip:
items.append((key, value))
dump_func = dump_functions[format_]
dump_func(items, buf) | python | def dump_package_data(data, buf, format_=FileFormat.py, skip_attributes=None):
"""Write package data to `buf`.
Args:
data (dict): Data source - must conform to `package_serialise_schema`.
buf (file-like object): Destination stream.
format_ (`FileFormat`): Format to dump data in.
skip_attributes (list of str): List of attributes to not print.
"""
if format_ == FileFormat.txt:
raise ValueError("'txt' format not supported for packages.")
data_ = dict((k, v) for k, v in data.iteritems() if v is not None)
data_ = package_serialise_schema.validate(data_)
skip = set(skip_attributes or [])
items = []
for key in package_key_order:
if key not in skip:
value = data_.pop(key, None)
if value is not None:
items.append((key, value))
# remaining are arbitrary keys
for key, value in data_.iteritems():
if key not in skip:
items.append((key, value))
dump_func = dump_functions[format_]
dump_func(items, buf) | [
"def",
"dump_package_data",
"(",
"data",
",",
"buf",
",",
"format_",
"=",
"FileFormat",
".",
"py",
",",
"skip_attributes",
"=",
"None",
")",
":",
"if",
"format_",
"==",
"FileFormat",
".",
"txt",
":",
"raise",
"ValueError",
"(",
"\"'txt' format not supported for packages.\"",
")",
"data_",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"data",
".",
"iteritems",
"(",
")",
"if",
"v",
"is",
"not",
"None",
")",
"data_",
"=",
"package_serialise_schema",
".",
"validate",
"(",
"data_",
")",
"skip",
"=",
"set",
"(",
"skip_attributes",
"or",
"[",
"]",
")",
"items",
"=",
"[",
"]",
"for",
"key",
"in",
"package_key_order",
":",
"if",
"key",
"not",
"in",
"skip",
":",
"value",
"=",
"data_",
".",
"pop",
"(",
"key",
",",
"None",
")",
"if",
"value",
"is",
"not",
"None",
":",
"items",
".",
"append",
"(",
"(",
"key",
",",
"value",
")",
")",
"# remaining are arbitrary keys",
"for",
"key",
",",
"value",
"in",
"data_",
".",
"iteritems",
"(",
")",
":",
"if",
"key",
"not",
"in",
"skip",
":",
"items",
".",
"append",
"(",
"(",
"key",
",",
"value",
")",
")",
"dump_func",
"=",
"dump_functions",
"[",
"format_",
"]",
"dump_func",
"(",
"items",
",",
"buf",
")"
] | Write package data to `buf`.
Args:
data (dict): Data source - must conform to `package_serialise_schema`.
buf (file-like object): Destination stream.
format_ (`FileFormat`): Format to dump data in.
skip_attributes (list of str): List of attributes to not print. | [
"Write",
"package",
"data",
"to",
"buf",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_serialise.py#L97-L126 |
232,311 | nerdvegas/rez | src/rez/vendor/distlib/_backport/sysconfig.py | get_config_vars | def get_config_vars(*args):
"""With no arguments, return a dictionary of all configuration
variables relevant for the current platform.
On Unix, this means every variable defined in Python's installed Makefile;
On Windows and Mac OS it's a much smaller set.
With arguments, return a list of values that result from looking up
each argument in the configuration variable dictionary.
"""
global _CONFIG_VARS
if _CONFIG_VARS is None:
_CONFIG_VARS = {}
# Normalized versions of prefix and exec_prefix are handy to have;
# in fact, these are the standard versions used most places in the
# distutils2 module.
_CONFIG_VARS['prefix'] = _PREFIX
_CONFIG_VARS['exec_prefix'] = _EXEC_PREFIX
_CONFIG_VARS['py_version'] = _PY_VERSION
_CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT
_CONFIG_VARS['py_version_nodot'] = _PY_VERSION[0] + _PY_VERSION[2]
_CONFIG_VARS['base'] = _PREFIX
_CONFIG_VARS['platbase'] = _EXEC_PREFIX
_CONFIG_VARS['projectbase'] = _PROJECT_BASE
try:
_CONFIG_VARS['abiflags'] = sys.abiflags
except AttributeError:
# sys.abiflags may not be defined on all platforms.
_CONFIG_VARS['abiflags'] = ''
if os.name in ('nt', 'os2'):
_init_non_posix(_CONFIG_VARS)
if os.name == 'posix':
_init_posix(_CONFIG_VARS)
# Setting 'userbase' is done below the call to the
# init function to enable using 'get_config_var' in
# the init-function.
if sys.version >= '2.6':
_CONFIG_VARS['userbase'] = _getuserbase()
if 'srcdir' not in _CONFIG_VARS:
_CONFIG_VARS['srcdir'] = _PROJECT_BASE
else:
_CONFIG_VARS['srcdir'] = _safe_realpath(_CONFIG_VARS['srcdir'])
# Convert srcdir into an absolute path if it appears necessary.
# Normally it is relative to the build directory. However, during
# testing, for example, we might be running a non-installed python
# from a different directory.
if _PYTHON_BUILD and os.name == "posix":
base = _PROJECT_BASE
try:
cwd = os.getcwd()
except OSError:
cwd = None
if (not os.path.isabs(_CONFIG_VARS['srcdir']) and
base != cwd):
# srcdir is relative and we are not in the same directory
# as the executable. Assume executable is in the build
# directory and make srcdir absolute.
srcdir = os.path.join(base, _CONFIG_VARS['srcdir'])
_CONFIG_VARS['srcdir'] = os.path.normpath(srcdir)
if sys.platform == 'darwin':
kernel_version = os.uname()[2] # Kernel version (8.4.3)
major_version = int(kernel_version.split('.')[0])
if major_version < 8:
# On Mac OS X before 10.4, check if -arch and -isysroot
# are in CFLAGS or LDFLAGS and remove them if they are.
# This is needed when building extensions on a 10.3 system
# using a universal build of python.
for key in ('LDFLAGS', 'BASECFLAGS',
# a number of derived variables. These need to be
# patched up as well.
'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
flags = _CONFIG_VARS[key]
flags = re.sub('-arch\s+\w+\s', ' ', flags)
flags = re.sub('-isysroot [^ \t]*', ' ', flags)
_CONFIG_VARS[key] = flags
else:
# Allow the user to override the architecture flags using
# an environment variable.
# NOTE: This name was introduced by Apple in OSX 10.5 and
# is used by several scripting languages distributed with
# that OS release.
if 'ARCHFLAGS' in os.environ:
arch = os.environ['ARCHFLAGS']
for key in ('LDFLAGS', 'BASECFLAGS',
# a number of derived variables. These need to be
# patched up as well.
'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
flags = _CONFIG_VARS[key]
flags = re.sub('-arch\s+\w+\s', ' ', flags)
flags = flags + ' ' + arch
_CONFIG_VARS[key] = flags
# If we're on OSX 10.5 or later and the user tries to
# compiles an extension using an SDK that is not present
# on the current machine it is better to not use an SDK
# than to fail.
#
# The major usecase for this is users using a Python.org
# binary installer on OSX 10.6: that installer uses
# the 10.4u SDK, but that SDK is not installed by default
# when you install Xcode.
#
CFLAGS = _CONFIG_VARS.get('CFLAGS', '')
m = re.search('-isysroot\s+(\S+)', CFLAGS)
if m is not None:
sdk = m.group(1)
if not os.path.exists(sdk):
for key in ('LDFLAGS', 'BASECFLAGS',
# a number of derived variables. These need to be
# patched up as well.
'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
flags = _CONFIG_VARS[key]
flags = re.sub('-isysroot\s+\S+(\s|$)', ' ', flags)
_CONFIG_VARS[key] = flags
if args:
vals = []
for name in args:
vals.append(_CONFIG_VARS.get(name))
return vals
else:
return _CONFIG_VARS | python | def get_config_vars(*args):
"""With no arguments, return a dictionary of all configuration
variables relevant for the current platform.
On Unix, this means every variable defined in Python's installed Makefile;
On Windows and Mac OS it's a much smaller set.
With arguments, return a list of values that result from looking up
each argument in the configuration variable dictionary.
"""
global _CONFIG_VARS
if _CONFIG_VARS is None:
_CONFIG_VARS = {}
# Normalized versions of prefix and exec_prefix are handy to have;
# in fact, these are the standard versions used most places in the
# distutils2 module.
_CONFIG_VARS['prefix'] = _PREFIX
_CONFIG_VARS['exec_prefix'] = _EXEC_PREFIX
_CONFIG_VARS['py_version'] = _PY_VERSION
_CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT
_CONFIG_VARS['py_version_nodot'] = _PY_VERSION[0] + _PY_VERSION[2]
_CONFIG_VARS['base'] = _PREFIX
_CONFIG_VARS['platbase'] = _EXEC_PREFIX
_CONFIG_VARS['projectbase'] = _PROJECT_BASE
try:
_CONFIG_VARS['abiflags'] = sys.abiflags
except AttributeError:
# sys.abiflags may not be defined on all platforms.
_CONFIG_VARS['abiflags'] = ''
if os.name in ('nt', 'os2'):
_init_non_posix(_CONFIG_VARS)
if os.name == 'posix':
_init_posix(_CONFIG_VARS)
# Setting 'userbase' is done below the call to the
# init function to enable using 'get_config_var' in
# the init-function.
if sys.version >= '2.6':
_CONFIG_VARS['userbase'] = _getuserbase()
if 'srcdir' not in _CONFIG_VARS:
_CONFIG_VARS['srcdir'] = _PROJECT_BASE
else:
_CONFIG_VARS['srcdir'] = _safe_realpath(_CONFIG_VARS['srcdir'])
# Convert srcdir into an absolute path if it appears necessary.
# Normally it is relative to the build directory. However, during
# testing, for example, we might be running a non-installed python
# from a different directory.
if _PYTHON_BUILD and os.name == "posix":
base = _PROJECT_BASE
try:
cwd = os.getcwd()
except OSError:
cwd = None
if (not os.path.isabs(_CONFIG_VARS['srcdir']) and
base != cwd):
# srcdir is relative and we are not in the same directory
# as the executable. Assume executable is in the build
# directory and make srcdir absolute.
srcdir = os.path.join(base, _CONFIG_VARS['srcdir'])
_CONFIG_VARS['srcdir'] = os.path.normpath(srcdir)
if sys.platform == 'darwin':
kernel_version = os.uname()[2] # Kernel version (8.4.3)
major_version = int(kernel_version.split('.')[0])
if major_version < 8:
# On Mac OS X before 10.4, check if -arch and -isysroot
# are in CFLAGS or LDFLAGS and remove them if they are.
# This is needed when building extensions on a 10.3 system
# using a universal build of python.
for key in ('LDFLAGS', 'BASECFLAGS',
# a number of derived variables. These need to be
# patched up as well.
'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
flags = _CONFIG_VARS[key]
flags = re.sub('-arch\s+\w+\s', ' ', flags)
flags = re.sub('-isysroot [^ \t]*', ' ', flags)
_CONFIG_VARS[key] = flags
else:
# Allow the user to override the architecture flags using
# an environment variable.
# NOTE: This name was introduced by Apple in OSX 10.5 and
# is used by several scripting languages distributed with
# that OS release.
if 'ARCHFLAGS' in os.environ:
arch = os.environ['ARCHFLAGS']
for key in ('LDFLAGS', 'BASECFLAGS',
# a number of derived variables. These need to be
# patched up as well.
'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
flags = _CONFIG_VARS[key]
flags = re.sub('-arch\s+\w+\s', ' ', flags)
flags = flags + ' ' + arch
_CONFIG_VARS[key] = flags
# If we're on OSX 10.5 or later and the user tries to
# compiles an extension using an SDK that is not present
# on the current machine it is better to not use an SDK
# than to fail.
#
# The major usecase for this is users using a Python.org
# binary installer on OSX 10.6: that installer uses
# the 10.4u SDK, but that SDK is not installed by default
# when you install Xcode.
#
CFLAGS = _CONFIG_VARS.get('CFLAGS', '')
m = re.search('-isysroot\s+(\S+)', CFLAGS)
if m is not None:
sdk = m.group(1)
if not os.path.exists(sdk):
for key in ('LDFLAGS', 'BASECFLAGS',
# a number of derived variables. These need to be
# patched up as well.
'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
flags = _CONFIG_VARS[key]
flags = re.sub('-isysroot\s+\S+(\s|$)', ' ', flags)
_CONFIG_VARS[key] = flags
if args:
vals = []
for name in args:
vals.append(_CONFIG_VARS.get(name))
return vals
else:
return _CONFIG_VARS | [
"def",
"get_config_vars",
"(",
"*",
"args",
")",
":",
"global",
"_CONFIG_VARS",
"if",
"_CONFIG_VARS",
"is",
"None",
":",
"_CONFIG_VARS",
"=",
"{",
"}",
"# Normalized versions of prefix and exec_prefix are handy to have;",
"# in fact, these are the standard versions used most places in the",
"# distutils2 module.",
"_CONFIG_VARS",
"[",
"'prefix'",
"]",
"=",
"_PREFIX",
"_CONFIG_VARS",
"[",
"'exec_prefix'",
"]",
"=",
"_EXEC_PREFIX",
"_CONFIG_VARS",
"[",
"'py_version'",
"]",
"=",
"_PY_VERSION",
"_CONFIG_VARS",
"[",
"'py_version_short'",
"]",
"=",
"_PY_VERSION_SHORT",
"_CONFIG_VARS",
"[",
"'py_version_nodot'",
"]",
"=",
"_PY_VERSION",
"[",
"0",
"]",
"+",
"_PY_VERSION",
"[",
"2",
"]",
"_CONFIG_VARS",
"[",
"'base'",
"]",
"=",
"_PREFIX",
"_CONFIG_VARS",
"[",
"'platbase'",
"]",
"=",
"_EXEC_PREFIX",
"_CONFIG_VARS",
"[",
"'projectbase'",
"]",
"=",
"_PROJECT_BASE",
"try",
":",
"_CONFIG_VARS",
"[",
"'abiflags'",
"]",
"=",
"sys",
".",
"abiflags",
"except",
"AttributeError",
":",
"# sys.abiflags may not be defined on all platforms.",
"_CONFIG_VARS",
"[",
"'abiflags'",
"]",
"=",
"''",
"if",
"os",
".",
"name",
"in",
"(",
"'nt'",
",",
"'os2'",
")",
":",
"_init_non_posix",
"(",
"_CONFIG_VARS",
")",
"if",
"os",
".",
"name",
"==",
"'posix'",
":",
"_init_posix",
"(",
"_CONFIG_VARS",
")",
"# Setting 'userbase' is done below the call to the",
"# init function to enable using 'get_config_var' in",
"# the init-function.",
"if",
"sys",
".",
"version",
">=",
"'2.6'",
":",
"_CONFIG_VARS",
"[",
"'userbase'",
"]",
"=",
"_getuserbase",
"(",
")",
"if",
"'srcdir'",
"not",
"in",
"_CONFIG_VARS",
":",
"_CONFIG_VARS",
"[",
"'srcdir'",
"]",
"=",
"_PROJECT_BASE",
"else",
":",
"_CONFIG_VARS",
"[",
"'srcdir'",
"]",
"=",
"_safe_realpath",
"(",
"_CONFIG_VARS",
"[",
"'srcdir'",
"]",
")",
"# Convert srcdir into an absolute path if it appears necessary.",
"# Normally it is relative to the build directory. However, during",
"# testing, for example, we might be running a non-installed python",
"# from a different directory.",
"if",
"_PYTHON_BUILD",
"and",
"os",
".",
"name",
"==",
"\"posix\"",
":",
"base",
"=",
"_PROJECT_BASE",
"try",
":",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"except",
"OSError",
":",
"cwd",
"=",
"None",
"if",
"(",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"_CONFIG_VARS",
"[",
"'srcdir'",
"]",
")",
"and",
"base",
"!=",
"cwd",
")",
":",
"# srcdir is relative and we are not in the same directory",
"# as the executable. Assume executable is in the build",
"# directory and make srcdir absolute.",
"srcdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"_CONFIG_VARS",
"[",
"'srcdir'",
"]",
")",
"_CONFIG_VARS",
"[",
"'srcdir'",
"]",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"srcdir",
")",
"if",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"kernel_version",
"=",
"os",
".",
"uname",
"(",
")",
"[",
"2",
"]",
"# Kernel version (8.4.3)",
"major_version",
"=",
"int",
"(",
"kernel_version",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
"if",
"major_version",
"<",
"8",
":",
"# On Mac OS X before 10.4, check if -arch and -isysroot",
"# are in CFLAGS or LDFLAGS and remove them if they are.",
"# This is needed when building extensions on a 10.3 system",
"# using a universal build of python.",
"for",
"key",
"in",
"(",
"'LDFLAGS'",
",",
"'BASECFLAGS'",
",",
"# a number of derived variables. These need to be",
"# patched up as well.",
"'CFLAGS'",
",",
"'PY_CFLAGS'",
",",
"'BLDSHARED'",
")",
":",
"flags",
"=",
"_CONFIG_VARS",
"[",
"key",
"]",
"flags",
"=",
"re",
".",
"sub",
"(",
"'-arch\\s+\\w+\\s'",
",",
"' '",
",",
"flags",
")",
"flags",
"=",
"re",
".",
"sub",
"(",
"'-isysroot [^ \\t]*'",
",",
"' '",
",",
"flags",
")",
"_CONFIG_VARS",
"[",
"key",
"]",
"=",
"flags",
"else",
":",
"# Allow the user to override the architecture flags using",
"# an environment variable.",
"# NOTE: This name was introduced by Apple in OSX 10.5 and",
"# is used by several scripting languages distributed with",
"# that OS release.",
"if",
"'ARCHFLAGS'",
"in",
"os",
".",
"environ",
":",
"arch",
"=",
"os",
".",
"environ",
"[",
"'ARCHFLAGS'",
"]",
"for",
"key",
"in",
"(",
"'LDFLAGS'",
",",
"'BASECFLAGS'",
",",
"# a number of derived variables. These need to be",
"# patched up as well.",
"'CFLAGS'",
",",
"'PY_CFLAGS'",
",",
"'BLDSHARED'",
")",
":",
"flags",
"=",
"_CONFIG_VARS",
"[",
"key",
"]",
"flags",
"=",
"re",
".",
"sub",
"(",
"'-arch\\s+\\w+\\s'",
",",
"' '",
",",
"flags",
")",
"flags",
"=",
"flags",
"+",
"' '",
"+",
"arch",
"_CONFIG_VARS",
"[",
"key",
"]",
"=",
"flags",
"# If we're on OSX 10.5 or later and the user tries to",
"# compiles an extension using an SDK that is not present",
"# on the current machine it is better to not use an SDK",
"# than to fail.",
"#",
"# The major usecase for this is users using a Python.org",
"# binary installer on OSX 10.6: that installer uses",
"# the 10.4u SDK, but that SDK is not installed by default",
"# when you install Xcode.",
"#",
"CFLAGS",
"=",
"_CONFIG_VARS",
".",
"get",
"(",
"'CFLAGS'",
",",
"''",
")",
"m",
"=",
"re",
".",
"search",
"(",
"'-isysroot\\s+(\\S+)'",
",",
"CFLAGS",
")",
"if",
"m",
"is",
"not",
"None",
":",
"sdk",
"=",
"m",
".",
"group",
"(",
"1",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"sdk",
")",
":",
"for",
"key",
"in",
"(",
"'LDFLAGS'",
",",
"'BASECFLAGS'",
",",
"# a number of derived variables. These need to be",
"# patched up as well.",
"'CFLAGS'",
",",
"'PY_CFLAGS'",
",",
"'BLDSHARED'",
")",
":",
"flags",
"=",
"_CONFIG_VARS",
"[",
"key",
"]",
"flags",
"=",
"re",
".",
"sub",
"(",
"'-isysroot\\s+\\S+(\\s|$)'",
",",
"' '",
",",
"flags",
")",
"_CONFIG_VARS",
"[",
"key",
"]",
"=",
"flags",
"if",
"args",
":",
"vals",
"=",
"[",
"]",
"for",
"name",
"in",
"args",
":",
"vals",
".",
"append",
"(",
"_CONFIG_VARS",
".",
"get",
"(",
"name",
")",
")",
"return",
"vals",
"else",
":",
"return",
"_CONFIG_VARS"
] | With no arguments, return a dictionary of all configuration
variables relevant for the current platform.
On Unix, this means every variable defined in Python's installed Makefile;
On Windows and Mac OS it's a much smaller set.
With arguments, return a list of values that result from looking up
each argument in the configuration variable dictionary. | [
"With",
"no",
"arguments",
"return",
"a",
"dictionary",
"of",
"all",
"configuration",
"variables",
"relevant",
"for",
"the",
"current",
"platform",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/distlib/_backport/sysconfig.py#L463-L591 |
232,312 | nerdvegas/rez | src/support/package_utils/set_authors.py | set_authors | def set_authors(data):
"""Add 'authors' attribute based on repo contributions
"""
if "authors" in data:
return
shfile = os.path.join(os.path.dirname(__file__), "get_committers.sh")
p = subprocess.Popen(["bash", shfile], stdout=subprocess.PIPE)
out, _ = p.communicate()
if p.returncode:
return
authors = out.strip().split('\n')
authors = [x.strip() for x in authors]
data["authors"] = authors | python | def set_authors(data):
"""Add 'authors' attribute based on repo contributions
"""
if "authors" in data:
return
shfile = os.path.join(os.path.dirname(__file__), "get_committers.sh")
p = subprocess.Popen(["bash", shfile], stdout=subprocess.PIPE)
out, _ = p.communicate()
if p.returncode:
return
authors = out.strip().split('\n')
authors = [x.strip() for x in authors]
data["authors"] = authors | [
"def",
"set_authors",
"(",
"data",
")",
":",
"if",
"\"authors\"",
"in",
"data",
":",
"return",
"shfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"get_committers.sh\"",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"\"bash\"",
",",
"shfile",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"out",
",",
"_",
"=",
"p",
".",
"communicate",
"(",
")",
"if",
"p",
".",
"returncode",
":",
"return",
"authors",
"=",
"out",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"authors",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"authors",
"]",
"data",
"[",
"\"authors\"",
"]",
"=",
"authors"
] | Add 'authors' attribute based on repo contributions | [
"Add",
"authors",
"attribute",
"based",
"on",
"repo",
"contributions"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/support/package_utils/set_authors.py#L5-L21 |
232,313 | nerdvegas/rez | src/rez/package_maker__.py | make_package | def make_package(name, path, make_base=None, make_root=None, skip_existing=True,
warn_on_skip=True):
"""Make and install a package.
Example:
>>> def make_root(variant, path):
>>> os.symlink("/foo_payload/misc/python27", "ext")
>>>
>>> with make_package('foo', '/packages', make_root=make_root) as pkg:
>>> pkg.version = '1.0.0'
>>> pkg.description = 'does foo things'
>>> pkg.requires = ['python-2.7']
Args:
name (str): Package name.
path (str): Package repository path to install package into.
make_base (callable): Function that is used to create the package
payload, if applicable.
make_root (callable): Function that is used to create the package
variant payloads, if applicable.
skip_existing (bool): If True, detect if a variant already exists, and
skip with a warning message if so.
warn_on_skip (bool): If True, print warning when a variant is skipped.
Yields:
`PackageMaker` object.
Note:
Both `make_base` and `make_root` are called once per variant install,
and have the signature (variant, path).
Note:
The 'installed_variants' attribute on the `PackageMaker` instance will
be appended with variant(s) created by this function, if any.
"""
maker = PackageMaker(name)
yield maker
# post-with-block:
#
package = maker.get_package()
cwd = os.getcwd()
src_variants = []
# skip those variants that already exist
if skip_existing:
for variant in package.iter_variants():
variant_ = variant.install(path, dry_run=True)
if variant_ is None:
src_variants.append(variant)
else:
maker.skipped_variants.append(variant_)
if warn_on_skip:
print_warning("Skipping installation: Package variant already "
"exists: %s" % variant_.uri)
else:
src_variants = package.iter_variants()
with retain_cwd():
# install the package variant(s) into the filesystem package repo at `path`
for variant in src_variants:
variant_ = variant.install(path)
base = variant_.base
if make_base and base:
if not os.path.exists(base):
os.makedirs(base)
os.chdir(base)
make_base(variant_, base)
root = variant_.root
if make_root and root:
if not os.path.exists(root):
os.makedirs(root)
os.chdir(root)
make_root(variant_, root)
maker.installed_variants.append(variant_) | python | def make_package(name, path, make_base=None, make_root=None, skip_existing=True,
warn_on_skip=True):
"""Make and install a package.
Example:
>>> def make_root(variant, path):
>>> os.symlink("/foo_payload/misc/python27", "ext")
>>>
>>> with make_package('foo', '/packages', make_root=make_root) as pkg:
>>> pkg.version = '1.0.0'
>>> pkg.description = 'does foo things'
>>> pkg.requires = ['python-2.7']
Args:
name (str): Package name.
path (str): Package repository path to install package into.
make_base (callable): Function that is used to create the package
payload, if applicable.
make_root (callable): Function that is used to create the package
variant payloads, if applicable.
skip_existing (bool): If True, detect if a variant already exists, and
skip with a warning message if so.
warn_on_skip (bool): If True, print warning when a variant is skipped.
Yields:
`PackageMaker` object.
Note:
Both `make_base` and `make_root` are called once per variant install,
and have the signature (variant, path).
Note:
The 'installed_variants' attribute on the `PackageMaker` instance will
be appended with variant(s) created by this function, if any.
"""
maker = PackageMaker(name)
yield maker
# post-with-block:
#
package = maker.get_package()
cwd = os.getcwd()
src_variants = []
# skip those variants that already exist
if skip_existing:
for variant in package.iter_variants():
variant_ = variant.install(path, dry_run=True)
if variant_ is None:
src_variants.append(variant)
else:
maker.skipped_variants.append(variant_)
if warn_on_skip:
print_warning("Skipping installation: Package variant already "
"exists: %s" % variant_.uri)
else:
src_variants = package.iter_variants()
with retain_cwd():
# install the package variant(s) into the filesystem package repo at `path`
for variant in src_variants:
variant_ = variant.install(path)
base = variant_.base
if make_base and base:
if not os.path.exists(base):
os.makedirs(base)
os.chdir(base)
make_base(variant_, base)
root = variant_.root
if make_root and root:
if not os.path.exists(root):
os.makedirs(root)
os.chdir(root)
make_root(variant_, root)
maker.installed_variants.append(variant_) | [
"def",
"make_package",
"(",
"name",
",",
"path",
",",
"make_base",
"=",
"None",
",",
"make_root",
"=",
"None",
",",
"skip_existing",
"=",
"True",
",",
"warn_on_skip",
"=",
"True",
")",
":",
"maker",
"=",
"PackageMaker",
"(",
"name",
")",
"yield",
"maker",
"# post-with-block:",
"#",
"package",
"=",
"maker",
".",
"get_package",
"(",
")",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"src_variants",
"=",
"[",
"]",
"# skip those variants that already exist",
"if",
"skip_existing",
":",
"for",
"variant",
"in",
"package",
".",
"iter_variants",
"(",
")",
":",
"variant_",
"=",
"variant",
".",
"install",
"(",
"path",
",",
"dry_run",
"=",
"True",
")",
"if",
"variant_",
"is",
"None",
":",
"src_variants",
".",
"append",
"(",
"variant",
")",
"else",
":",
"maker",
".",
"skipped_variants",
".",
"append",
"(",
"variant_",
")",
"if",
"warn_on_skip",
":",
"print_warning",
"(",
"\"Skipping installation: Package variant already \"",
"\"exists: %s\"",
"%",
"variant_",
".",
"uri",
")",
"else",
":",
"src_variants",
"=",
"package",
".",
"iter_variants",
"(",
")",
"with",
"retain_cwd",
"(",
")",
":",
"# install the package variant(s) into the filesystem package repo at `path`",
"for",
"variant",
"in",
"src_variants",
":",
"variant_",
"=",
"variant",
".",
"install",
"(",
"path",
")",
"base",
"=",
"variant_",
".",
"base",
"if",
"make_base",
"and",
"base",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"base",
")",
":",
"os",
".",
"makedirs",
"(",
"base",
")",
"os",
".",
"chdir",
"(",
"base",
")",
"make_base",
"(",
"variant_",
",",
"base",
")",
"root",
"=",
"variant_",
".",
"root",
"if",
"make_root",
"and",
"root",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"root",
")",
":",
"os",
".",
"makedirs",
"(",
"root",
")",
"os",
".",
"chdir",
"(",
"root",
")",
"make_root",
"(",
"variant_",
",",
"root",
")",
"maker",
".",
"installed_variants",
".",
"append",
"(",
"variant_",
")"
] | Make and install a package.
Example:
>>> def make_root(variant, path):
>>> os.symlink("/foo_payload/misc/python27", "ext")
>>>
>>> with make_package('foo', '/packages', make_root=make_root) as pkg:
>>> pkg.version = '1.0.0'
>>> pkg.description = 'does foo things'
>>> pkg.requires = ['python-2.7']
Args:
name (str): Package name.
path (str): Package repository path to install package into.
make_base (callable): Function that is used to create the package
payload, if applicable.
make_root (callable): Function that is used to create the package
variant payloads, if applicable.
skip_existing (bool): If True, detect if a variant already exists, and
skip with a warning message if so.
warn_on_skip (bool): If True, print warning when a variant is skipped.
Yields:
`PackageMaker` object.
Note:
Both `make_base` and `make_root` are called once per variant install,
and have the signature (variant, path).
Note:
The 'installed_variants' attribute on the `PackageMaker` instance will
be appended with variant(s) created by this function, if any. | [
"Make",
"and",
"install",
"a",
"package",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_maker__.py#L140-L219 |
232,314 | nerdvegas/rez | src/rez/package_maker__.py | PackageMaker.get_package | def get_package(self):
"""Create the analogous package.
Returns:
`Package` object.
"""
# get and validate package data
package_data = self._get_data()
package_data = package_schema.validate(package_data)
# check compatibility with rez version
if "requires_rez_version" in package_data:
ver = package_data.pop("requires_rez_version")
if _rez_Version < ver:
raise PackageMetadataError(
"Failed reading package definition file: rez version >= %s "
"needed (current version is %s)" % (ver, _rez_Version))
# create a 'memory' package repository containing just this package
version_str = package_data.get("version") or "_NO_VERSION"
repo_data = {self.name: {version_str: package_data}}
repo = create_memory_package_repository(repo_data)
# retrieve the package from the new repository
family_resource = repo.get_package_family(self.name)
it = repo.iter_packages(family_resource)
package_resource = it.next()
package = self.package_cls(package_resource)
# revalidate the package for extra measure
package.validate_data()
return package | python | def get_package(self):
"""Create the analogous package.
Returns:
`Package` object.
"""
# get and validate package data
package_data = self._get_data()
package_data = package_schema.validate(package_data)
# check compatibility with rez version
if "requires_rez_version" in package_data:
ver = package_data.pop("requires_rez_version")
if _rez_Version < ver:
raise PackageMetadataError(
"Failed reading package definition file: rez version >= %s "
"needed (current version is %s)" % (ver, _rez_Version))
# create a 'memory' package repository containing just this package
version_str = package_data.get("version") or "_NO_VERSION"
repo_data = {self.name: {version_str: package_data}}
repo = create_memory_package_repository(repo_data)
# retrieve the package from the new repository
family_resource = repo.get_package_family(self.name)
it = repo.iter_packages(family_resource)
package_resource = it.next()
package = self.package_cls(package_resource)
# revalidate the package for extra measure
package.validate_data()
return package | [
"def",
"get_package",
"(",
"self",
")",
":",
"# get and validate package data",
"package_data",
"=",
"self",
".",
"_get_data",
"(",
")",
"package_data",
"=",
"package_schema",
".",
"validate",
"(",
"package_data",
")",
"# check compatibility with rez version",
"if",
"\"requires_rez_version\"",
"in",
"package_data",
":",
"ver",
"=",
"package_data",
".",
"pop",
"(",
"\"requires_rez_version\"",
")",
"if",
"_rez_Version",
"<",
"ver",
":",
"raise",
"PackageMetadataError",
"(",
"\"Failed reading package definition file: rez version >= %s \"",
"\"needed (current version is %s)\"",
"%",
"(",
"ver",
",",
"_rez_Version",
")",
")",
"# create a 'memory' package repository containing just this package",
"version_str",
"=",
"package_data",
".",
"get",
"(",
"\"version\"",
")",
"or",
"\"_NO_VERSION\"",
"repo_data",
"=",
"{",
"self",
".",
"name",
":",
"{",
"version_str",
":",
"package_data",
"}",
"}",
"repo",
"=",
"create_memory_package_repository",
"(",
"repo_data",
")",
"# retrieve the package from the new repository",
"family_resource",
"=",
"repo",
".",
"get_package_family",
"(",
"self",
".",
"name",
")",
"it",
"=",
"repo",
".",
"iter_packages",
"(",
"family_resource",
")",
"package_resource",
"=",
"it",
".",
"next",
"(",
")",
"package",
"=",
"self",
".",
"package_cls",
"(",
"package_resource",
")",
"# revalidate the package for extra measure",
"package",
".",
"validate_data",
"(",
")",
"return",
"package"
] | Create the analogous package.
Returns:
`Package` object. | [
"Create",
"the",
"analogous",
"package",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_maker__.py#L93-L126 |
232,315 | nerdvegas/rez | src/rez/vendor/pyparsing/pyparsing.py | getTokensEndLoc | def getTokensEndLoc():
"""Method to be called from within a parse action to determine the end
location of the parsed tokens."""
import inspect
fstack = inspect.stack()
try:
# search up the stack (through intervening argument normalizers) for correct calling routine
for f in fstack[2:]:
if f[3] == "_parseNoCache":
endloc = f[0].f_locals["loc"]
return endloc
else:
raise ParseFatalException("incorrect usage of getTokensEndLoc - may only be called from within a parse action")
finally:
del fstack | python | def getTokensEndLoc():
"""Method to be called from within a parse action to determine the end
location of the parsed tokens."""
import inspect
fstack = inspect.stack()
try:
# search up the stack (through intervening argument normalizers) for correct calling routine
for f in fstack[2:]:
if f[3] == "_parseNoCache":
endloc = f[0].f_locals["loc"]
return endloc
else:
raise ParseFatalException("incorrect usage of getTokensEndLoc - may only be called from within a parse action")
finally:
del fstack | [
"def",
"getTokensEndLoc",
"(",
")",
":",
"import",
"inspect",
"fstack",
"=",
"inspect",
".",
"stack",
"(",
")",
"try",
":",
"# search up the stack (through intervening argument normalizers) for correct calling routine\r",
"for",
"f",
"in",
"fstack",
"[",
"2",
":",
"]",
":",
"if",
"f",
"[",
"3",
"]",
"==",
"\"_parseNoCache\"",
":",
"endloc",
"=",
"f",
"[",
"0",
"]",
".",
"f_locals",
"[",
"\"loc\"",
"]",
"return",
"endloc",
"else",
":",
"raise",
"ParseFatalException",
"(",
"\"incorrect usage of getTokensEndLoc - may only be called from within a parse action\"",
")",
"finally",
":",
"del",
"fstack"
] | Method to be called from within a parse action to determine the end
location of the parsed tokens. | [
"Method",
"to",
"be",
"called",
"from",
"within",
"a",
"parse",
"action",
"to",
"determine",
"the",
"end",
"location",
"of",
"the",
"parsed",
"tokens",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pyparsing/pyparsing.py#L3350-L3364 |
232,316 | nerdvegas/rez | src/rez/utils/schema.py | schema_keys | def schema_keys(schema):
"""Get the string values of keys in a dict-based schema.
Non-string keys are ignored.
Returns:
Set of string keys of a schema which is in the form (eg):
schema = Schema({Required("foo"): int,
Optional("bah"): basestring})
"""
def _get_leaf(value):
if isinstance(value, Schema):
return _get_leaf(value._schema)
return value
keys = set()
dict_ = schema._schema
assert isinstance(dict_, dict)
for key in dict_.iterkeys():
key_ = _get_leaf(key)
if isinstance(key_, basestring):
keys.add(key_)
return keys | python | def schema_keys(schema):
"""Get the string values of keys in a dict-based schema.
Non-string keys are ignored.
Returns:
Set of string keys of a schema which is in the form (eg):
schema = Schema({Required("foo"): int,
Optional("bah"): basestring})
"""
def _get_leaf(value):
if isinstance(value, Schema):
return _get_leaf(value._schema)
return value
keys = set()
dict_ = schema._schema
assert isinstance(dict_, dict)
for key in dict_.iterkeys():
key_ = _get_leaf(key)
if isinstance(key_, basestring):
keys.add(key_)
return keys | [
"def",
"schema_keys",
"(",
"schema",
")",
":",
"def",
"_get_leaf",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Schema",
")",
":",
"return",
"_get_leaf",
"(",
"value",
".",
"_schema",
")",
"return",
"value",
"keys",
"=",
"set",
"(",
")",
"dict_",
"=",
"schema",
".",
"_schema",
"assert",
"isinstance",
"(",
"dict_",
",",
"dict",
")",
"for",
"key",
"in",
"dict_",
".",
"iterkeys",
"(",
")",
":",
"key_",
"=",
"_get_leaf",
"(",
"key",
")",
"if",
"isinstance",
"(",
"key_",
",",
"basestring",
")",
":",
"keys",
".",
"add",
"(",
"key_",
")",
"return",
"keys"
] | Get the string values of keys in a dict-based schema.
Non-string keys are ignored.
Returns:
Set of string keys of a schema which is in the form (eg):
schema = Schema({Required("foo"): int,
Optional("bah"): basestring}) | [
"Get",
"the",
"string",
"values",
"of",
"keys",
"in",
"a",
"dict",
"-",
"based",
"schema",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/schema.py#L12-L37 |
232,317 | nerdvegas/rez | src/rez/utils/schema.py | dict_to_schema | def dict_to_schema(schema_dict, required, allow_custom_keys=True, modifier=None):
"""Convert a dict of Schemas into a Schema.
Args:
required (bool): Whether to make schema keys optional or required.
allow_custom_keys (bool, optional): If True, creates a schema that
allows custom items in dicts.
modifier (callable): Functor to apply to dict values - it is applied
via `Schema.Use`.
Returns:
A `Schema` object.
"""
if modifier:
modifier = Use(modifier)
def _to(value):
if isinstance(value, dict):
d = {}
for k, v in value.iteritems():
if isinstance(k, basestring):
k = Required(k) if required else Optional(k)
d[k] = _to(v)
if allow_custom_keys:
d[Optional(basestring)] = modifier or object
schema = Schema(d)
elif modifier:
schema = And(value, modifier)
else:
schema = value
return schema
return _to(schema_dict) | python | def dict_to_schema(schema_dict, required, allow_custom_keys=True, modifier=None):
"""Convert a dict of Schemas into a Schema.
Args:
required (bool): Whether to make schema keys optional or required.
allow_custom_keys (bool, optional): If True, creates a schema that
allows custom items in dicts.
modifier (callable): Functor to apply to dict values - it is applied
via `Schema.Use`.
Returns:
A `Schema` object.
"""
if modifier:
modifier = Use(modifier)
def _to(value):
if isinstance(value, dict):
d = {}
for k, v in value.iteritems():
if isinstance(k, basestring):
k = Required(k) if required else Optional(k)
d[k] = _to(v)
if allow_custom_keys:
d[Optional(basestring)] = modifier or object
schema = Schema(d)
elif modifier:
schema = And(value, modifier)
else:
schema = value
return schema
return _to(schema_dict) | [
"def",
"dict_to_schema",
"(",
"schema_dict",
",",
"required",
",",
"allow_custom_keys",
"=",
"True",
",",
"modifier",
"=",
"None",
")",
":",
"if",
"modifier",
":",
"modifier",
"=",
"Use",
"(",
"modifier",
")",
"def",
"_to",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"d",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"value",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"k",
",",
"basestring",
")",
":",
"k",
"=",
"Required",
"(",
"k",
")",
"if",
"required",
"else",
"Optional",
"(",
"k",
")",
"d",
"[",
"k",
"]",
"=",
"_to",
"(",
"v",
")",
"if",
"allow_custom_keys",
":",
"d",
"[",
"Optional",
"(",
"basestring",
")",
"]",
"=",
"modifier",
"or",
"object",
"schema",
"=",
"Schema",
"(",
"d",
")",
"elif",
"modifier",
":",
"schema",
"=",
"And",
"(",
"value",
",",
"modifier",
")",
"else",
":",
"schema",
"=",
"value",
"return",
"schema",
"return",
"_to",
"(",
"schema_dict",
")"
] | Convert a dict of Schemas into a Schema.
Args:
required (bool): Whether to make schema keys optional or required.
allow_custom_keys (bool, optional): If True, creates a schema that
allows custom items in dicts.
modifier (callable): Functor to apply to dict values - it is applied
via `Schema.Use`.
Returns:
A `Schema` object. | [
"Convert",
"a",
"dict",
"of",
"Schemas",
"into",
"a",
"Schema",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/schema.py#L40-L72 |
232,318 | nerdvegas/rez | src/rezgui/widgets/ContextTableWidget.py | ContextTableWidget.enter_diff_mode | def enter_diff_mode(self, context_model=None):
"""Enter diff mode.
Args:
context_model (`ContextModel`): Context to diff against. If None, a
copy of the current context is used.
"""
assert not self.diff_mode
self.diff_mode = True
if context_model is None:
self.diff_from_source = True
self.diff_context_model = self.context_model.copy()
else:
self.diff_from_source = False
self.diff_context_model = context_model
self.clear()
self.setColumnCount(5)
self.refresh() | python | def enter_diff_mode(self, context_model=None):
"""Enter diff mode.
Args:
context_model (`ContextModel`): Context to diff against. If None, a
copy of the current context is used.
"""
assert not self.diff_mode
self.diff_mode = True
if context_model is None:
self.diff_from_source = True
self.diff_context_model = self.context_model.copy()
else:
self.diff_from_source = False
self.diff_context_model = context_model
self.clear()
self.setColumnCount(5)
self.refresh() | [
"def",
"enter_diff_mode",
"(",
"self",
",",
"context_model",
"=",
"None",
")",
":",
"assert",
"not",
"self",
".",
"diff_mode",
"self",
".",
"diff_mode",
"=",
"True",
"if",
"context_model",
"is",
"None",
":",
"self",
".",
"diff_from_source",
"=",
"True",
"self",
".",
"diff_context_model",
"=",
"self",
".",
"context_model",
".",
"copy",
"(",
")",
"else",
":",
"self",
".",
"diff_from_source",
"=",
"False",
"self",
".",
"diff_context_model",
"=",
"context_model",
"self",
".",
"clear",
"(",
")",
"self",
".",
"setColumnCount",
"(",
"5",
")",
"self",
".",
"refresh",
"(",
")"
] | Enter diff mode.
Args:
context_model (`ContextModel`): Context to diff against. If None, a
copy of the current context is used. | [
"Enter",
"diff",
"mode",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/widgets/ContextTableWidget.py#L349-L368 |
232,319 | nerdvegas/rez | src/rezgui/widgets/ContextTableWidget.py | ContextTableWidget.leave_diff_mode | def leave_diff_mode(self):
"""Leave diff mode."""
assert self.diff_mode
self.diff_mode = False
self.diff_context_model = None
self.diff_from_source = False
self.setColumnCount(2)
self.refresh() | python | def leave_diff_mode(self):
"""Leave diff mode."""
assert self.diff_mode
self.diff_mode = False
self.diff_context_model = None
self.diff_from_source = False
self.setColumnCount(2)
self.refresh() | [
"def",
"leave_diff_mode",
"(",
"self",
")",
":",
"assert",
"self",
".",
"diff_mode",
"self",
".",
"diff_mode",
"=",
"False",
"self",
".",
"diff_context_model",
"=",
"None",
"self",
".",
"diff_from_source",
"=",
"False",
"self",
".",
"setColumnCount",
"(",
"2",
")",
"self",
".",
"refresh",
"(",
")"
] | Leave diff mode. | [
"Leave",
"diff",
"mode",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/widgets/ContextTableWidget.py#L370-L377 |
232,320 | nerdvegas/rez | src/rezgui/widgets/ContextTableWidget.py | ContextTableWidget.get_title | def get_title(self):
"""Returns a string suitable for titling a window containing this table."""
def _title(context_model):
context = context_model.context()
if context is None:
return "new context*"
title = os.path.basename(context.load_path) if context.load_path \
else "new context"
if context_model.is_modified():
title += '*'
return title
if self.diff_mode:
diff_title = _title(self.diff_context_model)
if self.diff_from_source:
diff_title += "'"
return "%s %s %s" % (_title(self.context_model),
self.short_double_arrow, diff_title)
else:
return _title(self.context_model) | python | def get_title(self):
"""Returns a string suitable for titling a window containing this table."""
def _title(context_model):
context = context_model.context()
if context is None:
return "new context*"
title = os.path.basename(context.load_path) if context.load_path \
else "new context"
if context_model.is_modified():
title += '*'
return title
if self.diff_mode:
diff_title = _title(self.diff_context_model)
if self.diff_from_source:
diff_title += "'"
return "%s %s %s" % (_title(self.context_model),
self.short_double_arrow, diff_title)
else:
return _title(self.context_model) | [
"def",
"get_title",
"(",
"self",
")",
":",
"def",
"_title",
"(",
"context_model",
")",
":",
"context",
"=",
"context_model",
".",
"context",
"(",
")",
"if",
"context",
"is",
"None",
":",
"return",
"\"new context*\"",
"title",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"context",
".",
"load_path",
")",
"if",
"context",
".",
"load_path",
"else",
"\"new context\"",
"if",
"context_model",
".",
"is_modified",
"(",
")",
":",
"title",
"+=",
"'*'",
"return",
"title",
"if",
"self",
".",
"diff_mode",
":",
"diff_title",
"=",
"_title",
"(",
"self",
".",
"diff_context_model",
")",
"if",
"self",
".",
"diff_from_source",
":",
"diff_title",
"+=",
"\"'\"",
"return",
"\"%s %s %s\"",
"%",
"(",
"_title",
"(",
"self",
".",
"context_model",
")",
",",
"self",
".",
"short_double_arrow",
",",
"diff_title",
")",
"else",
":",
"return",
"_title",
"(",
"self",
".",
"context_model",
")"
] | Returns a string suitable for titling a window containing this table. | [
"Returns",
"a",
"string",
"suitable",
"for",
"titling",
"a",
"window",
"containing",
"this",
"table",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/widgets/ContextTableWidget.py#L390-L409 |
232,321 | nerdvegas/rez | src/rez/utils/colorize.py | _color_level | def _color_level(str_, level):
""" Return the string wrapped with the appropriate styling for the message
level. The styling will be determined based on the rez configuration.
Args:
str_ (str): The string to be wrapped.
level (str): The message level. Should be one of 'critical', 'error',
'warning', 'info' or 'debug'.
Returns:
str: The string styled with the appropriate escape sequences.
"""
fore_color, back_color, styles = _get_style_from_config(level)
return _color(str_, fore_color, back_color, styles) | python | def _color_level(str_, level):
""" Return the string wrapped with the appropriate styling for the message
level. The styling will be determined based on the rez configuration.
Args:
str_ (str): The string to be wrapped.
level (str): The message level. Should be one of 'critical', 'error',
'warning', 'info' or 'debug'.
Returns:
str: The string styled with the appropriate escape sequences.
"""
fore_color, back_color, styles = _get_style_from_config(level)
return _color(str_, fore_color, back_color, styles) | [
"def",
"_color_level",
"(",
"str_",
",",
"level",
")",
":",
"fore_color",
",",
"back_color",
",",
"styles",
"=",
"_get_style_from_config",
"(",
"level",
")",
"return",
"_color",
"(",
"str_",
",",
"fore_color",
",",
"back_color",
",",
"styles",
")"
] | Return the string wrapped with the appropriate styling for the message
level. The styling will be determined based on the rez configuration.
Args:
str_ (str): The string to be wrapped.
level (str): The message level. Should be one of 'critical', 'error',
'warning', 'info' or 'debug'.
Returns:
str: The string styled with the appropriate escape sequences. | [
"Return",
"the",
"string",
"wrapped",
"with",
"the",
"appropriate",
"styling",
"for",
"the",
"message",
"level",
".",
"The",
"styling",
"will",
"be",
"determined",
"based",
"on",
"the",
"rez",
"configuration",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/colorize.py#L160-L173 |
232,322 | nerdvegas/rez | src/rez/utils/colorize.py | _color | def _color(str_, fore_color=None, back_color=None, styles=None):
""" Return the string wrapped with the appropriate styling escape sequences.
Args:
str_ (str): The string to be wrapped.
fore_color (str, optional): Any foreground color supported by the
`Colorama`_ module.
back_color (str, optional): Any background color supported by the
`Colorama`_ module.
styles (list of str, optional): Any styles supported by the `Colorama`_
module.
Returns:
str: The string styled with the appropriate escape sequences.
.. _Colorama:
https://pypi.python.org/pypi/colorama
"""
# TODO: Colorama is documented to work on Windows and trivial test case
# proves this to be the case, but it doesn't work in Rez. If the initialise
# is called in sec/rez/__init__.py then it does work, however as discussed
# in the following comment this is not always desirable. So until we can
# work out why we forcibly turn it off.
if not config.get("color_enabled", False) or platform_.name == "windows":
return str_
# lazily init colorama. This is important - we don't want to init at startup,
# because colorama prints a RESET_ALL character atexit. This in turn adds
# unexpected output when capturing the output of a command run in a
# ResolvedContext, for example.
_init_colorama()
colored = ""
if not styles:
styles = []
if fore_color:
colored += getattr(colorama.Fore, fore_color.upper(), '')
if back_color:
colored += getattr(colorama.Back, back_color.upper(), '')
for style in styles:
colored += getattr(colorama.Style, style.upper(), '')
return colored + str_ + colorama.Style.RESET_ALL | python | def _color(str_, fore_color=None, back_color=None, styles=None):
""" Return the string wrapped with the appropriate styling escape sequences.
Args:
str_ (str): The string to be wrapped.
fore_color (str, optional): Any foreground color supported by the
`Colorama`_ module.
back_color (str, optional): Any background color supported by the
`Colorama`_ module.
styles (list of str, optional): Any styles supported by the `Colorama`_
module.
Returns:
str: The string styled with the appropriate escape sequences.
.. _Colorama:
https://pypi.python.org/pypi/colorama
"""
# TODO: Colorama is documented to work on Windows and trivial test case
# proves this to be the case, but it doesn't work in Rez. If the initialise
# is called in sec/rez/__init__.py then it does work, however as discussed
# in the following comment this is not always desirable. So until we can
# work out why we forcibly turn it off.
if not config.get("color_enabled", False) or platform_.name == "windows":
return str_
# lazily init colorama. This is important - we don't want to init at startup,
# because colorama prints a RESET_ALL character atexit. This in turn adds
# unexpected output when capturing the output of a command run in a
# ResolvedContext, for example.
_init_colorama()
colored = ""
if not styles:
styles = []
if fore_color:
colored += getattr(colorama.Fore, fore_color.upper(), '')
if back_color:
colored += getattr(colorama.Back, back_color.upper(), '')
for style in styles:
colored += getattr(colorama.Style, style.upper(), '')
return colored + str_ + colorama.Style.RESET_ALL | [
"def",
"_color",
"(",
"str_",
",",
"fore_color",
"=",
"None",
",",
"back_color",
"=",
"None",
",",
"styles",
"=",
"None",
")",
":",
"# TODO: Colorama is documented to work on Windows and trivial test case",
"# proves this to be the case, but it doesn't work in Rez. If the initialise",
"# is called in sec/rez/__init__.py then it does work, however as discussed",
"# in the following comment this is not always desirable. So until we can",
"# work out why we forcibly turn it off.",
"if",
"not",
"config",
".",
"get",
"(",
"\"color_enabled\"",
",",
"False",
")",
"or",
"platform_",
".",
"name",
"==",
"\"windows\"",
":",
"return",
"str_",
"# lazily init colorama. This is important - we don't want to init at startup,",
"# because colorama prints a RESET_ALL character atexit. This in turn adds",
"# unexpected output when capturing the output of a command run in a",
"# ResolvedContext, for example.",
"_init_colorama",
"(",
")",
"colored",
"=",
"\"\"",
"if",
"not",
"styles",
":",
"styles",
"=",
"[",
"]",
"if",
"fore_color",
":",
"colored",
"+=",
"getattr",
"(",
"colorama",
".",
"Fore",
",",
"fore_color",
".",
"upper",
"(",
")",
",",
"''",
")",
"if",
"back_color",
":",
"colored",
"+=",
"getattr",
"(",
"colorama",
".",
"Back",
",",
"back_color",
".",
"upper",
"(",
")",
",",
"''",
")",
"for",
"style",
"in",
"styles",
":",
"colored",
"+=",
"getattr",
"(",
"colorama",
".",
"Style",
",",
"style",
".",
"upper",
"(",
")",
",",
"''",
")",
"return",
"colored",
"+",
"str_",
"+",
"colorama",
".",
"Style",
".",
"RESET_ALL"
] | Return the string wrapped with the appropriate styling escape sequences.
Args:
str_ (str): The string to be wrapped.
fore_color (str, optional): Any foreground color supported by the
`Colorama`_ module.
back_color (str, optional): Any background color supported by the
`Colorama`_ module.
styles (list of str, optional): Any styles supported by the `Colorama`_
module.
Returns:
str: The string styled with the appropriate escape sequences.
.. _Colorama:
https://pypi.python.org/pypi/colorama | [
"Return",
"the",
"string",
"wrapped",
"with",
"the",
"appropriate",
"styling",
"escape",
"sequences",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/colorize.py#L176-L219 |
232,323 | nerdvegas/rez | src/rez/utils/sourcecode.py | late | def late():
"""Used by functions in package.py that are evaluated lazily.
The term 'late' refers to the fact these package attributes are evaluated
late, ie when the attribute is queried for the first time.
If you want to implement a package.py attribute as a function, you MUST use
this decorator - otherwise it is understood that you want your attribute to
be a function, not the return value of that function.
"""
from rez.package_resources_ import package_rex_keys
def decorated(fn):
# this is done here rather than in standard schema validation because
# the latter causes a very obfuscated error message
if fn.__name__ in package_rex_keys:
raise ValueError("Cannot use @late decorator on function '%s'"
% fn.__name__)
setattr(fn, "_late", True)
_add_decorator(fn, "late")
return fn
return decorated | python | def late():
"""Used by functions in package.py that are evaluated lazily.
The term 'late' refers to the fact these package attributes are evaluated
late, ie when the attribute is queried for the first time.
If you want to implement a package.py attribute as a function, you MUST use
this decorator - otherwise it is understood that you want your attribute to
be a function, not the return value of that function.
"""
from rez.package_resources_ import package_rex_keys
def decorated(fn):
# this is done here rather than in standard schema validation because
# the latter causes a very obfuscated error message
if fn.__name__ in package_rex_keys:
raise ValueError("Cannot use @late decorator on function '%s'"
% fn.__name__)
setattr(fn, "_late", True)
_add_decorator(fn, "late")
return fn
return decorated | [
"def",
"late",
"(",
")",
":",
"from",
"rez",
".",
"package_resources_",
"import",
"package_rex_keys",
"def",
"decorated",
"(",
"fn",
")",
":",
"# this is done here rather than in standard schema validation because",
"# the latter causes a very obfuscated error message",
"if",
"fn",
".",
"__name__",
"in",
"package_rex_keys",
":",
"raise",
"ValueError",
"(",
"\"Cannot use @late decorator on function '%s'\"",
"%",
"fn",
".",
"__name__",
")",
"setattr",
"(",
"fn",
",",
"\"_late\"",
",",
"True",
")",
"_add_decorator",
"(",
"fn",
",",
"\"late\"",
")",
"return",
"fn",
"return",
"decorated"
] | Used by functions in package.py that are evaluated lazily.
The term 'late' refers to the fact these package attributes are evaluated
late, ie when the attribute is queried for the first time.
If you want to implement a package.py attribute as a function, you MUST use
this decorator - otherwise it is understood that you want your attribute to
be a function, not the return value of that function. | [
"Used",
"by",
"functions",
"in",
"package",
".",
"py",
"that",
"are",
"evaluated",
"lazily",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/sourcecode.py#L25-L49 |
232,324 | nerdvegas/rez | src/rez/utils/sourcecode.py | include | def include(module_name, *module_names):
"""Used by functions in package.py to have access to named modules.
See the 'package_definition_python_path' config setting for more info.
"""
def decorated(fn):
_add_decorator(fn, "include", nargs=[module_name] + list(module_names))
return fn
return decorated | python | def include(module_name, *module_names):
"""Used by functions in package.py to have access to named modules.
See the 'package_definition_python_path' config setting for more info.
"""
def decorated(fn):
_add_decorator(fn, "include", nargs=[module_name] + list(module_names))
return fn
return decorated | [
"def",
"include",
"(",
"module_name",
",",
"*",
"module_names",
")",
":",
"def",
"decorated",
"(",
"fn",
")",
":",
"_add_decorator",
"(",
"fn",
",",
"\"include\"",
",",
"nargs",
"=",
"[",
"module_name",
"]",
"+",
"list",
"(",
"module_names",
")",
")",
"return",
"fn",
"return",
"decorated"
] | Used by functions in package.py to have access to named modules.
See the 'package_definition_python_path' config setting for more info. | [
"Used",
"by",
"functions",
"in",
"package",
".",
"py",
"to",
"have",
"access",
"to",
"named",
"modules",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/sourcecode.py#L52-L61 |
232,325 | nerdvegas/rez | src/rez/packages_.py | iter_package_families | def iter_package_families(paths=None):
"""Iterate over package families, in no particular order.
Note that multiple package families with the same name can be returned.
Unlike packages, families later in the searchpath are not hidden by earlier
families.
Args:
paths (list of str, optional): paths to search for package families,
defaults to `config.packages_path`.
Returns:
`PackageFamily` iterator.
"""
for path in (paths or config.packages_path):
repo = package_repository_manager.get_repository(path)
for resource in repo.iter_package_families():
yield PackageFamily(resource) | python | def iter_package_families(paths=None):
"""Iterate over package families, in no particular order.
Note that multiple package families with the same name can be returned.
Unlike packages, families later in the searchpath are not hidden by earlier
families.
Args:
paths (list of str, optional): paths to search for package families,
defaults to `config.packages_path`.
Returns:
`PackageFamily` iterator.
"""
for path in (paths or config.packages_path):
repo = package_repository_manager.get_repository(path)
for resource in repo.iter_package_families():
yield PackageFamily(resource) | [
"def",
"iter_package_families",
"(",
"paths",
"=",
"None",
")",
":",
"for",
"path",
"in",
"(",
"paths",
"or",
"config",
".",
"packages_path",
")",
":",
"repo",
"=",
"package_repository_manager",
".",
"get_repository",
"(",
"path",
")",
"for",
"resource",
"in",
"repo",
".",
"iter_package_families",
"(",
")",
":",
"yield",
"PackageFamily",
"(",
"resource",
")"
] | Iterate over package families, in no particular order.
Note that multiple package families with the same name can be returned.
Unlike packages, families later in the searchpath are not hidden by earlier
families.
Args:
paths (list of str, optional): paths to search for package families,
defaults to `config.packages_path`.
Returns:
`PackageFamily` iterator. | [
"Iterate",
"over",
"package",
"families",
"in",
"no",
"particular",
"order",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L465-L482 |
232,326 | nerdvegas/rez | src/rez/packages_.py | iter_packages | def iter_packages(name, range_=None, paths=None):
"""Iterate over `Package` instances, in no particular order.
Packages of the same name and version earlier in the search path take
precedence - equivalent packages later in the paths are ignored. Packages
are not returned in any specific order.
Args:
name (str): Name of the package, eg 'maya'.
range_ (VersionRange or str): If provided, limits the versions returned
to those in `range_`.
paths (list of str, optional): paths to search for packages, defaults
to `config.packages_path`.
Returns:
`Package` iterator.
"""
entries = _get_families(name, paths)
seen = set()
for repo, family_resource in entries:
for package_resource in repo.iter_packages(family_resource):
key = (package_resource.name, package_resource.version)
if key in seen:
continue
seen.add(key)
if range_:
if isinstance(range_, basestring):
range_ = VersionRange(range_)
if package_resource.version not in range_:
continue
yield Package(package_resource) | python | def iter_packages(name, range_=None, paths=None):
"""Iterate over `Package` instances, in no particular order.
Packages of the same name and version earlier in the search path take
precedence - equivalent packages later in the paths are ignored. Packages
are not returned in any specific order.
Args:
name (str): Name of the package, eg 'maya'.
range_ (VersionRange or str): If provided, limits the versions returned
to those in `range_`.
paths (list of str, optional): paths to search for packages, defaults
to `config.packages_path`.
Returns:
`Package` iterator.
"""
entries = _get_families(name, paths)
seen = set()
for repo, family_resource in entries:
for package_resource in repo.iter_packages(family_resource):
key = (package_resource.name, package_resource.version)
if key in seen:
continue
seen.add(key)
if range_:
if isinstance(range_, basestring):
range_ = VersionRange(range_)
if package_resource.version not in range_:
continue
yield Package(package_resource) | [
"def",
"iter_packages",
"(",
"name",
",",
"range_",
"=",
"None",
",",
"paths",
"=",
"None",
")",
":",
"entries",
"=",
"_get_families",
"(",
"name",
",",
"paths",
")",
"seen",
"=",
"set",
"(",
")",
"for",
"repo",
",",
"family_resource",
"in",
"entries",
":",
"for",
"package_resource",
"in",
"repo",
".",
"iter_packages",
"(",
"family_resource",
")",
":",
"key",
"=",
"(",
"package_resource",
".",
"name",
",",
"package_resource",
".",
"version",
")",
"if",
"key",
"in",
"seen",
":",
"continue",
"seen",
".",
"add",
"(",
"key",
")",
"if",
"range_",
":",
"if",
"isinstance",
"(",
"range_",
",",
"basestring",
")",
":",
"range_",
"=",
"VersionRange",
"(",
"range_",
")",
"if",
"package_resource",
".",
"version",
"not",
"in",
"range_",
":",
"continue",
"yield",
"Package",
"(",
"package_resource",
")"
] | Iterate over `Package` instances, in no particular order.
Packages of the same name and version earlier in the search path take
precedence - equivalent packages later in the paths are ignored. Packages
are not returned in any specific order.
Args:
name (str): Name of the package, eg 'maya'.
range_ (VersionRange or str): If provided, limits the versions returned
to those in `range_`.
paths (list of str, optional): paths to search for packages, defaults
to `config.packages_path`.
Returns:
`Package` iterator. | [
"Iterate",
"over",
"Package",
"instances",
"in",
"no",
"particular",
"order",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L485-L518 |
232,327 | nerdvegas/rez | src/rez/packages_.py | get_package | def get_package(name, version, paths=None):
"""Get an exact version of a package.
Args:
name (str): Name of the package, eg 'maya'.
version (Version or str): Version of the package, eg '1.0.0'
paths (list of str, optional): paths to search for package, defaults
to `config.packages_path`.
Returns:
`Package` object, or None if the package was not found.
"""
if isinstance(version, basestring):
range_ = VersionRange("==%s" % version)
else:
range_ = VersionRange.from_version(version, "==")
it = iter_packages(name, range_, paths)
try:
return it.next()
except StopIteration:
return None | python | def get_package(name, version, paths=None):
"""Get an exact version of a package.
Args:
name (str): Name of the package, eg 'maya'.
version (Version or str): Version of the package, eg '1.0.0'
paths (list of str, optional): paths to search for package, defaults
to `config.packages_path`.
Returns:
`Package` object, or None if the package was not found.
"""
if isinstance(version, basestring):
range_ = VersionRange("==%s" % version)
else:
range_ = VersionRange.from_version(version, "==")
it = iter_packages(name, range_, paths)
try:
return it.next()
except StopIteration:
return None | [
"def",
"get_package",
"(",
"name",
",",
"version",
",",
"paths",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"version",
",",
"basestring",
")",
":",
"range_",
"=",
"VersionRange",
"(",
"\"==%s\"",
"%",
"version",
")",
"else",
":",
"range_",
"=",
"VersionRange",
".",
"from_version",
"(",
"version",
",",
"\"==\"",
")",
"it",
"=",
"iter_packages",
"(",
"name",
",",
"range_",
",",
"paths",
")",
"try",
":",
"return",
"it",
".",
"next",
"(",
")",
"except",
"StopIteration",
":",
"return",
"None"
] | Get an exact version of a package.
Args:
name (str): Name of the package, eg 'maya'.
version (Version or str): Version of the package, eg '1.0.0'
paths (list of str, optional): paths to search for package, defaults
to `config.packages_path`.
Returns:
`Package` object, or None if the package was not found. | [
"Get",
"an",
"exact",
"version",
"of",
"a",
"package",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L521-L542 |
232,328 | nerdvegas/rez | src/rez/packages_.py | get_package_from_string | def get_package_from_string(txt, paths=None):
"""Get a package given a string.
Args:
txt (str): String such as 'foo', 'bah-1.3'.
paths (list of str, optional): paths to search for package, defaults
to `config.packages_path`.
Returns:
`Package` instance, or None if no package was found.
"""
o = VersionedObject(txt)
return get_package(o.name, o.version, paths=paths) | python | def get_package_from_string(txt, paths=None):
"""Get a package given a string.
Args:
txt (str): String such as 'foo', 'bah-1.3'.
paths (list of str, optional): paths to search for package, defaults
to `config.packages_path`.
Returns:
`Package` instance, or None if no package was found.
"""
o = VersionedObject(txt)
return get_package(o.name, o.version, paths=paths) | [
"def",
"get_package_from_string",
"(",
"txt",
",",
"paths",
"=",
"None",
")",
":",
"o",
"=",
"VersionedObject",
"(",
"txt",
")",
"return",
"get_package",
"(",
"o",
".",
"name",
",",
"o",
".",
"version",
",",
"paths",
"=",
"paths",
")"
] | Get a package given a string.
Args:
txt (str): String such as 'foo', 'bah-1.3'.
paths (list of str, optional): paths to search for package, defaults
to `config.packages_path`.
Returns:
`Package` instance, or None if no package was found. | [
"Get",
"a",
"package",
"given",
"a",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L563-L575 |
232,329 | nerdvegas/rez | src/rez/packages_.py | get_developer_package | def get_developer_package(path, format=None):
"""Create a developer package.
Args:
path (str): Path to dir containing package definition file.
format (str): Package definition file format, detected if None.
Returns:
`DeveloperPackage`.
"""
from rez.developer_package import DeveloperPackage
return DeveloperPackage.from_path(path, format=format) | python | def get_developer_package(path, format=None):
"""Create a developer package.
Args:
path (str): Path to dir containing package definition file.
format (str): Package definition file format, detected if None.
Returns:
`DeveloperPackage`.
"""
from rez.developer_package import DeveloperPackage
return DeveloperPackage.from_path(path, format=format) | [
"def",
"get_developer_package",
"(",
"path",
",",
"format",
"=",
"None",
")",
":",
"from",
"rez",
".",
"developer_package",
"import",
"DeveloperPackage",
"return",
"DeveloperPackage",
".",
"from_path",
"(",
"path",
",",
"format",
"=",
"format",
")"
] | Create a developer package.
Args:
path (str): Path to dir containing package definition file.
format (str): Package definition file format, detected if None.
Returns:
`DeveloperPackage`. | [
"Create",
"a",
"developer",
"package",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L578-L589 |
232,330 | nerdvegas/rez | src/rez/packages_.py | create_package | def create_package(name, data, package_cls=None):
"""Create a package given package data.
Args:
name (str): Package name.
data (dict): Package data. Must conform to `package_maker.package_schema`.
Returns:
`Package` object.
"""
from rez.package_maker__ import PackageMaker
maker = PackageMaker(name, data, package_cls=package_cls)
return maker.get_package() | python | def create_package(name, data, package_cls=None):
"""Create a package given package data.
Args:
name (str): Package name.
data (dict): Package data. Must conform to `package_maker.package_schema`.
Returns:
`Package` object.
"""
from rez.package_maker__ import PackageMaker
maker = PackageMaker(name, data, package_cls=package_cls)
return maker.get_package() | [
"def",
"create_package",
"(",
"name",
",",
"data",
",",
"package_cls",
"=",
"None",
")",
":",
"from",
"rez",
".",
"package_maker__",
"import",
"PackageMaker",
"maker",
"=",
"PackageMaker",
"(",
"name",
",",
"data",
",",
"package_cls",
"=",
"package_cls",
")",
"return",
"maker",
".",
"get_package",
"(",
")"
] | Create a package given package data.
Args:
name (str): Package name.
data (dict): Package data. Must conform to `package_maker.package_schema`.
Returns:
`Package` object. | [
"Create",
"a",
"package",
"given",
"package",
"data",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L592-L604 |
232,331 | nerdvegas/rez | src/rez/packages_.py | get_last_release_time | def get_last_release_time(name, paths=None):
"""Returns the most recent time this package was released.
Note that releasing a variant into an already-released package is also
considered a package release.
Returns:
int: Epoch time of last package release, or zero if this cannot be
determined.
"""
entries = _get_families(name, paths)
max_time = 0
for repo, family_resource in entries:
time_ = repo.get_last_release_time(family_resource)
if time_ == 0:
return 0
max_time = max(max_time, time_)
return max_time | python | def get_last_release_time(name, paths=None):
"""Returns the most recent time this package was released.
Note that releasing a variant into an already-released package is also
considered a package release.
Returns:
int: Epoch time of last package release, or zero if this cannot be
determined.
"""
entries = _get_families(name, paths)
max_time = 0
for repo, family_resource in entries:
time_ = repo.get_last_release_time(family_resource)
if time_ == 0:
return 0
max_time = max(max_time, time_)
return max_time | [
"def",
"get_last_release_time",
"(",
"name",
",",
"paths",
"=",
"None",
")",
":",
"entries",
"=",
"_get_families",
"(",
"name",
",",
"paths",
")",
"max_time",
"=",
"0",
"for",
"repo",
",",
"family_resource",
"in",
"entries",
":",
"time_",
"=",
"repo",
".",
"get_last_release_time",
"(",
"family_resource",
")",
"if",
"time_",
"==",
"0",
":",
"return",
"0",
"max_time",
"=",
"max",
"(",
"max_time",
",",
"time_",
")",
"return",
"max_time"
] | Returns the most recent time this package was released.
Note that releasing a variant into an already-released package is also
considered a package release.
Returns:
int: Epoch time of last package release, or zero if this cannot be
determined. | [
"Returns",
"the",
"most",
"recent",
"time",
"this",
"package",
"was",
"released",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L628-L646 |
232,332 | nerdvegas/rez | src/rez/packages_.py | get_completions | def get_completions(prefix, paths=None, family_only=False):
"""Get autocompletion options given a prefix string.
Example:
>>> get_completions("may")
set(["maya", "maya_utils"])
>>> get_completions("maya-")
set(["maya-2013.1", "maya-2015.0.sp1"])
Args:
prefix (str): Prefix to match.
paths (list of str): paths to search for packages, defaults to
`config.packages_path`.
family_only (bool): If True, only match package names, do not include
version component.
Returns:
Set of strings, may be empty.
"""
op = None
if prefix:
if prefix[0] in ('!', '~'):
if family_only:
return set()
op = prefix[0]
prefix = prefix[1:]
fam = None
for ch in ('-', '@', '#'):
if ch in prefix:
if family_only:
return set()
fam = prefix.split(ch)[0]
break
words = set()
if not fam:
words = set(x.name for x in iter_package_families(paths=paths)
if x.name.startswith(prefix))
if len(words) == 1:
fam = iter(words).next()
if family_only:
return words
if fam:
it = iter_packages(fam, paths=paths)
words.update(x.qualified_name for x in it
if x.qualified_name.startswith(prefix))
if op:
words = set(op + x for x in words)
return words | python | def get_completions(prefix, paths=None, family_only=False):
"""Get autocompletion options given a prefix string.
Example:
>>> get_completions("may")
set(["maya", "maya_utils"])
>>> get_completions("maya-")
set(["maya-2013.1", "maya-2015.0.sp1"])
Args:
prefix (str): Prefix to match.
paths (list of str): paths to search for packages, defaults to
`config.packages_path`.
family_only (bool): If True, only match package names, do not include
version component.
Returns:
Set of strings, may be empty.
"""
op = None
if prefix:
if prefix[0] in ('!', '~'):
if family_only:
return set()
op = prefix[0]
prefix = prefix[1:]
fam = None
for ch in ('-', '@', '#'):
if ch in prefix:
if family_only:
return set()
fam = prefix.split(ch)[0]
break
words = set()
if not fam:
words = set(x.name for x in iter_package_families(paths=paths)
if x.name.startswith(prefix))
if len(words) == 1:
fam = iter(words).next()
if family_only:
return words
if fam:
it = iter_packages(fam, paths=paths)
words.update(x.qualified_name for x in it
if x.qualified_name.startswith(prefix))
if op:
words = set(op + x for x in words)
return words | [
"def",
"get_completions",
"(",
"prefix",
",",
"paths",
"=",
"None",
",",
"family_only",
"=",
"False",
")",
":",
"op",
"=",
"None",
"if",
"prefix",
":",
"if",
"prefix",
"[",
"0",
"]",
"in",
"(",
"'!'",
",",
"'~'",
")",
":",
"if",
"family_only",
":",
"return",
"set",
"(",
")",
"op",
"=",
"prefix",
"[",
"0",
"]",
"prefix",
"=",
"prefix",
"[",
"1",
":",
"]",
"fam",
"=",
"None",
"for",
"ch",
"in",
"(",
"'-'",
",",
"'@'",
",",
"'#'",
")",
":",
"if",
"ch",
"in",
"prefix",
":",
"if",
"family_only",
":",
"return",
"set",
"(",
")",
"fam",
"=",
"prefix",
".",
"split",
"(",
"ch",
")",
"[",
"0",
"]",
"break",
"words",
"=",
"set",
"(",
")",
"if",
"not",
"fam",
":",
"words",
"=",
"set",
"(",
"x",
".",
"name",
"for",
"x",
"in",
"iter_package_families",
"(",
"paths",
"=",
"paths",
")",
"if",
"x",
".",
"name",
".",
"startswith",
"(",
"prefix",
")",
")",
"if",
"len",
"(",
"words",
")",
"==",
"1",
":",
"fam",
"=",
"iter",
"(",
"words",
")",
".",
"next",
"(",
")",
"if",
"family_only",
":",
"return",
"words",
"if",
"fam",
":",
"it",
"=",
"iter_packages",
"(",
"fam",
",",
"paths",
"=",
"paths",
")",
"words",
".",
"update",
"(",
"x",
".",
"qualified_name",
"for",
"x",
"in",
"it",
"if",
"x",
".",
"qualified_name",
".",
"startswith",
"(",
"prefix",
")",
")",
"if",
"op",
":",
"words",
"=",
"set",
"(",
"op",
"+",
"x",
"for",
"x",
"in",
"words",
")",
"return",
"words"
] | Get autocompletion options given a prefix string.
Example:
>>> get_completions("may")
set(["maya", "maya_utils"])
>>> get_completions("maya-")
set(["maya-2013.1", "maya-2015.0.sp1"])
Args:
prefix (str): Prefix to match.
paths (list of str): paths to search for packages, defaults to
`config.packages_path`.
family_only (bool): If True, only match package names, do not include
version component.
Returns:
Set of strings, may be empty. | [
"Get",
"autocompletion",
"options",
"given",
"a",
"prefix",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L649-L702 |
232,333 | nerdvegas/rez | src/rez/packages_.py | PackageFamily.iter_packages | def iter_packages(self):
"""Iterate over the packages within this family, in no particular order.
Returns:
`Package` iterator.
"""
for package in self.repository.iter_packages(self.resource):
yield Package(package) | python | def iter_packages(self):
"""Iterate over the packages within this family, in no particular order.
Returns:
`Package` iterator.
"""
for package in self.repository.iter_packages(self.resource):
yield Package(package) | [
"def",
"iter_packages",
"(",
"self",
")",
":",
"for",
"package",
"in",
"self",
".",
"repository",
".",
"iter_packages",
"(",
"self",
".",
"resource",
")",
":",
"yield",
"Package",
"(",
"package",
")"
] | Iterate over the packages within this family, in no particular order.
Returns:
`Package` iterator. | [
"Iterate",
"over",
"the",
"packages",
"within",
"this",
"family",
"in",
"no",
"particular",
"order",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L55-L62 |
232,334 | nerdvegas/rez | src/rez/packages_.py | PackageBaseResourceWrapper.is_local | def is_local(self):
"""Returns True if the package is in the local package repository"""
local_repo = package_repository_manager.get_repository(
self.config.local_packages_path)
return (self.resource._repository.uid == local_repo.uid) | python | def is_local(self):
"""Returns True if the package is in the local package repository"""
local_repo = package_repository_manager.get_repository(
self.config.local_packages_path)
return (self.resource._repository.uid == local_repo.uid) | [
"def",
"is_local",
"(",
"self",
")",
":",
"local_repo",
"=",
"package_repository_manager",
".",
"get_repository",
"(",
"self",
".",
"config",
".",
"local_packages_path",
")",
"return",
"(",
"self",
".",
"resource",
".",
"_repository",
".",
"uid",
"==",
"local_repo",
".",
"uid",
")"
] | Returns True if the package is in the local package repository | [
"Returns",
"True",
"if",
"the",
"package",
"is",
"in",
"the",
"local",
"package",
"repository"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L99-L103 |
232,335 | nerdvegas/rez | src/rez/packages_.py | PackageBaseResourceWrapper.print_info | def print_info(self, buf=None, format_=FileFormat.yaml,
skip_attributes=None, include_release=False):
"""Print the contents of the package.
Args:
buf (file-like object): Stream to write to.
format_ (`FileFormat`): Format to write in.
skip_attributes (list of str): List of attributes to not print.
include_release (bool): If True, include release-related attributes,
such as 'timestamp' and 'changelog'
"""
data = self.validated_data().copy()
# config is a special case. We only really want to show any config settings
# that were in the package.py, not the entire Config contents that get
# grafted onto the Package/Variant instance. However Variant has an empy
# 'data' dict property, since it forwards data from its parent package.
data.pop("config", None)
if self.config:
if isinstance(self, Package):
config_dict = self.data.get("config")
else:
config_dict = self.parent.data.get("config")
data["config"] = config_dict
if not include_release:
skip_attributes = list(skip_attributes or []) + list(package_release_keys)
buf = buf or sys.stdout
dump_package_data(data, buf=buf, format_=format_,
skip_attributes=skip_attributes) | python | def print_info(self, buf=None, format_=FileFormat.yaml,
skip_attributes=None, include_release=False):
"""Print the contents of the package.
Args:
buf (file-like object): Stream to write to.
format_ (`FileFormat`): Format to write in.
skip_attributes (list of str): List of attributes to not print.
include_release (bool): If True, include release-related attributes,
such as 'timestamp' and 'changelog'
"""
data = self.validated_data().copy()
# config is a special case. We only really want to show any config settings
# that were in the package.py, not the entire Config contents that get
# grafted onto the Package/Variant instance. However Variant has an empy
# 'data' dict property, since it forwards data from its parent package.
data.pop("config", None)
if self.config:
if isinstance(self, Package):
config_dict = self.data.get("config")
else:
config_dict = self.parent.data.get("config")
data["config"] = config_dict
if not include_release:
skip_attributes = list(skip_attributes or []) + list(package_release_keys)
buf = buf or sys.stdout
dump_package_data(data, buf=buf, format_=format_,
skip_attributes=skip_attributes) | [
"def",
"print_info",
"(",
"self",
",",
"buf",
"=",
"None",
",",
"format_",
"=",
"FileFormat",
".",
"yaml",
",",
"skip_attributes",
"=",
"None",
",",
"include_release",
"=",
"False",
")",
":",
"data",
"=",
"self",
".",
"validated_data",
"(",
")",
".",
"copy",
"(",
")",
"# config is a special case. We only really want to show any config settings",
"# that were in the package.py, not the entire Config contents that get",
"# grafted onto the Package/Variant instance. However Variant has an empy",
"# 'data' dict property, since it forwards data from its parent package.",
"data",
".",
"pop",
"(",
"\"config\"",
",",
"None",
")",
"if",
"self",
".",
"config",
":",
"if",
"isinstance",
"(",
"self",
",",
"Package",
")",
":",
"config_dict",
"=",
"self",
".",
"data",
".",
"get",
"(",
"\"config\"",
")",
"else",
":",
"config_dict",
"=",
"self",
".",
"parent",
".",
"data",
".",
"get",
"(",
"\"config\"",
")",
"data",
"[",
"\"config\"",
"]",
"=",
"config_dict",
"if",
"not",
"include_release",
":",
"skip_attributes",
"=",
"list",
"(",
"skip_attributes",
"or",
"[",
"]",
")",
"+",
"list",
"(",
"package_release_keys",
")",
"buf",
"=",
"buf",
"or",
"sys",
".",
"stdout",
"dump_package_data",
"(",
"data",
",",
"buf",
"=",
"buf",
",",
"format_",
"=",
"format_",
",",
"skip_attributes",
"=",
"skip_attributes",
")"
] | Print the contents of the package.
Args:
buf (file-like object): Stream to write to.
format_ (`FileFormat`): Format to write in.
skip_attributes (list of str): List of attributes to not print.
include_release (bool): If True, include release-related attributes,
such as 'timestamp' and 'changelog' | [
"Print",
"the",
"contents",
"of",
"the",
"package",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L105-L135 |
232,336 | nerdvegas/rez | src/rez/packages_.py | Package.qualified_name | def qualified_name(self):
"""Get the qualified name of the package.
Returns:
str: Name of the package with version, eg "maya-2016.1".
"""
o = VersionedObject.construct(self.name, self.version)
return str(o) | python | def qualified_name(self):
"""Get the qualified name of the package.
Returns:
str: Name of the package with version, eg "maya-2016.1".
"""
o = VersionedObject.construct(self.name, self.version)
return str(o) | [
"def",
"qualified_name",
"(",
"self",
")",
":",
"o",
"=",
"VersionedObject",
".",
"construct",
"(",
"self",
".",
"name",
",",
"self",
".",
"version",
")",
"return",
"str",
"(",
"o",
")"
] | Get the qualified name of the package.
Returns:
str: Name of the package with version, eg "maya-2016.1". | [
"Get",
"the",
"qualified",
"name",
"of",
"the",
"package",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L218-L225 |
232,337 | nerdvegas/rez | src/rez/packages_.py | Package.parent | def parent(self):
"""Get the parent package family.
Returns:
`PackageFamily`.
"""
family = self.repository.get_parent_package_family(self.resource)
return PackageFamily(family) if family else None | python | def parent(self):
"""Get the parent package family.
Returns:
`PackageFamily`.
"""
family = self.repository.get_parent_package_family(self.resource)
return PackageFamily(family) if family else None | [
"def",
"parent",
"(",
"self",
")",
":",
"family",
"=",
"self",
".",
"repository",
".",
"get_parent_package_family",
"(",
"self",
".",
"resource",
")",
"return",
"PackageFamily",
"(",
"family",
")",
"if",
"family",
"else",
"None"
] | Get the parent package family.
Returns:
`PackageFamily`. | [
"Get",
"the",
"parent",
"package",
"family",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L228-L235 |
232,338 | nerdvegas/rez | src/rez/packages_.py | Package.iter_variants | def iter_variants(self):
"""Iterate over the variants within this package, in index order.
Returns:
`Variant` iterator.
"""
for variant in self.repository.iter_variants(self.resource):
yield Variant(variant, context=self.context, parent=self) | python | def iter_variants(self):
"""Iterate over the variants within this package, in index order.
Returns:
`Variant` iterator.
"""
for variant in self.repository.iter_variants(self.resource):
yield Variant(variant, context=self.context, parent=self) | [
"def",
"iter_variants",
"(",
"self",
")",
":",
"for",
"variant",
"in",
"self",
".",
"repository",
".",
"iter_variants",
"(",
"self",
".",
"resource",
")",
":",
"yield",
"Variant",
"(",
"variant",
",",
"context",
"=",
"self",
".",
"context",
",",
"parent",
"=",
"self",
")"
] | Iterate over the variants within this package, in index order.
Returns:
`Variant` iterator. | [
"Iterate",
"over",
"the",
"variants",
"within",
"this",
"package",
"in",
"index",
"order",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L250-L257 |
232,339 | nerdvegas/rez | src/rez/packages_.py | Package.get_variant | def get_variant(self, index=None):
"""Get the variant with the associated index.
Returns:
`Variant` object, or None if no variant with the given index exists.
"""
for variant in self.iter_variants():
if variant.index == index:
return variant | python | def get_variant(self, index=None):
"""Get the variant with the associated index.
Returns:
`Variant` object, or None if no variant with the given index exists.
"""
for variant in self.iter_variants():
if variant.index == index:
return variant | [
"def",
"get_variant",
"(",
"self",
",",
"index",
"=",
"None",
")",
":",
"for",
"variant",
"in",
"self",
".",
"iter_variants",
"(",
")",
":",
"if",
"variant",
".",
"index",
"==",
"index",
":",
"return",
"variant"
] | Get the variant with the associated index.
Returns:
`Variant` object, or None if no variant with the given index exists. | [
"Get",
"the",
"variant",
"with",
"the",
"associated",
"index",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L259-L267 |
232,340 | nerdvegas/rez | src/rez/packages_.py | Variant.qualified_name | def qualified_name(self):
"""Get the qualified name of the variant.
Returns:
str: Name of the variant with version and index, eg "maya-2016.1[1]".
"""
idxstr = '' if self.index is None else str(self.index)
return "%s[%s]" % (self.qualified_package_name, idxstr) | python | def qualified_name(self):
"""Get the qualified name of the variant.
Returns:
str: Name of the variant with version and index, eg "maya-2016.1[1]".
"""
idxstr = '' if self.index is None else str(self.index)
return "%s[%s]" % (self.qualified_package_name, idxstr) | [
"def",
"qualified_name",
"(",
"self",
")",
":",
"idxstr",
"=",
"''",
"if",
"self",
".",
"index",
"is",
"None",
"else",
"str",
"(",
"self",
".",
"index",
")",
"return",
"\"%s[%s]\"",
"%",
"(",
"self",
".",
"qualified_package_name",
",",
"idxstr",
")"
] | Get the qualified name of the variant.
Returns:
str: Name of the variant with version and index, eg "maya-2016.1[1]". | [
"Get",
"the",
"qualified",
"name",
"of",
"the",
"variant",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L305-L312 |
232,341 | nerdvegas/rez | src/rez/packages_.py | Variant.parent | def parent(self):
"""Get the parent package.
Returns:
`Package`.
"""
if self._parent is not None:
return self._parent
try:
package = self.repository.get_parent_package(self.resource)
self._parent = Package(package, context=self.context)
except AttributeError as e:
reraise(e, ValueError)
return self._parent | python | def parent(self):
"""Get the parent package.
Returns:
`Package`.
"""
if self._parent is not None:
return self._parent
try:
package = self.repository.get_parent_package(self.resource)
self._parent = Package(package, context=self.context)
except AttributeError as e:
reraise(e, ValueError)
return self._parent | [
"def",
"parent",
"(",
"self",
")",
":",
"if",
"self",
".",
"_parent",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_parent",
"try",
":",
"package",
"=",
"self",
".",
"repository",
".",
"get_parent_package",
"(",
"self",
".",
"resource",
")",
"self",
".",
"_parent",
"=",
"Package",
"(",
"package",
",",
"context",
"=",
"self",
".",
"context",
")",
"except",
"AttributeError",
"as",
"e",
":",
"reraise",
"(",
"e",
",",
"ValueError",
")",
"return",
"self",
".",
"_parent"
] | Get the parent package.
Returns:
`Package`. | [
"Get",
"the",
"parent",
"package",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L315-L330 |
232,342 | nerdvegas/rez | src/rez/packages_.py | Variant.get_requires | def get_requires(self, build_requires=False, private_build_requires=False):
"""Get the requirements of the variant.
Args:
build_requires (bool): If True, include build requirements.
private_build_requires (bool): If True, include private build
requirements.
Returns:
List of `Requirement` objects.
"""
requires = self.requires or []
if build_requires:
requires = requires + (self.build_requires or [])
if private_build_requires:
requires = requires + (self.private_build_requires or [])
return requires | python | def get_requires(self, build_requires=False, private_build_requires=False):
"""Get the requirements of the variant.
Args:
build_requires (bool): If True, include build requirements.
private_build_requires (bool): If True, include private build
requirements.
Returns:
List of `Requirement` objects.
"""
requires = self.requires or []
if build_requires:
requires = requires + (self.build_requires or [])
if private_build_requires:
requires = requires + (self.private_build_requires or [])
return requires | [
"def",
"get_requires",
"(",
"self",
",",
"build_requires",
"=",
"False",
",",
"private_build_requires",
"=",
"False",
")",
":",
"requires",
"=",
"self",
".",
"requires",
"or",
"[",
"]",
"if",
"build_requires",
":",
"requires",
"=",
"requires",
"+",
"(",
"self",
".",
"build_requires",
"or",
"[",
"]",
")",
"if",
"private_build_requires",
":",
"requires",
"=",
"requires",
"+",
"(",
"self",
".",
"private_build_requires",
"or",
"[",
"]",
")",
"return",
"requires"
] | Get the requirements of the variant.
Args:
build_requires (bool): If True, include build requirements.
private_build_requires (bool): If True, include private build
requirements.
Returns:
List of `Requirement` objects. | [
"Get",
"the",
"requirements",
"of",
"the",
"variant",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L358-L376 |
232,343 | nerdvegas/rez | src/rez/packages_.py | Variant.install | def install(self, path, dry_run=False, overrides=None):
"""Install this variant into another package repository.
If the package already exists, this variant will be correctly merged
into the package. If the variant already exists in this package, the
existing variant is returned.
Args:
path (str): Path to destination package repository.
dry_run (bool): If True, do not actually install the variant. In this
mode, a `Variant` instance is only returned if the equivalent
variant already exists in this repository; otherwise, None is
returned.
overrides (dict): Use this to change or add attributes to the
installed variant.
Returns:
`Variant` object - the (existing or newly created) variant in the
specified repository. If `dry_run` is True, None may be returned.
"""
repo = package_repository_manager.get_repository(path)
resource = repo.install_variant(self.resource,
dry_run=dry_run,
overrides=overrides)
if resource is None:
return None
elif resource is self.resource:
return self
else:
return Variant(resource) | python | def install(self, path, dry_run=False, overrides=None):
"""Install this variant into another package repository.
If the package already exists, this variant will be correctly merged
into the package. If the variant already exists in this package, the
existing variant is returned.
Args:
path (str): Path to destination package repository.
dry_run (bool): If True, do not actually install the variant. In this
mode, a `Variant` instance is only returned if the equivalent
variant already exists in this repository; otherwise, None is
returned.
overrides (dict): Use this to change or add attributes to the
installed variant.
Returns:
`Variant` object - the (existing or newly created) variant in the
specified repository. If `dry_run` is True, None may be returned.
"""
repo = package_repository_manager.get_repository(path)
resource = repo.install_variant(self.resource,
dry_run=dry_run,
overrides=overrides)
if resource is None:
return None
elif resource is self.resource:
return self
else:
return Variant(resource) | [
"def",
"install",
"(",
"self",
",",
"path",
",",
"dry_run",
"=",
"False",
",",
"overrides",
"=",
"None",
")",
":",
"repo",
"=",
"package_repository_manager",
".",
"get_repository",
"(",
"path",
")",
"resource",
"=",
"repo",
".",
"install_variant",
"(",
"self",
".",
"resource",
",",
"dry_run",
"=",
"dry_run",
",",
"overrides",
"=",
"overrides",
")",
"if",
"resource",
"is",
"None",
":",
"return",
"None",
"elif",
"resource",
"is",
"self",
".",
"resource",
":",
"return",
"self",
"else",
":",
"return",
"Variant",
"(",
"resource",
")"
] | Install this variant into another package repository.
If the package already exists, this variant will be correctly merged
into the package. If the variant already exists in this package, the
existing variant is returned.
Args:
path (str): Path to destination package repository.
dry_run (bool): If True, do not actually install the variant. In this
mode, a `Variant` instance is only returned if the equivalent
variant already exists in this repository; otherwise, None is
returned.
overrides (dict): Use this to change or add attributes to the
installed variant.
Returns:
`Variant` object - the (existing or newly created) variant in the
specified repository. If `dry_run` is True, None may be returned. | [
"Install",
"this",
"variant",
"into",
"another",
"package",
"repository",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L378-L407 |
232,344 | nerdvegas/rez | src/rez/serialise.py | open_file_for_write | def open_file_for_write(filepath, mode=None):
"""Writes both to given filepath, and tmpdir location.
This is to get around the problem with some NFS's where immediately reading
a file that has just been written is problematic. Instead, any files that we
write, we also write to /tmp, and reads of these files are redirected there.
Args:
filepath (str): File to write.
mode (int): Same mode arg as you would pass to `os.chmod`.
Yields:
File-like object.
"""
stream = StringIO()
yield stream
content = stream.getvalue()
filepath = os.path.realpath(filepath)
tmpdir = tmpdir_manager.mkdtemp()
cache_filepath = os.path.join(tmpdir, os.path.basename(filepath))
debug_print("Writing to %s (local cache of %s)", cache_filepath, filepath)
with atomic_write(filepath, overwrite=True) as f:
f.write(content)
if mode is not None:
os.chmod(filepath, mode)
with open(cache_filepath, 'w') as f:
f.write(content)
file_cache[filepath] = cache_filepath | python | def open_file_for_write(filepath, mode=None):
"""Writes both to given filepath, and tmpdir location.
This is to get around the problem with some NFS's where immediately reading
a file that has just been written is problematic. Instead, any files that we
write, we also write to /tmp, and reads of these files are redirected there.
Args:
filepath (str): File to write.
mode (int): Same mode arg as you would pass to `os.chmod`.
Yields:
File-like object.
"""
stream = StringIO()
yield stream
content = stream.getvalue()
filepath = os.path.realpath(filepath)
tmpdir = tmpdir_manager.mkdtemp()
cache_filepath = os.path.join(tmpdir, os.path.basename(filepath))
debug_print("Writing to %s (local cache of %s)", cache_filepath, filepath)
with atomic_write(filepath, overwrite=True) as f:
f.write(content)
if mode is not None:
os.chmod(filepath, mode)
with open(cache_filepath, 'w') as f:
f.write(content)
file_cache[filepath] = cache_filepath | [
"def",
"open_file_for_write",
"(",
"filepath",
",",
"mode",
"=",
"None",
")",
":",
"stream",
"=",
"StringIO",
"(",
")",
"yield",
"stream",
"content",
"=",
"stream",
".",
"getvalue",
"(",
")",
"filepath",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"filepath",
")",
"tmpdir",
"=",
"tmpdir_manager",
".",
"mkdtemp",
"(",
")",
"cache_filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmpdir",
",",
"os",
".",
"path",
".",
"basename",
"(",
"filepath",
")",
")",
"debug_print",
"(",
"\"Writing to %s (local cache of %s)\"",
",",
"cache_filepath",
",",
"filepath",
")",
"with",
"atomic_write",
"(",
"filepath",
",",
"overwrite",
"=",
"True",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"content",
")",
"if",
"mode",
"is",
"not",
"None",
":",
"os",
".",
"chmod",
"(",
"filepath",
",",
"mode",
")",
"with",
"open",
"(",
"cache_filepath",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"content",
")",
"file_cache",
"[",
"filepath",
"]",
"=",
"cache_filepath"
] | Writes both to given filepath, and tmpdir location.
This is to get around the problem with some NFS's where immediately reading
a file that has just been written is problematic. Instead, any files that we
write, we also write to /tmp, and reads of these files are redirected there.
Args:
filepath (str): File to write.
mode (int): Same mode arg as you would pass to `os.chmod`.
Yields:
File-like object. | [
"Writes",
"both",
"to",
"given",
"filepath",
"and",
"tmpdir",
"location",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/serialise.py#L43-L76 |
232,345 | nerdvegas/rez | src/rez/serialise.py | load_py | def load_py(stream, filepath=None):
"""Load python-formatted data from a stream.
Args:
stream (file-like object).
Returns:
dict.
"""
with add_sys_paths(config.package_definition_build_python_paths):
return _load_py(stream, filepath=filepath) | python | def load_py(stream, filepath=None):
"""Load python-formatted data from a stream.
Args:
stream (file-like object).
Returns:
dict.
"""
with add_sys_paths(config.package_definition_build_python_paths):
return _load_py(stream, filepath=filepath) | [
"def",
"load_py",
"(",
"stream",
",",
"filepath",
"=",
"None",
")",
":",
"with",
"add_sys_paths",
"(",
"config",
".",
"package_definition_build_python_paths",
")",
":",
"return",
"_load_py",
"(",
"stream",
",",
"filepath",
"=",
"filepath",
")"
] | Load python-formatted data from a stream.
Args:
stream (file-like object).
Returns:
dict. | [
"Load",
"python",
"-",
"formatted",
"data",
"from",
"a",
"stream",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/serialise.py#L193-L203 |
232,346 | nerdvegas/rez | src/rez/serialise.py | process_python_objects | def process_python_objects(data, filepath=None):
"""Replace certain values in the given package data dict.
Does things like:
* evaluates @early decorated functions, and replaces with return value;
* converts functions into `SourceCode` instances so they can be serialized
out to installed packages, and evaluated later;
* strips some values (modules, __-leading variables) that are never to be
part of installed packages.
Returns:
dict: Updated dict.
"""
def _process(value):
if isinstance(value, dict):
for k, v in value.items():
value[k] = _process(v)
return value
elif isfunction(value):
func = value
if hasattr(func, "_early"):
# run the function now, and replace with return value
#
# make a copy of the func with its own globals, and add 'this'
import types
fn = types.FunctionType(func.func_code,
func.func_globals.copy(),
name=func.func_name,
argdefs=func.func_defaults,
closure=func.func_closure)
# apply globals
fn.func_globals["this"] = EarlyThis(data)
fn.func_globals.update(get_objects())
# execute the function
spec = getargspec(func)
args = spec.args or []
if len(args) not in (0, 1):
raise ResourceError("@early decorated function must "
"take zero or one args only")
if args:
# this 'data' arg support isn't needed anymore, but I'm
# supporting it til I know nobody is using it...
#
value_ = fn(data)
else:
value_ = fn()
# process again in case this is a function returning a function
return _process(value_)
elif hasattr(func, "_late"):
return SourceCode(func=func, filepath=filepath,
eval_as_function=True)
elif func.__name__ in package_rex_keys:
# if a rex function, the code has to be eval'd NOT as a function,
# otherwise the globals dict doesn't get updated with any vars
# defined in the code, and that means rex code like this:
#
# rr = 'test'
# env.RR = '{rr}'
#
# ..won't work. It was never intentional that the above work, but
# it does, so now we have to keep it so.
#
return SourceCode(func=func, filepath=filepath,
eval_as_function=False)
else:
# a normal function. Leave unchanged, it will be stripped after
return func
else:
return value
def _trim(value):
if isinstance(value, dict):
for k, v in value.items():
if isfunction(v):
if v.__name__ == "preprocess":
# preprocess is a special case. It has to stay intact
# until the `DeveloperPackage` has a chance to apply it;
# after which it gets removed from the package attributes.
#
pass
else:
del value[k]
elif ismodule(v) or k.startswith("__"):
del value[k]
else:
value[k] = _trim(v)
return value
data = _process(data)
data = _trim(data)
return data | python | def process_python_objects(data, filepath=None):
"""Replace certain values in the given package data dict.
Does things like:
* evaluates @early decorated functions, and replaces with return value;
* converts functions into `SourceCode` instances so they can be serialized
out to installed packages, and evaluated later;
* strips some values (modules, __-leading variables) that are never to be
part of installed packages.
Returns:
dict: Updated dict.
"""
def _process(value):
if isinstance(value, dict):
for k, v in value.items():
value[k] = _process(v)
return value
elif isfunction(value):
func = value
if hasattr(func, "_early"):
# run the function now, and replace with return value
#
# make a copy of the func with its own globals, and add 'this'
import types
fn = types.FunctionType(func.func_code,
func.func_globals.copy(),
name=func.func_name,
argdefs=func.func_defaults,
closure=func.func_closure)
# apply globals
fn.func_globals["this"] = EarlyThis(data)
fn.func_globals.update(get_objects())
# execute the function
spec = getargspec(func)
args = spec.args or []
if len(args) not in (0, 1):
raise ResourceError("@early decorated function must "
"take zero or one args only")
if args:
# this 'data' arg support isn't needed anymore, but I'm
# supporting it til I know nobody is using it...
#
value_ = fn(data)
else:
value_ = fn()
# process again in case this is a function returning a function
return _process(value_)
elif hasattr(func, "_late"):
return SourceCode(func=func, filepath=filepath,
eval_as_function=True)
elif func.__name__ in package_rex_keys:
# if a rex function, the code has to be eval'd NOT as a function,
# otherwise the globals dict doesn't get updated with any vars
# defined in the code, and that means rex code like this:
#
# rr = 'test'
# env.RR = '{rr}'
#
# ..won't work. It was never intentional that the above work, but
# it does, so now we have to keep it so.
#
return SourceCode(func=func, filepath=filepath,
eval_as_function=False)
else:
# a normal function. Leave unchanged, it will be stripped after
return func
else:
return value
def _trim(value):
if isinstance(value, dict):
for k, v in value.items():
if isfunction(v):
if v.__name__ == "preprocess":
# preprocess is a special case. It has to stay intact
# until the `DeveloperPackage` has a chance to apply it;
# after which it gets removed from the package attributes.
#
pass
else:
del value[k]
elif ismodule(v) or k.startswith("__"):
del value[k]
else:
value[k] = _trim(v)
return value
data = _process(data)
data = _trim(data)
return data | [
"def",
"process_python_objects",
"(",
"data",
",",
"filepath",
"=",
"None",
")",
":",
"def",
"_process",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"for",
"k",
",",
"v",
"in",
"value",
".",
"items",
"(",
")",
":",
"value",
"[",
"k",
"]",
"=",
"_process",
"(",
"v",
")",
"return",
"value",
"elif",
"isfunction",
"(",
"value",
")",
":",
"func",
"=",
"value",
"if",
"hasattr",
"(",
"func",
",",
"\"_early\"",
")",
":",
"# run the function now, and replace with return value",
"#",
"# make a copy of the func with its own globals, and add 'this'",
"import",
"types",
"fn",
"=",
"types",
".",
"FunctionType",
"(",
"func",
".",
"func_code",
",",
"func",
".",
"func_globals",
".",
"copy",
"(",
")",
",",
"name",
"=",
"func",
".",
"func_name",
",",
"argdefs",
"=",
"func",
".",
"func_defaults",
",",
"closure",
"=",
"func",
".",
"func_closure",
")",
"# apply globals",
"fn",
".",
"func_globals",
"[",
"\"this\"",
"]",
"=",
"EarlyThis",
"(",
"data",
")",
"fn",
".",
"func_globals",
".",
"update",
"(",
"get_objects",
"(",
")",
")",
"# execute the function",
"spec",
"=",
"getargspec",
"(",
"func",
")",
"args",
"=",
"spec",
".",
"args",
"or",
"[",
"]",
"if",
"len",
"(",
"args",
")",
"not",
"in",
"(",
"0",
",",
"1",
")",
":",
"raise",
"ResourceError",
"(",
"\"@early decorated function must \"",
"\"take zero or one args only\"",
")",
"if",
"args",
":",
"# this 'data' arg support isn't needed anymore, but I'm",
"# supporting it til I know nobody is using it...",
"#",
"value_",
"=",
"fn",
"(",
"data",
")",
"else",
":",
"value_",
"=",
"fn",
"(",
")",
"# process again in case this is a function returning a function",
"return",
"_process",
"(",
"value_",
")",
"elif",
"hasattr",
"(",
"func",
",",
"\"_late\"",
")",
":",
"return",
"SourceCode",
"(",
"func",
"=",
"func",
",",
"filepath",
"=",
"filepath",
",",
"eval_as_function",
"=",
"True",
")",
"elif",
"func",
".",
"__name__",
"in",
"package_rex_keys",
":",
"# if a rex function, the code has to be eval'd NOT as a function,",
"# otherwise the globals dict doesn't get updated with any vars",
"# defined in the code, and that means rex code like this:",
"#",
"# rr = 'test'",
"# env.RR = '{rr}'",
"#",
"# ..won't work. It was never intentional that the above work, but",
"# it does, so now we have to keep it so.",
"#",
"return",
"SourceCode",
"(",
"func",
"=",
"func",
",",
"filepath",
"=",
"filepath",
",",
"eval_as_function",
"=",
"False",
")",
"else",
":",
"# a normal function. Leave unchanged, it will be stripped after",
"return",
"func",
"else",
":",
"return",
"value",
"def",
"_trim",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"for",
"k",
",",
"v",
"in",
"value",
".",
"items",
"(",
")",
":",
"if",
"isfunction",
"(",
"v",
")",
":",
"if",
"v",
".",
"__name__",
"==",
"\"preprocess\"",
":",
"# preprocess is a special case. It has to stay intact",
"# until the `DeveloperPackage` has a chance to apply it;",
"# after which it gets removed from the package attributes.",
"#",
"pass",
"else",
":",
"del",
"value",
"[",
"k",
"]",
"elif",
"ismodule",
"(",
"v",
")",
"or",
"k",
".",
"startswith",
"(",
"\"__\"",
")",
":",
"del",
"value",
"[",
"k",
"]",
"else",
":",
"value",
"[",
"k",
"]",
"=",
"_trim",
"(",
"v",
")",
"return",
"value",
"data",
"=",
"_process",
"(",
"data",
")",
"data",
"=",
"_trim",
"(",
"data",
")",
"return",
"data"
] | Replace certain values in the given package data dict.
Does things like:
* evaluates @early decorated functions, and replaces with return value;
* converts functions into `SourceCode` instances so they can be serialized
out to installed packages, and evaluated later;
* strips some values (modules, __-leading variables) that are never to be
part of installed packages.
Returns:
dict: Updated dict. | [
"Replace",
"certain",
"values",
"in",
"the",
"given",
"package",
"data",
"dict",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/serialise.py#L266-L366 |
232,347 | nerdvegas/rez | src/rez/serialise.py | load_yaml | def load_yaml(stream, **kwargs):
"""Load yaml-formatted data from a stream.
Args:
stream (file-like object).
Returns:
dict.
"""
# if there's an error parsing the yaml, and you pass yaml.load a string,
# it will print lines of context, but will print "<string>" instead of a
# filename; if you pass a stream, it will print the filename, but no lines
# of context.
# Get the best of both worlds, by passing it a string, then replacing
# "<string>" with the filename if there's an error...
content = stream.read()
try:
return yaml.load(content) or {}
except Exception, e:
if stream.name and stream.name != '<string>':
for mark_name in 'context_mark', 'problem_mark':
mark = getattr(e, mark_name, None)
if mark is None:
continue
if getattr(mark, 'name') == '<string>':
mark.name = stream.name
raise e | python | def load_yaml(stream, **kwargs):
"""Load yaml-formatted data from a stream.
Args:
stream (file-like object).
Returns:
dict.
"""
# if there's an error parsing the yaml, and you pass yaml.load a string,
# it will print lines of context, but will print "<string>" instead of a
# filename; if you pass a stream, it will print the filename, but no lines
# of context.
# Get the best of both worlds, by passing it a string, then replacing
# "<string>" with the filename if there's an error...
content = stream.read()
try:
return yaml.load(content) or {}
except Exception, e:
if stream.name and stream.name != '<string>':
for mark_name in 'context_mark', 'problem_mark':
mark = getattr(e, mark_name, None)
if mark is None:
continue
if getattr(mark, 'name') == '<string>':
mark.name = stream.name
raise e | [
"def",
"load_yaml",
"(",
"stream",
",",
"*",
"*",
"kwargs",
")",
":",
"# if there's an error parsing the yaml, and you pass yaml.load a string,",
"# it will print lines of context, but will print \"<string>\" instead of a",
"# filename; if you pass a stream, it will print the filename, but no lines",
"# of context.",
"# Get the best of both worlds, by passing it a string, then replacing",
"# \"<string>\" with the filename if there's an error...",
"content",
"=",
"stream",
".",
"read",
"(",
")",
"try",
":",
"return",
"yaml",
".",
"load",
"(",
"content",
")",
"or",
"{",
"}",
"except",
"Exception",
",",
"e",
":",
"if",
"stream",
".",
"name",
"and",
"stream",
".",
"name",
"!=",
"'<string>'",
":",
"for",
"mark_name",
"in",
"'context_mark'",
",",
"'problem_mark'",
":",
"mark",
"=",
"getattr",
"(",
"e",
",",
"mark_name",
",",
"None",
")",
"if",
"mark",
"is",
"None",
":",
"continue",
"if",
"getattr",
"(",
"mark",
",",
"'name'",
")",
"==",
"'<string>'",
":",
"mark",
".",
"name",
"=",
"stream",
".",
"name",
"raise",
"e"
] | Load yaml-formatted data from a stream.
Args:
stream (file-like object).
Returns:
dict. | [
"Load",
"yaml",
"-",
"formatted",
"data",
"from",
"a",
"stream",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/serialise.py#L369-L395 |
232,348 | nerdvegas/rez | src/rez/vendor/amqp/connection.py | Connection._blocked | def _blocked(self, args):
"""RabbitMQ Extension."""
reason = args.read_shortstr()
if self.on_blocked:
return self.on_blocked(reason) | python | def _blocked(self, args):
"""RabbitMQ Extension."""
reason = args.read_shortstr()
if self.on_blocked:
return self.on_blocked(reason) | [
"def",
"_blocked",
"(",
"self",
",",
"args",
")",
":",
"reason",
"=",
"args",
".",
"read_shortstr",
"(",
")",
"if",
"self",
".",
"on_blocked",
":",
"return",
"self",
".",
"on_blocked",
"(",
"reason",
")"
] | RabbitMQ Extension. | [
"RabbitMQ",
"Extension",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/connection.py#L532-L536 |
232,349 | nerdvegas/rez | src/rez/vendor/amqp/connection.py | Connection._x_secure_ok | def _x_secure_ok(self, response):
"""Security mechanism response
This method attempts to authenticate, passing a block of SASL
data for the security mechanism at the server side.
PARAMETERS:
response: longstr
security response data
A block of opaque data passed to the security
mechanism. The contents of this data are defined by
the SASL security mechanism.
"""
args = AMQPWriter()
args.write_longstr(response)
self._send_method((10, 21), args) | python | def _x_secure_ok(self, response):
"""Security mechanism response
This method attempts to authenticate, passing a block of SASL
data for the security mechanism at the server side.
PARAMETERS:
response: longstr
security response data
A block of opaque data passed to the security
mechanism. The contents of this data are defined by
the SASL security mechanism.
"""
args = AMQPWriter()
args.write_longstr(response)
self._send_method((10, 21), args) | [
"def",
"_x_secure_ok",
"(",
"self",
",",
"response",
")",
":",
"args",
"=",
"AMQPWriter",
"(",
")",
"args",
".",
"write_longstr",
"(",
"response",
")",
"self",
".",
"_send_method",
"(",
"(",
"10",
",",
"21",
")",
",",
"args",
")"
] | Security mechanism response
This method attempts to authenticate, passing a block of SASL
data for the security mechanism at the server side.
PARAMETERS:
response: longstr
security response data
A block of opaque data passed to the security
mechanism. The contents of this data are defined by
the SASL security mechanism. | [
"Security",
"mechanism",
"response"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/connection.py#L662-L680 |
232,350 | nerdvegas/rez | src/rez/vendor/amqp/connection.py | Connection._x_start_ok | def _x_start_ok(self, client_properties, mechanism, response, locale):
"""Select security mechanism and locale
This method selects a SASL security mechanism. ASL uses SASL
(RFC2222) to negotiate authentication and encryption.
PARAMETERS:
client_properties: table
client properties
mechanism: shortstr
selected security mechanism
A single security mechanisms selected by the client,
which must be one of those specified by the server.
RULE:
The client SHOULD authenticate using the highest-
level security profile it can handle from the list
provided by the server.
RULE:
The mechanism field MUST contain one of the
security mechanisms proposed by the server in the
Start method. If it doesn't, the server MUST close
the socket.
response: longstr
security response data
A block of opaque data passed to the security
mechanism. The contents of this data are defined by
the SASL security mechanism. For the PLAIN security
mechanism this is defined as a field table holding two
fields, LOGIN and PASSWORD.
locale: shortstr
selected message locale
A single message local selected by the client, which
must be one of those specified by the server.
"""
if self.server_capabilities.get('consumer_cancel_notify'):
if 'capabilities' not in client_properties:
client_properties['capabilities'] = {}
client_properties['capabilities']['consumer_cancel_notify'] = True
if self.server_capabilities.get('connection.blocked'):
if 'capabilities' not in client_properties:
client_properties['capabilities'] = {}
client_properties['capabilities']['connection.blocked'] = True
args = AMQPWriter()
args.write_table(client_properties)
args.write_shortstr(mechanism)
args.write_longstr(response)
args.write_shortstr(locale)
self._send_method((10, 11), args) | python | def _x_start_ok(self, client_properties, mechanism, response, locale):
"""Select security mechanism and locale
This method selects a SASL security mechanism. ASL uses SASL
(RFC2222) to negotiate authentication and encryption.
PARAMETERS:
client_properties: table
client properties
mechanism: shortstr
selected security mechanism
A single security mechanisms selected by the client,
which must be one of those specified by the server.
RULE:
The client SHOULD authenticate using the highest-
level security profile it can handle from the list
provided by the server.
RULE:
The mechanism field MUST contain one of the
security mechanisms proposed by the server in the
Start method. If it doesn't, the server MUST close
the socket.
response: longstr
security response data
A block of opaque data passed to the security
mechanism. The contents of this data are defined by
the SASL security mechanism. For the PLAIN security
mechanism this is defined as a field table holding two
fields, LOGIN and PASSWORD.
locale: shortstr
selected message locale
A single message local selected by the client, which
must be one of those specified by the server.
"""
if self.server_capabilities.get('consumer_cancel_notify'):
if 'capabilities' not in client_properties:
client_properties['capabilities'] = {}
client_properties['capabilities']['consumer_cancel_notify'] = True
if self.server_capabilities.get('connection.blocked'):
if 'capabilities' not in client_properties:
client_properties['capabilities'] = {}
client_properties['capabilities']['connection.blocked'] = True
args = AMQPWriter()
args.write_table(client_properties)
args.write_shortstr(mechanism)
args.write_longstr(response)
args.write_shortstr(locale)
self._send_method((10, 11), args) | [
"def",
"_x_start_ok",
"(",
"self",
",",
"client_properties",
",",
"mechanism",
",",
"response",
",",
"locale",
")",
":",
"if",
"self",
".",
"server_capabilities",
".",
"get",
"(",
"'consumer_cancel_notify'",
")",
":",
"if",
"'capabilities'",
"not",
"in",
"client_properties",
":",
"client_properties",
"[",
"'capabilities'",
"]",
"=",
"{",
"}",
"client_properties",
"[",
"'capabilities'",
"]",
"[",
"'consumer_cancel_notify'",
"]",
"=",
"True",
"if",
"self",
".",
"server_capabilities",
".",
"get",
"(",
"'connection.blocked'",
")",
":",
"if",
"'capabilities'",
"not",
"in",
"client_properties",
":",
"client_properties",
"[",
"'capabilities'",
"]",
"=",
"{",
"}",
"client_properties",
"[",
"'capabilities'",
"]",
"[",
"'connection.blocked'",
"]",
"=",
"True",
"args",
"=",
"AMQPWriter",
"(",
")",
"args",
".",
"write_table",
"(",
"client_properties",
")",
"args",
".",
"write_shortstr",
"(",
"mechanism",
")",
"args",
".",
"write_longstr",
"(",
"response",
")",
"args",
".",
"write_shortstr",
"(",
"locale",
")",
"self",
".",
"_send_method",
"(",
"(",
"10",
",",
"11",
")",
",",
"args",
")"
] | Select security mechanism and locale
This method selects a SASL security mechanism. ASL uses SASL
(RFC2222) to negotiate authentication and encryption.
PARAMETERS:
client_properties: table
client properties
mechanism: shortstr
selected security mechanism
A single security mechanisms selected by the client,
which must be one of those specified by the server.
RULE:
The client SHOULD authenticate using the highest-
level security profile it can handle from the list
provided by the server.
RULE:
The mechanism field MUST contain one of the
security mechanisms proposed by the server in the
Start method. If it doesn't, the server MUST close
the socket.
response: longstr
security response data
A block of opaque data passed to the security
mechanism. The contents of this data are defined by
the SASL security mechanism. For the PLAIN security
mechanism this is defined as a field table holding two
fields, LOGIN and PASSWORD.
locale: shortstr
selected message locale
A single message local selected by the client, which
must be one of those specified by the server. | [
"Select",
"security",
"mechanism",
"and",
"locale"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/connection.py#L758-L820 |
232,351 | nerdvegas/rez | src/rez/vendor/amqp/connection.py | Connection._tune | def _tune(self, args):
"""Propose connection tuning parameters
This method proposes a set of connection configuration values
to the client. The client can accept and/or adjust these.
PARAMETERS:
channel_max: short
proposed maximum channels
The maximum total number of channels that the server
allows per connection. Zero means that the server does
not impose a fixed limit, but the number of allowed
channels may be limited by available server resources.
frame_max: long
proposed maximum frame size
The largest frame size that the server proposes for
the connection. The client can negotiate a lower
value. Zero means that the server does not impose any
specific limit but may reject very large frames if it
cannot allocate resources for them.
RULE:
Until the frame-max has been negotiated, both
peers MUST accept frames of up to 4096 octets
large. The minimum non-zero value for the frame-
max field is 4096.
heartbeat: short
desired heartbeat delay
The delay, in seconds, of the connection heartbeat
that the server wants. Zero means the server does not
want a heartbeat.
"""
client_heartbeat = self.client_heartbeat or 0
self.channel_max = args.read_short() or self.channel_max
self.frame_max = args.read_long() or self.frame_max
self.method_writer.frame_max = self.frame_max
self.server_heartbeat = args.read_short() or 0
# negotiate the heartbeat interval to the smaller of the
# specified values
if self.server_heartbeat == 0 or client_heartbeat == 0:
self.heartbeat = max(self.server_heartbeat, client_heartbeat)
else:
self.heartbeat = min(self.server_heartbeat, client_heartbeat)
# Ignore server heartbeat if client_heartbeat is disabled
if not self.client_heartbeat:
self.heartbeat = 0
self._x_tune_ok(self.channel_max, self.frame_max, self.heartbeat) | python | def _tune(self, args):
"""Propose connection tuning parameters
This method proposes a set of connection configuration values
to the client. The client can accept and/or adjust these.
PARAMETERS:
channel_max: short
proposed maximum channels
The maximum total number of channels that the server
allows per connection. Zero means that the server does
not impose a fixed limit, but the number of allowed
channels may be limited by available server resources.
frame_max: long
proposed maximum frame size
The largest frame size that the server proposes for
the connection. The client can negotiate a lower
value. Zero means that the server does not impose any
specific limit but may reject very large frames if it
cannot allocate resources for them.
RULE:
Until the frame-max has been negotiated, both
peers MUST accept frames of up to 4096 octets
large. The minimum non-zero value for the frame-
max field is 4096.
heartbeat: short
desired heartbeat delay
The delay, in seconds, of the connection heartbeat
that the server wants. Zero means the server does not
want a heartbeat.
"""
client_heartbeat = self.client_heartbeat or 0
self.channel_max = args.read_short() or self.channel_max
self.frame_max = args.read_long() or self.frame_max
self.method_writer.frame_max = self.frame_max
self.server_heartbeat = args.read_short() or 0
# negotiate the heartbeat interval to the smaller of the
# specified values
if self.server_heartbeat == 0 or client_heartbeat == 0:
self.heartbeat = max(self.server_heartbeat, client_heartbeat)
else:
self.heartbeat = min(self.server_heartbeat, client_heartbeat)
# Ignore server heartbeat if client_heartbeat is disabled
if not self.client_heartbeat:
self.heartbeat = 0
self._x_tune_ok(self.channel_max, self.frame_max, self.heartbeat) | [
"def",
"_tune",
"(",
"self",
",",
"args",
")",
":",
"client_heartbeat",
"=",
"self",
".",
"client_heartbeat",
"or",
"0",
"self",
".",
"channel_max",
"=",
"args",
".",
"read_short",
"(",
")",
"or",
"self",
".",
"channel_max",
"self",
".",
"frame_max",
"=",
"args",
".",
"read_long",
"(",
")",
"or",
"self",
".",
"frame_max",
"self",
".",
"method_writer",
".",
"frame_max",
"=",
"self",
".",
"frame_max",
"self",
".",
"server_heartbeat",
"=",
"args",
".",
"read_short",
"(",
")",
"or",
"0",
"# negotiate the heartbeat interval to the smaller of the",
"# specified values",
"if",
"self",
".",
"server_heartbeat",
"==",
"0",
"or",
"client_heartbeat",
"==",
"0",
":",
"self",
".",
"heartbeat",
"=",
"max",
"(",
"self",
".",
"server_heartbeat",
",",
"client_heartbeat",
")",
"else",
":",
"self",
".",
"heartbeat",
"=",
"min",
"(",
"self",
".",
"server_heartbeat",
",",
"client_heartbeat",
")",
"# Ignore server heartbeat if client_heartbeat is disabled",
"if",
"not",
"self",
".",
"client_heartbeat",
":",
"self",
".",
"heartbeat",
"=",
"0",
"self",
".",
"_x_tune_ok",
"(",
"self",
".",
"channel_max",
",",
"self",
".",
"frame_max",
",",
"self",
".",
"heartbeat",
")"
] | Propose connection tuning parameters
This method proposes a set of connection configuration values
to the client. The client can accept and/or adjust these.
PARAMETERS:
channel_max: short
proposed maximum channels
The maximum total number of channels that the server
allows per connection. Zero means that the server does
not impose a fixed limit, but the number of allowed
channels may be limited by available server resources.
frame_max: long
proposed maximum frame size
The largest frame size that the server proposes for
the connection. The client can negotiate a lower
value. Zero means that the server does not impose any
specific limit but may reject very large frames if it
cannot allocate resources for them.
RULE:
Until the frame-max has been negotiated, both
peers MUST accept frames of up to 4096 octets
large. The minimum non-zero value for the frame-
max field is 4096.
heartbeat: short
desired heartbeat delay
The delay, in seconds, of the connection heartbeat
that the server wants. Zero means the server does not
want a heartbeat. | [
"Propose",
"connection",
"tuning",
"parameters"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/connection.py#L822-L881 |
232,352 | nerdvegas/rez | src/rez/vendor/amqp/connection.py | Connection.heartbeat_tick | def heartbeat_tick(self, rate=2):
"""Send heartbeat packets, if necessary, and fail if none have been
received recently. This should be called frequently, on the order of
once per second.
:keyword rate: Ignored
"""
if not self.heartbeat:
return
# treat actual data exchange in either direction as a heartbeat
sent_now = self.method_writer.bytes_sent
recv_now = self.method_reader.bytes_recv
if self.prev_sent is None or self.prev_sent != sent_now:
self.last_heartbeat_sent = monotonic()
if self.prev_recv is None or self.prev_recv != recv_now:
self.last_heartbeat_received = monotonic()
self.prev_sent, self.prev_recv = sent_now, recv_now
# send a heartbeat if it's time to do so
if monotonic() > self.last_heartbeat_sent + self.heartbeat:
self.send_heartbeat()
self.last_heartbeat_sent = monotonic()
# if we've missed two intervals' heartbeats, fail; this gives the
# server enough time to send heartbeats a little late
if (self.last_heartbeat_received and
self.last_heartbeat_received + 2 *
self.heartbeat < monotonic()):
raise ConnectionForced('Too many heartbeats missed') | python | def heartbeat_tick(self, rate=2):
"""Send heartbeat packets, if necessary, and fail if none have been
received recently. This should be called frequently, on the order of
once per second.
:keyword rate: Ignored
"""
if not self.heartbeat:
return
# treat actual data exchange in either direction as a heartbeat
sent_now = self.method_writer.bytes_sent
recv_now = self.method_reader.bytes_recv
if self.prev_sent is None or self.prev_sent != sent_now:
self.last_heartbeat_sent = monotonic()
if self.prev_recv is None or self.prev_recv != recv_now:
self.last_heartbeat_received = monotonic()
self.prev_sent, self.prev_recv = sent_now, recv_now
# send a heartbeat if it's time to do so
if monotonic() > self.last_heartbeat_sent + self.heartbeat:
self.send_heartbeat()
self.last_heartbeat_sent = monotonic()
# if we've missed two intervals' heartbeats, fail; this gives the
# server enough time to send heartbeats a little late
if (self.last_heartbeat_received and
self.last_heartbeat_received + 2 *
self.heartbeat < monotonic()):
raise ConnectionForced('Too many heartbeats missed') | [
"def",
"heartbeat_tick",
"(",
"self",
",",
"rate",
"=",
"2",
")",
":",
"if",
"not",
"self",
".",
"heartbeat",
":",
"return",
"# treat actual data exchange in either direction as a heartbeat",
"sent_now",
"=",
"self",
".",
"method_writer",
".",
"bytes_sent",
"recv_now",
"=",
"self",
".",
"method_reader",
".",
"bytes_recv",
"if",
"self",
".",
"prev_sent",
"is",
"None",
"or",
"self",
".",
"prev_sent",
"!=",
"sent_now",
":",
"self",
".",
"last_heartbeat_sent",
"=",
"monotonic",
"(",
")",
"if",
"self",
".",
"prev_recv",
"is",
"None",
"or",
"self",
".",
"prev_recv",
"!=",
"recv_now",
":",
"self",
".",
"last_heartbeat_received",
"=",
"monotonic",
"(",
")",
"self",
".",
"prev_sent",
",",
"self",
".",
"prev_recv",
"=",
"sent_now",
",",
"recv_now",
"# send a heartbeat if it's time to do so",
"if",
"monotonic",
"(",
")",
">",
"self",
".",
"last_heartbeat_sent",
"+",
"self",
".",
"heartbeat",
":",
"self",
".",
"send_heartbeat",
"(",
")",
"self",
".",
"last_heartbeat_sent",
"=",
"monotonic",
"(",
")",
"# if we've missed two intervals' heartbeats, fail; this gives the",
"# server enough time to send heartbeats a little late",
"if",
"(",
"self",
".",
"last_heartbeat_received",
"and",
"self",
".",
"last_heartbeat_received",
"+",
"2",
"*",
"self",
".",
"heartbeat",
"<",
"monotonic",
"(",
")",
")",
":",
"raise",
"ConnectionForced",
"(",
"'Too many heartbeats missed'",
")"
] | Send heartbeat packets, if necessary, and fail if none have been
received recently. This should be called frequently, on the order of
once per second.
:keyword rate: Ignored | [
"Send",
"heartbeat",
"packets",
"if",
"necessary",
"and",
"fail",
"if",
"none",
"have",
"been",
"received",
"recently",
".",
"This",
"should",
"be",
"called",
"frequently",
"on",
"the",
"order",
"of",
"once",
"per",
"second",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/connection.py#L886-L915 |
232,353 | nerdvegas/rez | src/rez/vendor/amqp/connection.py | Connection._x_tune_ok | def _x_tune_ok(self, channel_max, frame_max, heartbeat):
"""Negotiate connection tuning parameters
This method sends the client's connection tuning parameters to
the server. Certain fields are negotiated, others provide
capability information.
PARAMETERS:
channel_max: short
negotiated maximum channels
The maximum total number of channels that the client
will use per connection. May not be higher than the
value specified by the server.
RULE:
The server MAY ignore the channel-max value or MAY
use it for tuning its resource allocation.
frame_max: long
negotiated maximum frame size
The largest frame size that the client and server will
use for the connection. Zero means that the client
does not impose any specific limit but may reject very
large frames if it cannot allocate resources for them.
Note that the frame-max limit applies principally to
content frames, where large contents can be broken
into frames of arbitrary size.
RULE:
Until the frame-max has been negotiated, both
peers must accept frames of up to 4096 octets
large. The minimum non-zero value for the frame-
max field is 4096.
heartbeat: short
desired heartbeat delay
The delay, in seconds, of the connection heartbeat
that the client wants. Zero means the client does not
want a heartbeat.
"""
args = AMQPWriter()
args.write_short(channel_max)
args.write_long(frame_max)
args.write_short(heartbeat or 0)
self._send_method((10, 31), args)
self._wait_tune_ok = False | python | def _x_tune_ok(self, channel_max, frame_max, heartbeat):
"""Negotiate connection tuning parameters
This method sends the client's connection tuning parameters to
the server. Certain fields are negotiated, others provide
capability information.
PARAMETERS:
channel_max: short
negotiated maximum channels
The maximum total number of channels that the client
will use per connection. May not be higher than the
value specified by the server.
RULE:
The server MAY ignore the channel-max value or MAY
use it for tuning its resource allocation.
frame_max: long
negotiated maximum frame size
The largest frame size that the client and server will
use for the connection. Zero means that the client
does not impose any specific limit but may reject very
large frames if it cannot allocate resources for them.
Note that the frame-max limit applies principally to
content frames, where large contents can be broken
into frames of arbitrary size.
RULE:
Until the frame-max has been negotiated, both
peers must accept frames of up to 4096 octets
large. The minimum non-zero value for the frame-
max field is 4096.
heartbeat: short
desired heartbeat delay
The delay, in seconds, of the connection heartbeat
that the client wants. Zero means the client does not
want a heartbeat.
"""
args = AMQPWriter()
args.write_short(channel_max)
args.write_long(frame_max)
args.write_short(heartbeat or 0)
self._send_method((10, 31), args)
self._wait_tune_ok = False | [
"def",
"_x_tune_ok",
"(",
"self",
",",
"channel_max",
",",
"frame_max",
",",
"heartbeat",
")",
":",
"args",
"=",
"AMQPWriter",
"(",
")",
"args",
".",
"write_short",
"(",
"channel_max",
")",
"args",
".",
"write_long",
"(",
"frame_max",
")",
"args",
".",
"write_short",
"(",
"heartbeat",
"or",
"0",
")",
"self",
".",
"_send_method",
"(",
"(",
"10",
",",
"31",
")",
",",
"args",
")",
"self",
".",
"_wait_tune_ok",
"=",
"False"
] | Negotiate connection tuning parameters
This method sends the client's connection tuning parameters to
the server. Certain fields are negotiated, others provide
capability information.
PARAMETERS:
channel_max: short
negotiated maximum channels
The maximum total number of channels that the client
will use per connection. May not be higher than the
value specified by the server.
RULE:
The server MAY ignore the channel-max value or MAY
use it for tuning its resource allocation.
frame_max: long
negotiated maximum frame size
The largest frame size that the client and server will
use for the connection. Zero means that the client
does not impose any specific limit but may reject very
large frames if it cannot allocate resources for them.
Note that the frame-max limit applies principally to
content frames, where large contents can be broken
into frames of arbitrary size.
RULE:
Until the frame-max has been negotiated, both
peers must accept frames of up to 4096 octets
large. The minimum non-zero value for the frame-
max field is 4096.
heartbeat: short
desired heartbeat delay
The delay, in seconds, of the connection heartbeat
that the client wants. Zero means the client does not
want a heartbeat. | [
"Negotiate",
"connection",
"tuning",
"parameters"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/connection.py#L917-L971 |
232,354 | nerdvegas/rez | src/rez/status.py | Status.parent_suite | def parent_suite(self):
"""Get the current parent suite.
A parent suite exists when a context within a suite is active. That is,
during execution of a tool within a suite, or after a user has entered
an interactive shell in a suite context, for example via the command-
line syntax 'tool +i', where 'tool' is an alias in a suite.
Returns:
`Suite` object, or None if there is no current parent suite.
"""
if self.context and self.context.parent_suite_path:
return Suite.load(self.context.parent_suite_path)
return None | python | def parent_suite(self):
"""Get the current parent suite.
A parent suite exists when a context within a suite is active. That is,
during execution of a tool within a suite, or after a user has entered
an interactive shell in a suite context, for example via the command-
line syntax 'tool +i', where 'tool' is an alias in a suite.
Returns:
`Suite` object, or None if there is no current parent suite.
"""
if self.context and self.context.parent_suite_path:
return Suite.load(self.context.parent_suite_path)
return None | [
"def",
"parent_suite",
"(",
"self",
")",
":",
"if",
"self",
".",
"context",
"and",
"self",
".",
"context",
".",
"parent_suite_path",
":",
"return",
"Suite",
".",
"load",
"(",
"self",
".",
"context",
".",
"parent_suite_path",
")",
"return",
"None"
] | Get the current parent suite.
A parent suite exists when a context within a suite is active. That is,
during execution of a tool within a suite, or after a user has entered
an interactive shell in a suite context, for example via the command-
line syntax 'tool +i', where 'tool' is an alias in a suite.
Returns:
`Suite` object, or None if there is no current parent suite. | [
"Get",
"the",
"current",
"parent",
"suite",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/status.py#L56-L69 |
232,355 | nerdvegas/rez | src/rez/status.py | Status.print_info | def print_info(self, obj=None, buf=sys.stdout):
"""Print a status message about the given object.
If an object is not provided, status info is shown about the current
environment - what the active context is if any, and what suites are
visible.
Args:
obj (str): String which may be one of the following:
- A tool name;
- A package name, possibly versioned;
- A context filepath;
- A suite filepath;
- The name of a context in a visible suite.
"""
if not obj:
self._print_info(buf)
return True
b = False
for fn in (self._print_tool_info,
self._print_package_info,
self._print_suite_info,
self._print_context_info):
b_ = fn(obj, buf, b)
b |= b_
if b_:
print >> buf, ''
if not b:
print >> buf, "Rez does not know what '%s' is" % obj
return b | python | def print_info(self, obj=None, buf=sys.stdout):
"""Print a status message about the given object.
If an object is not provided, status info is shown about the current
environment - what the active context is if any, and what suites are
visible.
Args:
obj (str): String which may be one of the following:
- A tool name;
- A package name, possibly versioned;
- A context filepath;
- A suite filepath;
- The name of a context in a visible suite.
"""
if not obj:
self._print_info(buf)
return True
b = False
for fn in (self._print_tool_info,
self._print_package_info,
self._print_suite_info,
self._print_context_info):
b_ = fn(obj, buf, b)
b |= b_
if b_:
print >> buf, ''
if not b:
print >> buf, "Rez does not know what '%s' is" % obj
return b | [
"def",
"print_info",
"(",
"self",
",",
"obj",
"=",
"None",
",",
"buf",
"=",
"sys",
".",
"stdout",
")",
":",
"if",
"not",
"obj",
":",
"self",
".",
"_print_info",
"(",
"buf",
")",
"return",
"True",
"b",
"=",
"False",
"for",
"fn",
"in",
"(",
"self",
".",
"_print_tool_info",
",",
"self",
".",
"_print_package_info",
",",
"self",
".",
"_print_suite_info",
",",
"self",
".",
"_print_context_info",
")",
":",
"b_",
"=",
"fn",
"(",
"obj",
",",
"buf",
",",
"b",
")",
"b",
"|=",
"b_",
"if",
"b_",
":",
"print",
">>",
"buf",
",",
"''",
"if",
"not",
"b",
":",
"print",
">>",
"buf",
",",
"\"Rez does not know what '%s' is\"",
"%",
"obj",
"return",
"b"
] | Print a status message about the given object.
If an object is not provided, status info is shown about the current
environment - what the active context is if any, and what suites are
visible.
Args:
obj (str): String which may be one of the following:
- A tool name;
- A package name, possibly versioned;
- A context filepath;
- A suite filepath;
- The name of a context in a visible suite. | [
"Print",
"a",
"status",
"message",
"about",
"the",
"given",
"object",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/status.py#L87-L118 |
232,356 | nerdvegas/rez | src/rez/status.py | Status.print_tools | def print_tools(self, pattern=None, buf=sys.stdout):
"""Print a list of visible tools.
Args:
pattern (str): Only list tools that match this glob pattern.
"""
seen = set()
rows = []
context = self.context
if context:
data = context.get_tools()
conflicts = set(context.get_conflicting_tools().keys())
for _, (variant, tools) in sorted(data.items()):
pkg_str = variant.qualified_package_name
for tool in tools:
if pattern and not fnmatch(tool, pattern):
continue
if tool in conflicts:
label = "(in conflict)"
color = critical
else:
label = ''
color = None
rows.append([tool, '-', pkg_str, "active context", label, color])
seen.add(tool)
for suite in self.suites:
for tool, d in suite.get_tools().iteritems():
if tool in seen:
continue
if pattern and not fnmatch(tool, pattern):
continue
label = []
color = None
path = which(tool)
if path:
path_ = os.path.join(suite.tools_path, tool)
if path != path_:
label.append("(hidden by unknown tool '%s')" % path)
color = warning
variant = d["variant"]
if isinstance(variant, set):
pkg_str = ", ".join(variant)
label.append("(in conflict)")
color = critical
else:
pkg_str = variant.qualified_package_name
orig_tool = d["tool_name"]
if orig_tool == tool:
orig_tool = '-'
label = ' '.join(label)
source = ("context '%s' in suite '%s'"
% (d["context_name"], suite.load_path))
rows.append([tool, orig_tool, pkg_str, source, label, color])
seen.add(tool)
_pr = Printer(buf)
if not rows:
_pr("No matching tools.")
return False
headers = [["TOOL", "ALIASING", "PACKAGE", "SOURCE", "", None],
["----", "--------", "-------", "------", "", None]]
rows = headers + sorted(rows, key=lambda x: x[0].lower())
print_colored_columns(_pr, rows)
return True | python | def print_tools(self, pattern=None, buf=sys.stdout):
"""Print a list of visible tools.
Args:
pattern (str): Only list tools that match this glob pattern.
"""
seen = set()
rows = []
context = self.context
if context:
data = context.get_tools()
conflicts = set(context.get_conflicting_tools().keys())
for _, (variant, tools) in sorted(data.items()):
pkg_str = variant.qualified_package_name
for tool in tools:
if pattern and not fnmatch(tool, pattern):
continue
if tool in conflicts:
label = "(in conflict)"
color = critical
else:
label = ''
color = None
rows.append([tool, '-', pkg_str, "active context", label, color])
seen.add(tool)
for suite in self.suites:
for tool, d in suite.get_tools().iteritems():
if tool in seen:
continue
if pattern and not fnmatch(tool, pattern):
continue
label = []
color = None
path = which(tool)
if path:
path_ = os.path.join(suite.tools_path, tool)
if path != path_:
label.append("(hidden by unknown tool '%s')" % path)
color = warning
variant = d["variant"]
if isinstance(variant, set):
pkg_str = ", ".join(variant)
label.append("(in conflict)")
color = critical
else:
pkg_str = variant.qualified_package_name
orig_tool = d["tool_name"]
if orig_tool == tool:
orig_tool = '-'
label = ' '.join(label)
source = ("context '%s' in suite '%s'"
% (d["context_name"], suite.load_path))
rows.append([tool, orig_tool, pkg_str, source, label, color])
seen.add(tool)
_pr = Printer(buf)
if not rows:
_pr("No matching tools.")
return False
headers = [["TOOL", "ALIASING", "PACKAGE", "SOURCE", "", None],
["----", "--------", "-------", "------", "", None]]
rows = headers + sorted(rows, key=lambda x: x[0].lower())
print_colored_columns(_pr, rows)
return True | [
"def",
"print_tools",
"(",
"self",
",",
"pattern",
"=",
"None",
",",
"buf",
"=",
"sys",
".",
"stdout",
")",
":",
"seen",
"=",
"set",
"(",
")",
"rows",
"=",
"[",
"]",
"context",
"=",
"self",
".",
"context",
"if",
"context",
":",
"data",
"=",
"context",
".",
"get_tools",
"(",
")",
"conflicts",
"=",
"set",
"(",
"context",
".",
"get_conflicting_tools",
"(",
")",
".",
"keys",
"(",
")",
")",
"for",
"_",
",",
"(",
"variant",
",",
"tools",
")",
"in",
"sorted",
"(",
"data",
".",
"items",
"(",
")",
")",
":",
"pkg_str",
"=",
"variant",
".",
"qualified_package_name",
"for",
"tool",
"in",
"tools",
":",
"if",
"pattern",
"and",
"not",
"fnmatch",
"(",
"tool",
",",
"pattern",
")",
":",
"continue",
"if",
"tool",
"in",
"conflicts",
":",
"label",
"=",
"\"(in conflict)\"",
"color",
"=",
"critical",
"else",
":",
"label",
"=",
"''",
"color",
"=",
"None",
"rows",
".",
"append",
"(",
"[",
"tool",
",",
"'-'",
",",
"pkg_str",
",",
"\"active context\"",
",",
"label",
",",
"color",
"]",
")",
"seen",
".",
"add",
"(",
"tool",
")",
"for",
"suite",
"in",
"self",
".",
"suites",
":",
"for",
"tool",
",",
"d",
"in",
"suite",
".",
"get_tools",
"(",
")",
".",
"iteritems",
"(",
")",
":",
"if",
"tool",
"in",
"seen",
":",
"continue",
"if",
"pattern",
"and",
"not",
"fnmatch",
"(",
"tool",
",",
"pattern",
")",
":",
"continue",
"label",
"=",
"[",
"]",
"color",
"=",
"None",
"path",
"=",
"which",
"(",
"tool",
")",
"if",
"path",
":",
"path_",
"=",
"os",
".",
"path",
".",
"join",
"(",
"suite",
".",
"tools_path",
",",
"tool",
")",
"if",
"path",
"!=",
"path_",
":",
"label",
".",
"append",
"(",
"\"(hidden by unknown tool '%s')\"",
"%",
"path",
")",
"color",
"=",
"warning",
"variant",
"=",
"d",
"[",
"\"variant\"",
"]",
"if",
"isinstance",
"(",
"variant",
",",
"set",
")",
":",
"pkg_str",
"=",
"\", \"",
".",
"join",
"(",
"variant",
")",
"label",
".",
"append",
"(",
"\"(in conflict)\"",
")",
"color",
"=",
"critical",
"else",
":",
"pkg_str",
"=",
"variant",
".",
"qualified_package_name",
"orig_tool",
"=",
"d",
"[",
"\"tool_name\"",
"]",
"if",
"orig_tool",
"==",
"tool",
":",
"orig_tool",
"=",
"'-'",
"label",
"=",
"' '",
".",
"join",
"(",
"label",
")",
"source",
"=",
"(",
"\"context '%s' in suite '%s'\"",
"%",
"(",
"d",
"[",
"\"context_name\"",
"]",
",",
"suite",
".",
"load_path",
")",
")",
"rows",
".",
"append",
"(",
"[",
"tool",
",",
"orig_tool",
",",
"pkg_str",
",",
"source",
",",
"label",
",",
"color",
"]",
")",
"seen",
".",
"add",
"(",
"tool",
")",
"_pr",
"=",
"Printer",
"(",
"buf",
")",
"if",
"not",
"rows",
":",
"_pr",
"(",
"\"No matching tools.\"",
")",
"return",
"False",
"headers",
"=",
"[",
"[",
"\"TOOL\"",
",",
"\"ALIASING\"",
",",
"\"PACKAGE\"",
",",
"\"SOURCE\"",
",",
"\"\"",
",",
"None",
"]",
",",
"[",
"\"----\"",
",",
"\"--------\"",
",",
"\"-------\"",
",",
"\"------\"",
",",
"\"\"",
",",
"None",
"]",
"]",
"rows",
"=",
"headers",
"+",
"sorted",
"(",
"rows",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
".",
"lower",
"(",
")",
")",
"print_colored_columns",
"(",
"_pr",
",",
"rows",
")",
"return",
"True"
] | Print a list of visible tools.
Args:
pattern (str): Only list tools that match this glob pattern. | [
"Print",
"a",
"list",
"of",
"visible",
"tools",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/status.py#L120-L193 |
232,357 | nerdvegas/rez | src/rez/developer_package.py | DeveloperPackage.from_path | def from_path(cls, path, format=None):
"""Load a developer package.
A developer package may for example be a package.yaml or package.py in a
user's source directory.
Args:
path: Directory containing the package definition file, or file
path for the package file itself
format: which FileFormat to use, or None to check both .py and .yaml
Returns:
`Package` object.
"""
name = None
data = None
if format is None:
formats = (FileFormat.py, FileFormat.yaml)
else:
formats = (format,)
try:
mode = os.stat(path).st_mode
except (IOError, OSError):
raise PackageMetadataError(
"Path %r did not exist, or was not accessible" % path)
is_dir = stat.S_ISDIR(mode)
for name_ in config.plugins.package_repository.filesystem.package_filenames:
for format_ in formats:
if is_dir:
filepath = os.path.join(path, "%s.%s" % (name_,
format_.extension))
exists = os.path.isfile(filepath)
else:
# if format was not specified, verify that it has the
# right extension before trying to load
if format is None:
if os.path.splitext(path)[1] != format_.extension:
continue
filepath = path
exists = True
if exists:
data = load_from_file(filepath, format_, disable_memcache=True)
break
if data:
name = data.get("name")
if name is not None or isinstance(name, basestring):
break
if data is None:
raise PackageMetadataError("No package definition file found at %s" % path)
if name is None or not isinstance(name, basestring):
raise PackageMetadataError(
"Error in %r - missing or non-string field 'name'" % filepath)
package = create_package(name, data, package_cls=cls)
# preprocessing
result = package._get_preprocessed(data)
if result:
package, data = result
package.filepath = filepath
# find all includes, this is needed at install time to copy the right
# py sourcefiles into the package installation
package.includes = set()
def visit(d):
for k, v in d.iteritems():
if isinstance(v, SourceCode):
package.includes |= (v.includes or set())
elif isinstance(v, dict):
visit(v)
visit(data)
package._validate_includes()
return package | python | def from_path(cls, path, format=None):
"""Load a developer package.
A developer package may for example be a package.yaml or package.py in a
user's source directory.
Args:
path: Directory containing the package definition file, or file
path for the package file itself
format: which FileFormat to use, or None to check both .py and .yaml
Returns:
`Package` object.
"""
name = None
data = None
if format is None:
formats = (FileFormat.py, FileFormat.yaml)
else:
formats = (format,)
try:
mode = os.stat(path).st_mode
except (IOError, OSError):
raise PackageMetadataError(
"Path %r did not exist, or was not accessible" % path)
is_dir = stat.S_ISDIR(mode)
for name_ in config.plugins.package_repository.filesystem.package_filenames:
for format_ in formats:
if is_dir:
filepath = os.path.join(path, "%s.%s" % (name_,
format_.extension))
exists = os.path.isfile(filepath)
else:
# if format was not specified, verify that it has the
# right extension before trying to load
if format is None:
if os.path.splitext(path)[1] != format_.extension:
continue
filepath = path
exists = True
if exists:
data = load_from_file(filepath, format_, disable_memcache=True)
break
if data:
name = data.get("name")
if name is not None or isinstance(name, basestring):
break
if data is None:
raise PackageMetadataError("No package definition file found at %s" % path)
if name is None or not isinstance(name, basestring):
raise PackageMetadataError(
"Error in %r - missing or non-string field 'name'" % filepath)
package = create_package(name, data, package_cls=cls)
# preprocessing
result = package._get_preprocessed(data)
if result:
package, data = result
package.filepath = filepath
# find all includes, this is needed at install time to copy the right
# py sourcefiles into the package installation
package.includes = set()
def visit(d):
for k, v in d.iteritems():
if isinstance(v, SourceCode):
package.includes |= (v.includes or set())
elif isinstance(v, dict):
visit(v)
visit(data)
package._validate_includes()
return package | [
"def",
"from_path",
"(",
"cls",
",",
"path",
",",
"format",
"=",
"None",
")",
":",
"name",
"=",
"None",
"data",
"=",
"None",
"if",
"format",
"is",
"None",
":",
"formats",
"=",
"(",
"FileFormat",
".",
"py",
",",
"FileFormat",
".",
"yaml",
")",
"else",
":",
"formats",
"=",
"(",
"format",
",",
")",
"try",
":",
"mode",
"=",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_mode",
"except",
"(",
"IOError",
",",
"OSError",
")",
":",
"raise",
"PackageMetadataError",
"(",
"\"Path %r did not exist, or was not accessible\"",
"%",
"path",
")",
"is_dir",
"=",
"stat",
".",
"S_ISDIR",
"(",
"mode",
")",
"for",
"name_",
"in",
"config",
".",
"plugins",
".",
"package_repository",
".",
"filesystem",
".",
"package_filenames",
":",
"for",
"format_",
"in",
"formats",
":",
"if",
"is_dir",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"%s.%s\"",
"%",
"(",
"name_",
",",
"format_",
".",
"extension",
")",
")",
"exists",
"=",
"os",
".",
"path",
".",
"isfile",
"(",
"filepath",
")",
"else",
":",
"# if format was not specified, verify that it has the",
"# right extension before trying to load",
"if",
"format",
"is",
"None",
":",
"if",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"[",
"1",
"]",
"!=",
"format_",
".",
"extension",
":",
"continue",
"filepath",
"=",
"path",
"exists",
"=",
"True",
"if",
"exists",
":",
"data",
"=",
"load_from_file",
"(",
"filepath",
",",
"format_",
",",
"disable_memcache",
"=",
"True",
")",
"break",
"if",
"data",
":",
"name",
"=",
"data",
".",
"get",
"(",
"\"name\"",
")",
"if",
"name",
"is",
"not",
"None",
"or",
"isinstance",
"(",
"name",
",",
"basestring",
")",
":",
"break",
"if",
"data",
"is",
"None",
":",
"raise",
"PackageMetadataError",
"(",
"\"No package definition file found at %s\"",
"%",
"path",
")",
"if",
"name",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"name",
",",
"basestring",
")",
":",
"raise",
"PackageMetadataError",
"(",
"\"Error in %r - missing or non-string field 'name'\"",
"%",
"filepath",
")",
"package",
"=",
"create_package",
"(",
"name",
",",
"data",
",",
"package_cls",
"=",
"cls",
")",
"# preprocessing",
"result",
"=",
"package",
".",
"_get_preprocessed",
"(",
"data",
")",
"if",
"result",
":",
"package",
",",
"data",
"=",
"result",
"package",
".",
"filepath",
"=",
"filepath",
"# find all includes, this is needed at install time to copy the right",
"# py sourcefiles into the package installation",
"package",
".",
"includes",
"=",
"set",
"(",
")",
"def",
"visit",
"(",
"d",
")",
":",
"for",
"k",
",",
"v",
"in",
"d",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"SourceCode",
")",
":",
"package",
".",
"includes",
"|=",
"(",
"v",
".",
"includes",
"or",
"set",
"(",
")",
")",
"elif",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"visit",
"(",
"v",
")",
"visit",
"(",
"data",
")",
"package",
".",
"_validate_includes",
"(",
")",
"return",
"package"
] | Load a developer package.
A developer package may for example be a package.yaml or package.py in a
user's source directory.
Args:
path: Directory containing the package definition file, or file
path for the package file itself
format: which FileFormat to use, or None to check both .py and .yaml
Returns:
`Package` object. | [
"Load",
"a",
"developer",
"package",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/developer_package.py#L35-L119 |
232,358 | nerdvegas/rez | src/rez/vendor/yaml/__init__.py | dump_all | def dump_all(documents, stream=None, Dumper=Dumper,
default_style=None, default_flow_style=None,
canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None,
encoding='utf-8', explicit_start=None, explicit_end=None,
version=None, tags=None):
"""
Serialize a sequence of Python objects into a YAML stream.
If stream is None, return the produced string instead.
"""
getvalue = None
if stream is None:
if encoding is None:
from StringIO import StringIO
else:
from cStringIO import StringIO
stream = StringIO()
getvalue = stream.getvalue
dumper = Dumper(stream, default_style=default_style,
default_flow_style=default_flow_style,
canonical=canonical, indent=indent, width=width,
allow_unicode=allow_unicode, line_break=line_break,
encoding=encoding, version=version, tags=tags,
explicit_start=explicit_start, explicit_end=explicit_end)
try:
dumper.open()
for data in documents:
dumper.represent(data)
dumper.close()
finally:
dumper.dispose()
if getvalue:
return getvalue() | python | def dump_all(documents, stream=None, Dumper=Dumper,
default_style=None, default_flow_style=None,
canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None,
encoding='utf-8', explicit_start=None, explicit_end=None,
version=None, tags=None):
"""
Serialize a sequence of Python objects into a YAML stream.
If stream is None, return the produced string instead.
"""
getvalue = None
if stream is None:
if encoding is None:
from StringIO import StringIO
else:
from cStringIO import StringIO
stream = StringIO()
getvalue = stream.getvalue
dumper = Dumper(stream, default_style=default_style,
default_flow_style=default_flow_style,
canonical=canonical, indent=indent, width=width,
allow_unicode=allow_unicode, line_break=line_break,
encoding=encoding, version=version, tags=tags,
explicit_start=explicit_start, explicit_end=explicit_end)
try:
dumper.open()
for data in documents:
dumper.represent(data)
dumper.close()
finally:
dumper.dispose()
if getvalue:
return getvalue() | [
"def",
"dump_all",
"(",
"documents",
",",
"stream",
"=",
"None",
",",
"Dumper",
"=",
"Dumper",
",",
"default_style",
"=",
"None",
",",
"default_flow_style",
"=",
"None",
",",
"canonical",
"=",
"None",
",",
"indent",
"=",
"None",
",",
"width",
"=",
"None",
",",
"allow_unicode",
"=",
"None",
",",
"line_break",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
",",
"explicit_start",
"=",
"None",
",",
"explicit_end",
"=",
"None",
",",
"version",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"getvalue",
"=",
"None",
"if",
"stream",
"is",
"None",
":",
"if",
"encoding",
"is",
"None",
":",
"from",
"StringIO",
"import",
"StringIO",
"else",
":",
"from",
"cStringIO",
"import",
"StringIO",
"stream",
"=",
"StringIO",
"(",
")",
"getvalue",
"=",
"stream",
".",
"getvalue",
"dumper",
"=",
"Dumper",
"(",
"stream",
",",
"default_style",
"=",
"default_style",
",",
"default_flow_style",
"=",
"default_flow_style",
",",
"canonical",
"=",
"canonical",
",",
"indent",
"=",
"indent",
",",
"width",
"=",
"width",
",",
"allow_unicode",
"=",
"allow_unicode",
",",
"line_break",
"=",
"line_break",
",",
"encoding",
"=",
"encoding",
",",
"version",
"=",
"version",
",",
"tags",
"=",
"tags",
",",
"explicit_start",
"=",
"explicit_start",
",",
"explicit_end",
"=",
"explicit_end",
")",
"try",
":",
"dumper",
".",
"open",
"(",
")",
"for",
"data",
"in",
"documents",
":",
"dumper",
".",
"represent",
"(",
"data",
")",
"dumper",
".",
"close",
"(",
")",
"finally",
":",
"dumper",
".",
"dispose",
"(",
")",
"if",
"getvalue",
":",
"return",
"getvalue",
"(",
")"
] | Serialize a sequence of Python objects into a YAML stream.
If stream is None, return the produced string instead. | [
"Serialize",
"a",
"sequence",
"of",
"Python",
"objects",
"into",
"a",
"YAML",
"stream",
".",
"If",
"stream",
"is",
"None",
"return",
"the",
"produced",
"string",
"instead",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/yaml/__init__.py#L163-L195 |
232,359 | nerdvegas/rez | src/rezgui/objects/ProcessTrackerThread.py | ProcessTrackerThread.running_instances | def running_instances(self, context, process_name):
"""Get a list of running instances.
Args:
context (`ResolvedContext`): Context the process is running in.
process_name (str): Name of the process.
Returns:
List of (`subprocess.Popen`, start-time) 2-tuples, where start_time
is the epoch time the process was added.
"""
handle = (id(context), process_name)
it = self.processes.get(handle, {}).itervalues()
entries = [x for x in it if x[0].poll() is None]
return entries | python | def running_instances(self, context, process_name):
"""Get a list of running instances.
Args:
context (`ResolvedContext`): Context the process is running in.
process_name (str): Name of the process.
Returns:
List of (`subprocess.Popen`, start-time) 2-tuples, where start_time
is the epoch time the process was added.
"""
handle = (id(context), process_name)
it = self.processes.get(handle, {}).itervalues()
entries = [x for x in it if x[0].poll() is None]
return entries | [
"def",
"running_instances",
"(",
"self",
",",
"context",
",",
"process_name",
")",
":",
"handle",
"=",
"(",
"id",
"(",
"context",
")",
",",
"process_name",
")",
"it",
"=",
"self",
".",
"processes",
".",
"get",
"(",
"handle",
",",
"{",
"}",
")",
".",
"itervalues",
"(",
")",
"entries",
"=",
"[",
"x",
"for",
"x",
"in",
"it",
"if",
"x",
"[",
"0",
"]",
".",
"poll",
"(",
")",
"is",
"None",
"]",
"return",
"entries"
] | Get a list of running instances.
Args:
context (`ResolvedContext`): Context the process is running in.
process_name (str): Name of the process.
Returns:
List of (`subprocess.Popen`, start-time) 2-tuples, where start_time
is the epoch time the process was added. | [
"Get",
"a",
"list",
"of",
"running",
"instances",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/objects/ProcessTrackerThread.py#L24-L38 |
232,360 | nerdvegas/rez | src/rez/rex.py | ActionManager.get_public_methods | def get_public_methods(self):
"""
return a list of methods on this class which should be exposed in the rex
API.
"""
return self.get_action_methods() + [
('getenv', self.getenv),
('expandvars', self.expandvars),
('defined', self.defined),
('undefined', self.undefined)] | python | def get_public_methods(self):
"""
return a list of methods on this class which should be exposed in the rex
API.
"""
return self.get_action_methods() + [
('getenv', self.getenv),
('expandvars', self.expandvars),
('defined', self.defined),
('undefined', self.undefined)] | [
"def",
"get_public_methods",
"(",
"self",
")",
":",
"return",
"self",
".",
"get_action_methods",
"(",
")",
"+",
"[",
"(",
"'getenv'",
",",
"self",
".",
"getenv",
")",
",",
"(",
"'expandvars'",
",",
"self",
".",
"expandvars",
")",
",",
"(",
"'defined'",
",",
"self",
".",
"defined",
")",
",",
"(",
"'undefined'",
",",
"self",
".",
"undefined",
")",
"]"
] | return a list of methods on this class which should be exposed in the rex
API. | [
"return",
"a",
"list",
"of",
"methods",
"on",
"this",
"class",
"which",
"should",
"be",
"exposed",
"in",
"the",
"rex",
"API",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/rex.py#L205-L214 |
232,361 | nerdvegas/rez | src/rez/rex.py | Python.apply_environ | def apply_environ(self):
"""Apply changes to target environ.
"""
if self.manager is None:
raise RezSystemError("You must call 'set_manager' on a Python rex "
"interpreter before using it.")
self.target_environ.update(self.manager.environ) | python | def apply_environ(self):
"""Apply changes to target environ.
"""
if self.manager is None:
raise RezSystemError("You must call 'set_manager' on a Python rex "
"interpreter before using it.")
self.target_environ.update(self.manager.environ) | [
"def",
"apply_environ",
"(",
"self",
")",
":",
"if",
"self",
".",
"manager",
"is",
"None",
":",
"raise",
"RezSystemError",
"(",
"\"You must call 'set_manager' on a Python rex \"",
"\"interpreter before using it.\"",
")",
"self",
".",
"target_environ",
".",
"update",
"(",
"self",
".",
"manager",
".",
"environ",
")"
] | Apply changes to target environ. | [
"Apply",
"changes",
"to",
"target",
"environ",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/rex.py#L564-L571 |
232,362 | nerdvegas/rez | src/rez/rex.py | EscapedString.formatted | def formatted(self, func):
"""Return the string with non-literal parts formatted.
Args:
func (callable): Callable that translates a string into a
formatted string.
Returns:
`EscapedString` object.
"""
other = EscapedString.__new__(EscapedString)
other.strings = []
for is_literal, value in self.strings:
if not is_literal:
value = func(value)
other.strings.append((is_literal, value))
return other | python | def formatted(self, func):
"""Return the string with non-literal parts formatted.
Args:
func (callable): Callable that translates a string into a
formatted string.
Returns:
`EscapedString` object.
"""
other = EscapedString.__new__(EscapedString)
other.strings = []
for is_literal, value in self.strings:
if not is_literal:
value = func(value)
other.strings.append((is_literal, value))
return other | [
"def",
"formatted",
"(",
"self",
",",
"func",
")",
":",
"other",
"=",
"EscapedString",
".",
"__new__",
"(",
"EscapedString",
")",
"other",
".",
"strings",
"=",
"[",
"]",
"for",
"is_literal",
",",
"value",
"in",
"self",
".",
"strings",
":",
"if",
"not",
"is_literal",
":",
"value",
"=",
"func",
"(",
"value",
")",
"other",
".",
"strings",
".",
"append",
"(",
"(",
"is_literal",
",",
"value",
")",
")",
"return",
"other"
] | Return the string with non-literal parts formatted.
Args:
func (callable): Callable that translates a string into a
formatted string.
Returns:
`EscapedString` object. | [
"Return",
"the",
"string",
"with",
"non",
"-",
"literal",
"parts",
"formatted",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/rex.py#L764-L781 |
232,363 | nerdvegas/rez | src/rez/rex.py | RexExecutor.execute_code | def execute_code(self, code, filename=None, isolate=False):
"""Execute code within the execution context.
Args:
code (str or SourceCode): Rex code to execute.
filename (str): Filename to report if there are syntax errors.
isolate (bool): If True, do not affect `self.globals` by executing
this code.
"""
def _apply():
self.compile_code(code=code,
filename=filename,
exec_namespace=self.globals)
# we want to execute the code using self.globals - if for no other
# reason that self.formatter is pointing at self.globals, so if we
# passed in a copy, we would also need to make self.formatter "look" at
# the same copy - but we don't want to "pollute" our namespace, because
# the same executor may be used to run multiple packages. Therefore,
# we save a copy of self.globals before execution, and restore it after
#
if isolate:
saved_globals = dict(self.globals)
try:
_apply()
finally:
self.globals.clear()
self.globals.update(saved_globals)
else:
_apply() | python | def execute_code(self, code, filename=None, isolate=False):
"""Execute code within the execution context.
Args:
code (str or SourceCode): Rex code to execute.
filename (str): Filename to report if there are syntax errors.
isolate (bool): If True, do not affect `self.globals` by executing
this code.
"""
def _apply():
self.compile_code(code=code,
filename=filename,
exec_namespace=self.globals)
# we want to execute the code using self.globals - if for no other
# reason that self.formatter is pointing at self.globals, so if we
# passed in a copy, we would also need to make self.formatter "look" at
# the same copy - but we don't want to "pollute" our namespace, because
# the same executor may be used to run multiple packages. Therefore,
# we save a copy of self.globals before execution, and restore it after
#
if isolate:
saved_globals = dict(self.globals)
try:
_apply()
finally:
self.globals.clear()
self.globals.update(saved_globals)
else:
_apply() | [
"def",
"execute_code",
"(",
"self",
",",
"code",
",",
"filename",
"=",
"None",
",",
"isolate",
"=",
"False",
")",
":",
"def",
"_apply",
"(",
")",
":",
"self",
".",
"compile_code",
"(",
"code",
"=",
"code",
",",
"filename",
"=",
"filename",
",",
"exec_namespace",
"=",
"self",
".",
"globals",
")",
"# we want to execute the code using self.globals - if for no other",
"# reason that self.formatter is pointing at self.globals, so if we",
"# passed in a copy, we would also need to make self.formatter \"look\" at",
"# the same copy - but we don't want to \"pollute\" our namespace, because",
"# the same executor may be used to run multiple packages. Therefore,",
"# we save a copy of self.globals before execution, and restore it after",
"#",
"if",
"isolate",
":",
"saved_globals",
"=",
"dict",
"(",
"self",
".",
"globals",
")",
"try",
":",
"_apply",
"(",
")",
"finally",
":",
"self",
".",
"globals",
".",
"clear",
"(",
")",
"self",
".",
"globals",
".",
"update",
"(",
"saved_globals",
")",
"else",
":",
"_apply",
"(",
")"
] | Execute code within the execution context.
Args:
code (str or SourceCode): Rex code to execute.
filename (str): Filename to report if there are syntax errors.
isolate (bool): If True, do not affect `self.globals` by executing
this code. | [
"Execute",
"code",
"within",
"the",
"execution",
"context",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/rex.py#L1187-L1217 |
232,364 | nerdvegas/rez | src/rez/rex.py | RexExecutor.execute_function | def execute_function(self, func, *nargs, **kwargs):
"""
Execute a function object within the execution context.
@returns The result of the function call.
"""
# makes a copy of the func
import types
fn = types.FunctionType(func.func_code,
func.func_globals.copy(),
name=func.func_name,
argdefs=func.func_defaults,
closure=func.func_closure)
fn.func_globals.update(self.globals)
error_class = Exception if config.catch_rex_errors else None
try:
return fn(*nargs, **kwargs)
except RexError:
raise
except error_class as e:
from inspect import getfile
stack = traceback.format_exc()
filename = getfile(func)
raise RexError("Failed to exec %s:\n\n%s" % (filename, stack)) | python | def execute_function(self, func, *nargs, **kwargs):
"""
Execute a function object within the execution context.
@returns The result of the function call.
"""
# makes a copy of the func
import types
fn = types.FunctionType(func.func_code,
func.func_globals.copy(),
name=func.func_name,
argdefs=func.func_defaults,
closure=func.func_closure)
fn.func_globals.update(self.globals)
error_class = Exception if config.catch_rex_errors else None
try:
return fn(*nargs, **kwargs)
except RexError:
raise
except error_class as e:
from inspect import getfile
stack = traceback.format_exc()
filename = getfile(func)
raise RexError("Failed to exec %s:\n\n%s" % (filename, stack)) | [
"def",
"execute_function",
"(",
"self",
",",
"func",
",",
"*",
"nargs",
",",
"*",
"*",
"kwargs",
")",
":",
"# makes a copy of the func",
"import",
"types",
"fn",
"=",
"types",
".",
"FunctionType",
"(",
"func",
".",
"func_code",
",",
"func",
".",
"func_globals",
".",
"copy",
"(",
")",
",",
"name",
"=",
"func",
".",
"func_name",
",",
"argdefs",
"=",
"func",
".",
"func_defaults",
",",
"closure",
"=",
"func",
".",
"func_closure",
")",
"fn",
".",
"func_globals",
".",
"update",
"(",
"self",
".",
"globals",
")",
"error_class",
"=",
"Exception",
"if",
"config",
".",
"catch_rex_errors",
"else",
"None",
"try",
":",
"return",
"fn",
"(",
"*",
"nargs",
",",
"*",
"*",
"kwargs",
")",
"except",
"RexError",
":",
"raise",
"except",
"error_class",
"as",
"e",
":",
"from",
"inspect",
"import",
"getfile",
"stack",
"=",
"traceback",
".",
"format_exc",
"(",
")",
"filename",
"=",
"getfile",
"(",
"func",
")",
"raise",
"RexError",
"(",
"\"Failed to exec %s:\\n\\n%s\"",
"%",
"(",
"filename",
",",
"stack",
")",
")"
] | Execute a function object within the execution context.
@returns The result of the function call. | [
"Execute",
"a",
"function",
"object",
"within",
"the",
"execution",
"context",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/rex.py#L1219-L1245 |
232,365 | nerdvegas/rez | src/rez/rex.py | RexExecutor.get_output | def get_output(self, style=OutputStyle.file):
"""Returns the result of all previous calls to execute_code."""
return self.manager.get_output(style=style) | python | def get_output(self, style=OutputStyle.file):
"""Returns the result of all previous calls to execute_code."""
return self.manager.get_output(style=style) | [
"def",
"get_output",
"(",
"self",
",",
"style",
"=",
"OutputStyle",
".",
"file",
")",
":",
"return",
"self",
".",
"manager",
".",
"get_output",
"(",
"style",
"=",
"style",
")"
] | Returns the result of all previous calls to execute_code. | [
"Returns",
"the",
"result",
"of",
"all",
"previous",
"calls",
"to",
"execute_code",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/rex.py#L1247-L1249 |
232,366 | nerdvegas/rez | src/rez/vendor/pygraph/algorithms/filters/find.py | find.configure | def configure(self, graph, spanning_tree):
"""
Configure the filter.
@type graph: graph
@param graph: Graph.
@type spanning_tree: dictionary
@param spanning_tree: Spanning tree.
"""
self.graph = graph
self.spanning_tree = spanning_tree | python | def configure(self, graph, spanning_tree):
"""
Configure the filter.
@type graph: graph
@param graph: Graph.
@type spanning_tree: dictionary
@param spanning_tree: Spanning tree.
"""
self.graph = graph
self.spanning_tree = spanning_tree | [
"def",
"configure",
"(",
"self",
",",
"graph",
",",
"spanning_tree",
")",
":",
"self",
".",
"graph",
"=",
"graph",
"self",
".",
"spanning_tree",
"=",
"spanning_tree"
] | Configure the filter.
@type graph: graph
@param graph: Graph.
@type spanning_tree: dictionary
@param spanning_tree: Spanning tree. | [
"Configure",
"the",
"filter",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/filters/find.py#L47-L58 |
232,367 | nerdvegas/rez | src/rez/package_filter.py | PackageFilterBase.iter_packages | def iter_packages(self, name, range_=None, paths=None):
"""Same as iter_packages in packages.py, but also applies this filter.
Args:
name (str): Name of the package, eg 'maya'.
range_ (VersionRange or str): If provided, limits the versions returned
to those in `range_`.
paths (list of str, optional): paths to search for packages, defaults
to `config.packages_path`.
Returns:
`Package` iterator.
"""
for package in iter_packages(name, range_, paths):
if not self.excludes(package):
yield package | python | def iter_packages(self, name, range_=None, paths=None):
"""Same as iter_packages in packages.py, but also applies this filter.
Args:
name (str): Name of the package, eg 'maya'.
range_ (VersionRange or str): If provided, limits the versions returned
to those in `range_`.
paths (list of str, optional): paths to search for packages, defaults
to `config.packages_path`.
Returns:
`Package` iterator.
"""
for package in iter_packages(name, range_, paths):
if not self.excludes(package):
yield package | [
"def",
"iter_packages",
"(",
"self",
",",
"name",
",",
"range_",
"=",
"None",
",",
"paths",
"=",
"None",
")",
":",
"for",
"package",
"in",
"iter_packages",
"(",
"name",
",",
"range_",
",",
"paths",
")",
":",
"if",
"not",
"self",
".",
"excludes",
"(",
"package",
")",
":",
"yield",
"package"
] | Same as iter_packages in packages.py, but also applies this filter.
Args:
name (str): Name of the package, eg 'maya'.
range_ (VersionRange or str): If provided, limits the versions returned
to those in `range_`.
paths (list of str, optional): paths to search for packages, defaults
to `config.packages_path`.
Returns:
`Package` iterator. | [
"Same",
"as",
"iter_packages",
"in",
"packages",
".",
"py",
"but",
"also",
"applies",
"this",
"filter",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_filter.py#L49-L64 |
232,368 | nerdvegas/rez | src/rez/package_filter.py | PackageFilter.copy | def copy(self):
"""Return a shallow copy of the filter.
Adding rules to the copy will not alter the source.
"""
other = PackageFilter.__new__(PackageFilter)
other._excludes = self._excludes.copy()
other._includes = self._includes.copy()
return other | python | def copy(self):
"""Return a shallow copy of the filter.
Adding rules to the copy will not alter the source.
"""
other = PackageFilter.__new__(PackageFilter)
other._excludes = self._excludes.copy()
other._includes = self._includes.copy()
return other | [
"def",
"copy",
"(",
"self",
")",
":",
"other",
"=",
"PackageFilter",
".",
"__new__",
"(",
"PackageFilter",
")",
"other",
".",
"_excludes",
"=",
"self",
".",
"_excludes",
".",
"copy",
"(",
")",
"other",
".",
"_includes",
"=",
"self",
".",
"_includes",
".",
"copy",
"(",
")",
"return",
"other"
] | Return a shallow copy of the filter.
Adding rules to the copy will not alter the source. | [
"Return",
"a",
"shallow",
"copy",
"of",
"the",
"filter",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_filter.py#L126-L134 |
232,369 | nerdvegas/rez | src/rez/package_filter.py | PackageFilter.cost | def cost(self):
"""Get the approximate cost of this filter.
Cost is the total cost of the exclusion rules in this filter. The cost
of family-specific filters is divided by 10.
Returns:
float: The approximate cost of the filter.
"""
total = 0.0
for family, rules in self._excludes.iteritems():
cost = sum(x.cost() for x in rules)
if family:
cost = cost / float(10)
total += cost
return total | python | def cost(self):
"""Get the approximate cost of this filter.
Cost is the total cost of the exclusion rules in this filter. The cost
of family-specific filters is divided by 10.
Returns:
float: The approximate cost of the filter.
"""
total = 0.0
for family, rules in self._excludes.iteritems():
cost = sum(x.cost() for x in rules)
if family:
cost = cost / float(10)
total += cost
return total | [
"def",
"cost",
"(",
"self",
")",
":",
"total",
"=",
"0.0",
"for",
"family",
",",
"rules",
"in",
"self",
".",
"_excludes",
".",
"iteritems",
"(",
")",
":",
"cost",
"=",
"sum",
"(",
"x",
".",
"cost",
"(",
")",
"for",
"x",
"in",
"rules",
")",
"if",
"family",
":",
"cost",
"=",
"cost",
"/",
"float",
"(",
"10",
")",
"total",
"+=",
"cost",
"return",
"total"
] | Get the approximate cost of this filter.
Cost is the total cost of the exclusion rules in this filter. The cost
of family-specific filters is divided by 10.
Returns:
float: The approximate cost of the filter. | [
"Get",
"the",
"approximate",
"cost",
"of",
"this",
"filter",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_filter.py#L149-L164 |
232,370 | nerdvegas/rez | src/rez/package_filter.py | PackageFilterList.add_filter | def add_filter(self, package_filter):
"""Add a filter to the list.
Args:
package_filter (`PackageFilter`): Filter to add.
"""
filters = self.filters + [package_filter]
self.filters = sorted(filters, key=lambda x: x.cost) | python | def add_filter(self, package_filter):
"""Add a filter to the list.
Args:
package_filter (`PackageFilter`): Filter to add.
"""
filters = self.filters + [package_filter]
self.filters = sorted(filters, key=lambda x: x.cost) | [
"def",
"add_filter",
"(",
"self",
",",
"package_filter",
")",
":",
"filters",
"=",
"self",
".",
"filters",
"+",
"[",
"package_filter",
"]",
"self",
".",
"filters",
"=",
"sorted",
"(",
"filters",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"cost",
")"
] | Add a filter to the list.
Args:
package_filter (`PackageFilter`): Filter to add. | [
"Add",
"a",
"filter",
"to",
"the",
"list",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_filter.py#L210-L217 |
232,371 | nerdvegas/rez | src/rez/package_filter.py | PackageFilterList.copy | def copy(self):
"""Return a copy of the filter list.
Adding rules to the copy will not alter the source.
"""
other = PackageFilterList.__new__(PackageFilterList)
other.filters = [x.copy() for x in self.filters]
return other | python | def copy(self):
"""Return a copy of the filter list.
Adding rules to the copy will not alter the source.
"""
other = PackageFilterList.__new__(PackageFilterList)
other.filters = [x.copy() for x in self.filters]
return other | [
"def",
"copy",
"(",
"self",
")",
":",
"other",
"=",
"PackageFilterList",
".",
"__new__",
"(",
"PackageFilterList",
")",
"other",
".",
"filters",
"=",
"[",
"x",
".",
"copy",
"(",
")",
"for",
"x",
"in",
"self",
".",
"filters",
"]",
"return",
"other"
] | Return a copy of the filter list.
Adding rules to the copy will not alter the source. | [
"Return",
"a",
"copy",
"of",
"the",
"filter",
"list",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_filter.py#L244-L251 |
232,372 | nerdvegas/rez | src/rez/package_filter.py | Rule.parse_rule | def parse_rule(cls, txt):
"""Parse a rule from a string.
See rezconfig.package_filter for an overview of valid strings.
Args:
txt (str): String to parse.
Returns:
`Rule` instance.
"""
types = {"glob": GlobRule,
"regex": RegexRule,
"range": RangeRule,
"before": TimestampRule,
"after": TimestampRule}
# parse form 'x(y)' into x, y
label, txt = Rule._parse_label(txt)
if label is None:
if '*' in txt:
label = "glob"
else:
label = "range"
elif label not in types:
raise ConfigurationError(
"'%s' is not a valid package filter type" % label)
rule_cls = types[label]
txt_ = "%s(%s)" % (label, txt)
try:
rule = rule_cls._parse(txt_)
except Exception as e:
raise ConfigurationError("Error parsing package filter '%s': %s: %s"
% (txt_, e.__class__.__name__, str(e)))
return rule | python | def parse_rule(cls, txt):
"""Parse a rule from a string.
See rezconfig.package_filter for an overview of valid strings.
Args:
txt (str): String to parse.
Returns:
`Rule` instance.
"""
types = {"glob": GlobRule,
"regex": RegexRule,
"range": RangeRule,
"before": TimestampRule,
"after": TimestampRule}
# parse form 'x(y)' into x, y
label, txt = Rule._parse_label(txt)
if label is None:
if '*' in txt:
label = "glob"
else:
label = "range"
elif label not in types:
raise ConfigurationError(
"'%s' is not a valid package filter type" % label)
rule_cls = types[label]
txt_ = "%s(%s)" % (label, txt)
try:
rule = rule_cls._parse(txt_)
except Exception as e:
raise ConfigurationError("Error parsing package filter '%s': %s: %s"
% (txt_, e.__class__.__name__, str(e)))
return rule | [
"def",
"parse_rule",
"(",
"cls",
",",
"txt",
")",
":",
"types",
"=",
"{",
"\"glob\"",
":",
"GlobRule",
",",
"\"regex\"",
":",
"RegexRule",
",",
"\"range\"",
":",
"RangeRule",
",",
"\"before\"",
":",
"TimestampRule",
",",
"\"after\"",
":",
"TimestampRule",
"}",
"# parse form 'x(y)' into x, y",
"label",
",",
"txt",
"=",
"Rule",
".",
"_parse_label",
"(",
"txt",
")",
"if",
"label",
"is",
"None",
":",
"if",
"'*'",
"in",
"txt",
":",
"label",
"=",
"\"glob\"",
"else",
":",
"label",
"=",
"\"range\"",
"elif",
"label",
"not",
"in",
"types",
":",
"raise",
"ConfigurationError",
"(",
"\"'%s' is not a valid package filter type\"",
"%",
"label",
")",
"rule_cls",
"=",
"types",
"[",
"label",
"]",
"txt_",
"=",
"\"%s(%s)\"",
"%",
"(",
"label",
",",
"txt",
")",
"try",
":",
"rule",
"=",
"rule_cls",
".",
"_parse",
"(",
"txt_",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"ConfigurationError",
"(",
"\"Error parsing package filter '%s': %s: %s\"",
"%",
"(",
"txt_",
",",
"e",
".",
"__class__",
".",
"__name__",
",",
"str",
"(",
"e",
")",
")",
")",
"return",
"rule"
] | Parse a rule from a string.
See rezconfig.package_filter for an overview of valid strings.
Args:
txt (str): String to parse.
Returns:
`Rule` instance. | [
"Parse",
"a",
"rule",
"from",
"a",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_filter.py#L309-L345 |
232,373 | nerdvegas/rez | src/rez/vendor/amqp/serialization.py | AMQPReader.read_bit | def read_bit(self):
"""Read a single boolean value."""
if not self.bitcount:
self.bits = ord(self.input.read(1))
self.bitcount = 8
result = (self.bits & 1) == 1
self.bits >>= 1
self.bitcount -= 1
return result | python | def read_bit(self):
"""Read a single boolean value."""
if not self.bitcount:
self.bits = ord(self.input.read(1))
self.bitcount = 8
result = (self.bits & 1) == 1
self.bits >>= 1
self.bitcount -= 1
return result | [
"def",
"read_bit",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"bitcount",
":",
"self",
".",
"bits",
"=",
"ord",
"(",
"self",
".",
"input",
".",
"read",
"(",
"1",
")",
")",
"self",
".",
"bitcount",
"=",
"8",
"result",
"=",
"(",
"self",
".",
"bits",
"&",
"1",
")",
"==",
"1",
"self",
".",
"bits",
">>=",
"1",
"self",
".",
"bitcount",
"-=",
"1",
"return",
"result"
] | Read a single boolean value. | [
"Read",
"a",
"single",
"boolean",
"value",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/serialization.py#L76-L84 |
232,374 | nerdvegas/rez | src/rez/vendor/amqp/serialization.py | AMQPReader.read_long | def read_long(self):
"""Read an unsigned 32-bit integer"""
self.bitcount = self.bits = 0
return unpack('>I', self.input.read(4))[0] | python | def read_long(self):
"""Read an unsigned 32-bit integer"""
self.bitcount = self.bits = 0
return unpack('>I', self.input.read(4))[0] | [
"def",
"read_long",
"(",
"self",
")",
":",
"self",
".",
"bitcount",
"=",
"self",
".",
"bits",
"=",
"0",
"return",
"unpack",
"(",
"'>I'",
",",
"self",
".",
"input",
".",
"read",
"(",
"4",
")",
")",
"[",
"0",
"]"
] | Read an unsigned 32-bit integer | [
"Read",
"an",
"unsigned",
"32",
"-",
"bit",
"integer"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/serialization.py#L96-L99 |
232,375 | nerdvegas/rez | src/rez/vendor/amqp/serialization.py | AMQPReader.read_longlong | def read_longlong(self):
"""Read an unsigned 64-bit integer"""
self.bitcount = self.bits = 0
return unpack('>Q', self.input.read(8))[0] | python | def read_longlong(self):
"""Read an unsigned 64-bit integer"""
self.bitcount = self.bits = 0
return unpack('>Q', self.input.read(8))[0] | [
"def",
"read_longlong",
"(",
"self",
")",
":",
"self",
".",
"bitcount",
"=",
"self",
".",
"bits",
"=",
"0",
"return",
"unpack",
"(",
"'>Q'",
",",
"self",
".",
"input",
".",
"read",
"(",
"8",
")",
")",
"[",
"0",
"]"
] | Read an unsigned 64-bit integer | [
"Read",
"an",
"unsigned",
"64",
"-",
"bit",
"integer"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/serialization.py#L101-L104 |
232,376 | nerdvegas/rez | src/rez/vendor/amqp/serialization.py | AMQPReader.read_float | def read_float(self):
"""Read float value."""
self.bitcount = self.bits = 0
return unpack('>d', self.input.read(8))[0] | python | def read_float(self):
"""Read float value."""
self.bitcount = self.bits = 0
return unpack('>d', self.input.read(8))[0] | [
"def",
"read_float",
"(",
"self",
")",
":",
"self",
".",
"bitcount",
"=",
"self",
".",
"bits",
"=",
"0",
"return",
"unpack",
"(",
"'>d'",
",",
"self",
".",
"input",
".",
"read",
"(",
"8",
")",
")",
"[",
"0",
"]"
] | Read float value. | [
"Read",
"float",
"value",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/serialization.py#L106-L109 |
232,377 | nerdvegas/rez | src/rez/vendor/amqp/serialization.py | AMQPReader.read_shortstr | def read_shortstr(self):
"""Read a short string that's stored in up to 255 bytes.
The encoding isn't specified in the AMQP spec, so
assume it's utf-8
"""
self.bitcount = self.bits = 0
slen = unpack('B', self.input.read(1))[0]
return self.input.read(slen).decode('utf-8') | python | def read_shortstr(self):
"""Read a short string that's stored in up to 255 bytes.
The encoding isn't specified in the AMQP spec, so
assume it's utf-8
"""
self.bitcount = self.bits = 0
slen = unpack('B', self.input.read(1))[0]
return self.input.read(slen).decode('utf-8') | [
"def",
"read_shortstr",
"(",
"self",
")",
":",
"self",
".",
"bitcount",
"=",
"self",
".",
"bits",
"=",
"0",
"slen",
"=",
"unpack",
"(",
"'B'",
",",
"self",
".",
"input",
".",
"read",
"(",
"1",
")",
")",
"[",
"0",
"]",
"return",
"self",
".",
"input",
".",
"read",
"(",
"slen",
")",
".",
"decode",
"(",
"'utf-8'",
")"
] | Read a short string that's stored in up to 255 bytes.
The encoding isn't specified in the AMQP spec, so
assume it's utf-8 | [
"Read",
"a",
"short",
"string",
"that",
"s",
"stored",
"in",
"up",
"to",
"255",
"bytes",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/serialization.py#L111-L120 |
232,378 | nerdvegas/rez | src/rez/vendor/amqp/serialization.py | GenericContent._load_properties | def _load_properties(self, raw_bytes):
"""Given the raw bytes containing the property-flags and property-list
from a content-frame-header, parse and insert into a dictionary
stored in this object as an attribute named 'properties'."""
r = AMQPReader(raw_bytes)
#
# Read 16-bit shorts until we get one with a low bit set to zero
#
flags = []
while 1:
flag_bits = r.read_short()
flags.append(flag_bits)
if flag_bits & 1 == 0:
break
shift = 0
d = {}
for key, proptype in self.PROPERTIES:
if shift == 0:
if not flags:
break
flag_bits, flags = flags[0], flags[1:]
shift = 15
if flag_bits & (1 << shift):
d[key] = getattr(r, 'read_' + proptype)()
shift -= 1
self.properties = d | python | def _load_properties(self, raw_bytes):
"""Given the raw bytes containing the property-flags and property-list
from a content-frame-header, parse and insert into a dictionary
stored in this object as an attribute named 'properties'."""
r = AMQPReader(raw_bytes)
#
# Read 16-bit shorts until we get one with a low bit set to zero
#
flags = []
while 1:
flag_bits = r.read_short()
flags.append(flag_bits)
if flag_bits & 1 == 0:
break
shift = 0
d = {}
for key, proptype in self.PROPERTIES:
if shift == 0:
if not flags:
break
flag_bits, flags = flags[0], flags[1:]
shift = 15
if flag_bits & (1 << shift):
d[key] = getattr(r, 'read_' + proptype)()
shift -= 1
self.properties = d | [
"def",
"_load_properties",
"(",
"self",
",",
"raw_bytes",
")",
":",
"r",
"=",
"AMQPReader",
"(",
"raw_bytes",
")",
"#",
"# Read 16-bit shorts until we get one with a low bit set to zero",
"#",
"flags",
"=",
"[",
"]",
"while",
"1",
":",
"flag_bits",
"=",
"r",
".",
"read_short",
"(",
")",
"flags",
".",
"append",
"(",
"flag_bits",
")",
"if",
"flag_bits",
"&",
"1",
"==",
"0",
":",
"break",
"shift",
"=",
"0",
"d",
"=",
"{",
"}",
"for",
"key",
",",
"proptype",
"in",
"self",
".",
"PROPERTIES",
":",
"if",
"shift",
"==",
"0",
":",
"if",
"not",
"flags",
":",
"break",
"flag_bits",
",",
"flags",
"=",
"flags",
"[",
"0",
"]",
",",
"flags",
"[",
"1",
":",
"]",
"shift",
"=",
"15",
"if",
"flag_bits",
"&",
"(",
"1",
"<<",
"shift",
")",
":",
"d",
"[",
"key",
"]",
"=",
"getattr",
"(",
"r",
",",
"'read_'",
"+",
"proptype",
")",
"(",
")",
"shift",
"-=",
"1",
"self",
".",
"properties",
"=",
"d"
] | Given the raw bytes containing the property-flags and property-list
from a content-frame-header, parse and insert into a dictionary
stored in this object as an attribute named 'properties'. | [
"Given",
"the",
"raw",
"bytes",
"containing",
"the",
"property",
"-",
"flags",
"and",
"property",
"-",
"list",
"from",
"a",
"content",
"-",
"frame",
"-",
"header",
"parse",
"and",
"insert",
"into",
"a",
"dictionary",
"stored",
"in",
"this",
"object",
"as",
"an",
"attribute",
"named",
"properties",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/serialization.py#L451-L479 |
232,379 | nerdvegas/rez | src/rez/util.py | create_executable_script | def create_executable_script(filepath, body, program=None):
"""Create an executable script.
Args:
filepath (str): File to create.
body (str or callable): Contents of the script. If a callable, its code
is used as the script body.
program (str): Name of program to launch the script, 'python' if None
"""
program = program or "python"
if callable(body):
from rez.utils.sourcecode import SourceCode
code = SourceCode(func=body)
body = code.source
if not body.endswith('\n'):
body += '\n'
with open(filepath, 'w') as f:
# TODO: make cross platform
f.write("#!/usr/bin/env %s\n" % program)
f.write(body)
# TODO: Although Windows supports os.chmod you can only set the readonly
# flag. Setting the file readonly breaks the unit tests that expect to
# clean up the files once the test has run. Temporarily we don't bother
# setting the permissions, but this will need to change.
if os.name == "posix":
os.chmod(filepath, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH
| stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) | python | def create_executable_script(filepath, body, program=None):
"""Create an executable script.
Args:
filepath (str): File to create.
body (str or callable): Contents of the script. If a callable, its code
is used as the script body.
program (str): Name of program to launch the script, 'python' if None
"""
program = program or "python"
if callable(body):
from rez.utils.sourcecode import SourceCode
code = SourceCode(func=body)
body = code.source
if not body.endswith('\n'):
body += '\n'
with open(filepath, 'w') as f:
# TODO: make cross platform
f.write("#!/usr/bin/env %s\n" % program)
f.write(body)
# TODO: Although Windows supports os.chmod you can only set the readonly
# flag. Setting the file readonly breaks the unit tests that expect to
# clean up the files once the test has run. Temporarily we don't bother
# setting the permissions, but this will need to change.
if os.name == "posix":
os.chmod(filepath, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH
| stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) | [
"def",
"create_executable_script",
"(",
"filepath",
",",
"body",
",",
"program",
"=",
"None",
")",
":",
"program",
"=",
"program",
"or",
"\"python\"",
"if",
"callable",
"(",
"body",
")",
":",
"from",
"rez",
".",
"utils",
".",
"sourcecode",
"import",
"SourceCode",
"code",
"=",
"SourceCode",
"(",
"func",
"=",
"body",
")",
"body",
"=",
"code",
".",
"source",
"if",
"not",
"body",
".",
"endswith",
"(",
"'\\n'",
")",
":",
"body",
"+=",
"'\\n'",
"with",
"open",
"(",
"filepath",
",",
"'w'",
")",
"as",
"f",
":",
"# TODO: make cross platform",
"f",
".",
"write",
"(",
"\"#!/usr/bin/env %s\\n\"",
"%",
"program",
")",
"f",
".",
"write",
"(",
"body",
")",
"# TODO: Although Windows supports os.chmod you can only set the readonly",
"# flag. Setting the file readonly breaks the unit tests that expect to",
"# clean up the files once the test has run. Temporarily we don't bother",
"# setting the permissions, but this will need to change.",
"if",
"os",
".",
"name",
"==",
"\"posix\"",
":",
"os",
".",
"chmod",
"(",
"filepath",
",",
"stat",
".",
"S_IRUSR",
"|",
"stat",
".",
"S_IRGRP",
"|",
"stat",
".",
"S_IROTH",
"|",
"stat",
".",
"S_IXUSR",
"|",
"stat",
".",
"S_IXGRP",
"|",
"stat",
".",
"S_IXOTH",
")"
] | Create an executable script.
Args:
filepath (str): File to create.
body (str or callable): Contents of the script. If a callable, its code
is used as the script body.
program (str): Name of program to launch the script, 'python' if None | [
"Create",
"an",
"executable",
"script",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/util.py#L31-L60 |
232,380 | nerdvegas/rez | src/rez/util.py | create_forwarding_script | def create_forwarding_script(filepath, module, func_name, *nargs, **kwargs):
"""Create a 'forwarding' script.
A forwarding script is one that executes some arbitrary Rez function. This
is used internally by Rez to dynamically create a script that uses Rez,
even though the parent environment may not be configured to do so.
"""
doc = dict(
module=module,
func_name=func_name)
if nargs:
doc["nargs"] = nargs
if kwargs:
doc["kwargs"] = kwargs
body = dump_yaml(doc)
create_executable_script(filepath, body, "_rez_fwd") | python | def create_forwarding_script(filepath, module, func_name, *nargs, **kwargs):
"""Create a 'forwarding' script.
A forwarding script is one that executes some arbitrary Rez function. This
is used internally by Rez to dynamically create a script that uses Rez,
even though the parent environment may not be configured to do so.
"""
doc = dict(
module=module,
func_name=func_name)
if nargs:
doc["nargs"] = nargs
if kwargs:
doc["kwargs"] = kwargs
body = dump_yaml(doc)
create_executable_script(filepath, body, "_rez_fwd") | [
"def",
"create_forwarding_script",
"(",
"filepath",
",",
"module",
",",
"func_name",
",",
"*",
"nargs",
",",
"*",
"*",
"kwargs",
")",
":",
"doc",
"=",
"dict",
"(",
"module",
"=",
"module",
",",
"func_name",
"=",
"func_name",
")",
"if",
"nargs",
":",
"doc",
"[",
"\"nargs\"",
"]",
"=",
"nargs",
"if",
"kwargs",
":",
"doc",
"[",
"\"kwargs\"",
"]",
"=",
"kwargs",
"body",
"=",
"dump_yaml",
"(",
"doc",
")",
"create_executable_script",
"(",
"filepath",
",",
"body",
",",
"\"_rez_fwd\"",
")"
] | Create a 'forwarding' script.
A forwarding script is one that executes some arbitrary Rez function. This
is used internally by Rez to dynamically create a script that uses Rez,
even though the parent environment may not be configured to do so. | [
"Create",
"a",
"forwarding",
"script",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/util.py#L63-L80 |
232,381 | nerdvegas/rez | src/rez/util.py | dedup | def dedup(seq):
"""Remove duplicates from a list while keeping order."""
seen = set()
for item in seq:
if item not in seen:
seen.add(item)
yield item | python | def dedup(seq):
"""Remove duplicates from a list while keeping order."""
seen = set()
for item in seq:
if item not in seen:
seen.add(item)
yield item | [
"def",
"dedup",
"(",
"seq",
")",
":",
"seen",
"=",
"set",
"(",
")",
"for",
"item",
"in",
"seq",
":",
"if",
"item",
"not",
"in",
"seen",
":",
"seen",
".",
"add",
"(",
"item",
")",
"yield",
"item"
] | Remove duplicates from a list while keeping order. | [
"Remove",
"duplicates",
"from",
"a",
"list",
"while",
"keeping",
"order",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/util.py#L83-L89 |
232,382 | nerdvegas/rez | src/rez/util.py | find_last_sublist | def find_last_sublist(list_, sublist):
"""Given a list, find the last occurance of a sublist within it.
Returns:
Index where the sublist starts, or None if there is no match.
"""
for i in reversed(range(len(list_) - len(sublist) + 1)):
if list_[i] == sublist[0] and list_[i:i + len(sublist)] == sublist:
return i
return None | python | def find_last_sublist(list_, sublist):
"""Given a list, find the last occurance of a sublist within it.
Returns:
Index where the sublist starts, or None if there is no match.
"""
for i in reversed(range(len(list_) - len(sublist) + 1)):
if list_[i] == sublist[0] and list_[i:i + len(sublist)] == sublist:
return i
return None | [
"def",
"find_last_sublist",
"(",
"list_",
",",
"sublist",
")",
":",
"for",
"i",
"in",
"reversed",
"(",
"range",
"(",
"len",
"(",
"list_",
")",
"-",
"len",
"(",
"sublist",
")",
"+",
"1",
")",
")",
":",
"if",
"list_",
"[",
"i",
"]",
"==",
"sublist",
"[",
"0",
"]",
"and",
"list_",
"[",
"i",
":",
"i",
"+",
"len",
"(",
"sublist",
")",
"]",
"==",
"sublist",
":",
"return",
"i",
"return",
"None"
] | Given a list, find the last occurance of a sublist within it.
Returns:
Index where the sublist starts, or None if there is no match. | [
"Given",
"a",
"list",
"find",
"the",
"last",
"occurance",
"of",
"a",
"sublist",
"within",
"it",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/util.py#L157-L166 |
232,383 | nerdvegas/rez | src/rez/package_help.py | PackageHelp.open | def open(self, section_index=0):
"""Launch a help section."""
uri = self._sections[section_index][1]
if len(uri.split()) == 1:
self._open_url(uri)
else:
if self._verbose:
print "running command: %s" % uri
p = popen(uri, shell=True)
p.wait() | python | def open(self, section_index=0):
"""Launch a help section."""
uri = self._sections[section_index][1]
if len(uri.split()) == 1:
self._open_url(uri)
else:
if self._verbose:
print "running command: %s" % uri
p = popen(uri, shell=True)
p.wait() | [
"def",
"open",
"(",
"self",
",",
"section_index",
"=",
"0",
")",
":",
"uri",
"=",
"self",
".",
"_sections",
"[",
"section_index",
"]",
"[",
"1",
"]",
"if",
"len",
"(",
"uri",
".",
"split",
"(",
")",
")",
"==",
"1",
":",
"self",
".",
"_open_url",
"(",
"uri",
")",
"else",
":",
"if",
"self",
".",
"_verbose",
":",
"print",
"\"running command: %s\"",
"%",
"uri",
"p",
"=",
"popen",
"(",
"uri",
",",
"shell",
"=",
"True",
")",
"p",
".",
"wait",
"(",
")"
] | Launch a help section. | [
"Launch",
"a",
"help",
"section",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_help.py#L88-L97 |
232,384 | nerdvegas/rez | src/rez/package_help.py | PackageHelp.print_info | def print_info(self, buf=None):
"""Print help sections."""
buf = buf or sys.stdout
print >> buf, "Sections:"
for i, section in enumerate(self._sections):
print >> buf, " %s:\t%s (%s)" % (i + 1, section[0], section[1]) | python | def print_info(self, buf=None):
"""Print help sections."""
buf = buf or sys.stdout
print >> buf, "Sections:"
for i, section in enumerate(self._sections):
print >> buf, " %s:\t%s (%s)" % (i + 1, section[0], section[1]) | [
"def",
"print_info",
"(",
"self",
",",
"buf",
"=",
"None",
")",
":",
"buf",
"=",
"buf",
"or",
"sys",
".",
"stdout",
"print",
">>",
"buf",
",",
"\"Sections:\"",
"for",
"i",
",",
"section",
"in",
"enumerate",
"(",
"self",
".",
"_sections",
")",
":",
"print",
">>",
"buf",
",",
"\" %s:\\t%s (%s)\"",
"%",
"(",
"i",
"+",
"1",
",",
"section",
"[",
"0",
"]",
",",
"section",
"[",
"1",
"]",
")"
] | Print help sections. | [
"Print",
"help",
"sections",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_help.py#L99-L104 |
232,385 | nerdvegas/rez | src/rez/vendor/memcache/memcache.py | Client.set_servers | def set_servers(self, servers):
"""
Set the pool of servers used by this client.
@param servers: an array of servers.
Servers can be passed in two forms:
1. Strings of the form C{"host:port"}, which implies a default weight of 1.
2. Tuples of the form C{("host:port", weight)}, where C{weight} is
an integer weight value.
"""
self.servers = [_Host(s, self.debug, dead_retry=self.dead_retry,
socket_timeout=self.socket_timeout,
flush_on_reconnect=self.flush_on_reconnect)
for s in servers]
self._init_buckets() | python | def set_servers(self, servers):
"""
Set the pool of servers used by this client.
@param servers: an array of servers.
Servers can be passed in two forms:
1. Strings of the form C{"host:port"}, which implies a default weight of 1.
2. Tuples of the form C{("host:port", weight)}, where C{weight} is
an integer weight value.
"""
self.servers = [_Host(s, self.debug, dead_retry=self.dead_retry,
socket_timeout=self.socket_timeout,
flush_on_reconnect=self.flush_on_reconnect)
for s in servers]
self._init_buckets() | [
"def",
"set_servers",
"(",
"self",
",",
"servers",
")",
":",
"self",
".",
"servers",
"=",
"[",
"_Host",
"(",
"s",
",",
"self",
".",
"debug",
",",
"dead_retry",
"=",
"self",
".",
"dead_retry",
",",
"socket_timeout",
"=",
"self",
".",
"socket_timeout",
",",
"flush_on_reconnect",
"=",
"self",
".",
"flush_on_reconnect",
")",
"for",
"s",
"in",
"servers",
"]",
"self",
".",
"_init_buckets",
"(",
")"
] | Set the pool of servers used by this client.
@param servers: an array of servers.
Servers can be passed in two forms:
1. Strings of the form C{"host:port"}, which implies a default weight of 1.
2. Tuples of the form C{("host:port", weight)}, where C{weight} is
an integer weight value. | [
"Set",
"the",
"pool",
"of",
"servers",
"used",
"by",
"this",
"client",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/memcache/memcache.py#L240-L254 |
232,386 | nerdvegas/rez | src/rez/vendor/memcache/memcache.py | Client.get_stats | def get_stats(self, stat_args = None):
'''Get statistics from each of the servers.
@param stat_args: Additional arguments to pass to the memcache
"stats" command.
@return: A list of tuples ( server_identifier, stats_dictionary ).
The dictionary contains a number of name/value pairs specifying
the name of the status field and the string value associated with
it. The values are not converted from strings.
'''
data = []
for s in self.servers:
if not s.connect(): continue
if s.family == socket.AF_INET:
name = '%s:%s (%s)' % ( s.ip, s.port, s.weight )
elif s.family == socket.AF_INET6:
name = '[%s]:%s (%s)' % ( s.ip, s.port, s.weight )
else:
name = 'unix:%s (%s)' % ( s.address, s.weight )
if not stat_args:
s.send_cmd('stats')
else:
s.send_cmd('stats ' + stat_args)
serverData = {}
data.append(( name, serverData ))
readline = s.readline
while 1:
line = readline()
if not line or line.strip() in ('END', 'RESET'):
break
stats = line.split(' ', 2)
serverData[stats[1]] = stats[2]
return(data) | python | def get_stats(self, stat_args = None):
'''Get statistics from each of the servers.
@param stat_args: Additional arguments to pass to the memcache
"stats" command.
@return: A list of tuples ( server_identifier, stats_dictionary ).
The dictionary contains a number of name/value pairs specifying
the name of the status field and the string value associated with
it. The values are not converted from strings.
'''
data = []
for s in self.servers:
if not s.connect(): continue
if s.family == socket.AF_INET:
name = '%s:%s (%s)' % ( s.ip, s.port, s.weight )
elif s.family == socket.AF_INET6:
name = '[%s]:%s (%s)' % ( s.ip, s.port, s.weight )
else:
name = 'unix:%s (%s)' % ( s.address, s.weight )
if not stat_args:
s.send_cmd('stats')
else:
s.send_cmd('stats ' + stat_args)
serverData = {}
data.append(( name, serverData ))
readline = s.readline
while 1:
line = readline()
if not line or line.strip() in ('END', 'RESET'):
break
stats = line.split(' ', 2)
serverData[stats[1]] = stats[2]
return(data) | [
"def",
"get_stats",
"(",
"self",
",",
"stat_args",
"=",
"None",
")",
":",
"data",
"=",
"[",
"]",
"for",
"s",
"in",
"self",
".",
"servers",
":",
"if",
"not",
"s",
".",
"connect",
"(",
")",
":",
"continue",
"if",
"s",
".",
"family",
"==",
"socket",
".",
"AF_INET",
":",
"name",
"=",
"'%s:%s (%s)'",
"%",
"(",
"s",
".",
"ip",
",",
"s",
".",
"port",
",",
"s",
".",
"weight",
")",
"elif",
"s",
".",
"family",
"==",
"socket",
".",
"AF_INET6",
":",
"name",
"=",
"'[%s]:%s (%s)'",
"%",
"(",
"s",
".",
"ip",
",",
"s",
".",
"port",
",",
"s",
".",
"weight",
")",
"else",
":",
"name",
"=",
"'unix:%s (%s)'",
"%",
"(",
"s",
".",
"address",
",",
"s",
".",
"weight",
")",
"if",
"not",
"stat_args",
":",
"s",
".",
"send_cmd",
"(",
"'stats'",
")",
"else",
":",
"s",
".",
"send_cmd",
"(",
"'stats '",
"+",
"stat_args",
")",
"serverData",
"=",
"{",
"}",
"data",
".",
"append",
"(",
"(",
"name",
",",
"serverData",
")",
")",
"readline",
"=",
"s",
".",
"readline",
"while",
"1",
":",
"line",
"=",
"readline",
"(",
")",
"if",
"not",
"line",
"or",
"line",
".",
"strip",
"(",
")",
"in",
"(",
"'END'",
",",
"'RESET'",
")",
":",
"break",
"stats",
"=",
"line",
".",
"split",
"(",
"' '",
",",
"2",
")",
"serverData",
"[",
"stats",
"[",
"1",
"]",
"]",
"=",
"stats",
"[",
"2",
"]",
"return",
"(",
"data",
")"
] | Get statistics from each of the servers.
@param stat_args: Additional arguments to pass to the memcache
"stats" command.
@return: A list of tuples ( server_identifier, stats_dictionary ).
The dictionary contains a number of name/value pairs specifying
the name of the status field and the string value associated with
it. The values are not converted from strings. | [
"Get",
"statistics",
"from",
"each",
"of",
"the",
"servers",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/memcache/memcache.py#L256-L290 |
232,387 | nerdvegas/rez | src/rez/vendor/memcache/memcache.py | Client.delete_multi | def delete_multi(self, keys, time=0, key_prefix=''):
'''
Delete multiple keys in the memcache doing just one query.
>>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'})
>>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'}
1
>>> mc.delete_multi(['key1', 'key2'])
1
>>> mc.get_multi(['key1', 'key2']) == {}
1
This method is recommended over iterated regular L{delete}s as it reduces total latency, since
your app doesn't have to wait for each round-trip of L{delete} before sending
the next one.
@param keys: An iterable of keys to clear
@param time: number of seconds any subsequent set / update commands should fail. Defaults to 0 for no delay.
@param key_prefix: Optional string to prepend to each key when sending to memcache.
See docs for L{get_multi} and L{set_multi}.
@return: 1 if no failure in communication with any memcacheds.
@rtype: int
'''
self._statlog('delete_multi')
server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(keys, key_prefix)
# send out all requests on each server before reading anything
dead_servers = []
rc = 1
for server in server_keys.iterkeys():
bigcmd = []
write = bigcmd.append
if time != None:
for key in server_keys[server]: # These are mangled keys
write("delete %s %d\r\n" % (key, time))
else:
for key in server_keys[server]: # These are mangled keys
write("delete %s\r\n" % key)
try:
server.send_cmds(''.join(bigcmd))
except socket.error, msg:
rc = 0
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
dead_servers.append(server)
# if any servers died on the way, don't expect them to respond.
for server in dead_servers:
del server_keys[server]
for server, keys in server_keys.iteritems():
try:
for key in keys:
server.expect("DELETED")
except socket.error, msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
rc = 0
return rc | python | def delete_multi(self, keys, time=0, key_prefix=''):
'''
Delete multiple keys in the memcache doing just one query.
>>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'})
>>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'}
1
>>> mc.delete_multi(['key1', 'key2'])
1
>>> mc.get_multi(['key1', 'key2']) == {}
1
This method is recommended over iterated regular L{delete}s as it reduces total latency, since
your app doesn't have to wait for each round-trip of L{delete} before sending
the next one.
@param keys: An iterable of keys to clear
@param time: number of seconds any subsequent set / update commands should fail. Defaults to 0 for no delay.
@param key_prefix: Optional string to prepend to each key when sending to memcache.
See docs for L{get_multi} and L{set_multi}.
@return: 1 if no failure in communication with any memcacheds.
@rtype: int
'''
self._statlog('delete_multi')
server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(keys, key_prefix)
# send out all requests on each server before reading anything
dead_servers = []
rc = 1
for server in server_keys.iterkeys():
bigcmd = []
write = bigcmd.append
if time != None:
for key in server_keys[server]: # These are mangled keys
write("delete %s %d\r\n" % (key, time))
else:
for key in server_keys[server]: # These are mangled keys
write("delete %s\r\n" % key)
try:
server.send_cmds(''.join(bigcmd))
except socket.error, msg:
rc = 0
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
dead_servers.append(server)
# if any servers died on the way, don't expect them to respond.
for server in dead_servers:
del server_keys[server]
for server, keys in server_keys.iteritems():
try:
for key in keys:
server.expect("DELETED")
except socket.error, msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
rc = 0
return rc | [
"def",
"delete_multi",
"(",
"self",
",",
"keys",
",",
"time",
"=",
"0",
",",
"key_prefix",
"=",
"''",
")",
":",
"self",
".",
"_statlog",
"(",
"'delete_multi'",
")",
"server_keys",
",",
"prefixed_to_orig_key",
"=",
"self",
".",
"_map_and_prefix_keys",
"(",
"keys",
",",
"key_prefix",
")",
"# send out all requests on each server before reading anything",
"dead_servers",
"=",
"[",
"]",
"rc",
"=",
"1",
"for",
"server",
"in",
"server_keys",
".",
"iterkeys",
"(",
")",
":",
"bigcmd",
"=",
"[",
"]",
"write",
"=",
"bigcmd",
".",
"append",
"if",
"time",
"!=",
"None",
":",
"for",
"key",
"in",
"server_keys",
"[",
"server",
"]",
":",
"# These are mangled keys",
"write",
"(",
"\"delete %s %d\\r\\n\"",
"%",
"(",
"key",
",",
"time",
")",
")",
"else",
":",
"for",
"key",
"in",
"server_keys",
"[",
"server",
"]",
":",
"# These are mangled keys",
"write",
"(",
"\"delete %s\\r\\n\"",
"%",
"key",
")",
"try",
":",
"server",
".",
"send_cmds",
"(",
"''",
".",
"join",
"(",
"bigcmd",
")",
")",
"except",
"socket",
".",
"error",
",",
"msg",
":",
"rc",
"=",
"0",
"if",
"isinstance",
"(",
"msg",
",",
"tuple",
")",
":",
"msg",
"=",
"msg",
"[",
"1",
"]",
"server",
".",
"mark_dead",
"(",
"msg",
")",
"dead_servers",
".",
"append",
"(",
"server",
")",
"# if any servers died on the way, don't expect them to respond.",
"for",
"server",
"in",
"dead_servers",
":",
"del",
"server_keys",
"[",
"server",
"]",
"for",
"server",
",",
"keys",
"in",
"server_keys",
".",
"iteritems",
"(",
")",
":",
"try",
":",
"for",
"key",
"in",
"keys",
":",
"server",
".",
"expect",
"(",
"\"DELETED\"",
")",
"except",
"socket",
".",
"error",
",",
"msg",
":",
"if",
"isinstance",
"(",
"msg",
",",
"tuple",
")",
":",
"msg",
"=",
"msg",
"[",
"1",
"]",
"server",
".",
"mark_dead",
"(",
"msg",
")",
"rc",
"=",
"0",
"return",
"rc"
] | Delete multiple keys in the memcache doing just one query.
>>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'})
>>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'}
1
>>> mc.delete_multi(['key1', 'key2'])
1
>>> mc.get_multi(['key1', 'key2']) == {}
1
This method is recommended over iterated regular L{delete}s as it reduces total latency, since
your app doesn't have to wait for each round-trip of L{delete} before sending
the next one.
@param keys: An iterable of keys to clear
@param time: number of seconds any subsequent set / update commands should fail. Defaults to 0 for no delay.
@param key_prefix: Optional string to prepend to each key when sending to memcache.
See docs for L{get_multi} and L{set_multi}.
@return: 1 if no failure in communication with any memcacheds.
@rtype: int | [
"Delete",
"multiple",
"keys",
"in",
"the",
"memcache",
"doing",
"just",
"one",
"query",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/memcache/memcache.py#L365-L429 |
232,388 | nerdvegas/rez | src/rez/vendor/memcache/memcache.py | Client.delete | def delete(self, key, time=0):
'''Deletes a key from the memcache.
@return: Nonzero on success.
@param time: number of seconds any subsequent set / update commands
should fail. Defaults to None for no delay.
@rtype: int
'''
if self.do_check_key:
self.check_key(key)
server, key = self._get_server(key)
if not server:
return 0
self._statlog('delete')
if time != None and time != 0:
cmd = "delete %s %d" % (key, time)
else:
cmd = "delete %s" % key
try:
server.send_cmd(cmd)
line = server.readline()
if line and line.strip() in ['DELETED', 'NOT_FOUND']: return 1
self.debuglog('Delete expected DELETED or NOT_FOUND, got: %s'
% repr(line))
except socket.error, msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
return 0 | python | def delete(self, key, time=0):
'''Deletes a key from the memcache.
@return: Nonzero on success.
@param time: number of seconds any subsequent set / update commands
should fail. Defaults to None for no delay.
@rtype: int
'''
if self.do_check_key:
self.check_key(key)
server, key = self._get_server(key)
if not server:
return 0
self._statlog('delete')
if time != None and time != 0:
cmd = "delete %s %d" % (key, time)
else:
cmd = "delete %s" % key
try:
server.send_cmd(cmd)
line = server.readline()
if line and line.strip() in ['DELETED', 'NOT_FOUND']: return 1
self.debuglog('Delete expected DELETED or NOT_FOUND, got: %s'
% repr(line))
except socket.error, msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
return 0 | [
"def",
"delete",
"(",
"self",
",",
"key",
",",
"time",
"=",
"0",
")",
":",
"if",
"self",
".",
"do_check_key",
":",
"self",
".",
"check_key",
"(",
"key",
")",
"server",
",",
"key",
"=",
"self",
".",
"_get_server",
"(",
"key",
")",
"if",
"not",
"server",
":",
"return",
"0",
"self",
".",
"_statlog",
"(",
"'delete'",
")",
"if",
"time",
"!=",
"None",
"and",
"time",
"!=",
"0",
":",
"cmd",
"=",
"\"delete %s %d\"",
"%",
"(",
"key",
",",
"time",
")",
"else",
":",
"cmd",
"=",
"\"delete %s\"",
"%",
"key",
"try",
":",
"server",
".",
"send_cmd",
"(",
"cmd",
")",
"line",
"=",
"server",
".",
"readline",
"(",
")",
"if",
"line",
"and",
"line",
".",
"strip",
"(",
")",
"in",
"[",
"'DELETED'",
",",
"'NOT_FOUND'",
"]",
":",
"return",
"1",
"self",
".",
"debuglog",
"(",
"'Delete expected DELETED or NOT_FOUND, got: %s'",
"%",
"repr",
"(",
"line",
")",
")",
"except",
"socket",
".",
"error",
",",
"msg",
":",
"if",
"isinstance",
"(",
"msg",
",",
"tuple",
")",
":",
"msg",
"=",
"msg",
"[",
"1",
"]",
"server",
".",
"mark_dead",
"(",
"msg",
")",
"return",
"0"
] | Deletes a key from the memcache.
@return: Nonzero on success.
@param time: number of seconds any subsequent set / update commands
should fail. Defaults to None for no delay.
@rtype: int | [
"Deletes",
"a",
"key",
"from",
"the",
"memcache",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/memcache/memcache.py#L431-L459 |
232,389 | nerdvegas/rez | src/rez/vendor/memcache/memcache.py | Client.add | def add(self, key, val, time = 0, min_compress_len = 0):
'''
Add new key with value.
Like L{set}, but only stores in memcache if the key doesn't already exist.
@return: Nonzero on success.
@rtype: int
'''
return self._set("add", key, val, time, min_compress_len) | python | def add(self, key, val, time = 0, min_compress_len = 0):
'''
Add new key with value.
Like L{set}, but only stores in memcache if the key doesn't already exist.
@return: Nonzero on success.
@rtype: int
'''
return self._set("add", key, val, time, min_compress_len) | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"val",
",",
"time",
"=",
"0",
",",
"min_compress_len",
"=",
"0",
")",
":",
"return",
"self",
".",
"_set",
"(",
"\"add\"",
",",
"key",
",",
"val",
",",
"time",
",",
"min_compress_len",
")"
] | Add new key with value.
Like L{set}, but only stores in memcache if the key doesn't already exist.
@return: Nonzero on success.
@rtype: int | [
"Add",
"new",
"key",
"with",
"value",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/memcache/memcache.py#L517-L526 |
232,390 | nerdvegas/rez | src/rez/vendor/memcache/memcache.py | Client.append | def append(self, key, val, time=0, min_compress_len=0):
'''Append the value to the end of the existing key's value.
Only stores in memcache if key already exists.
Also see L{prepend}.
@return: Nonzero on success.
@rtype: int
'''
return self._set("append", key, val, time, min_compress_len) | python | def append(self, key, val, time=0, min_compress_len=0):
'''Append the value to the end of the existing key's value.
Only stores in memcache if key already exists.
Also see L{prepend}.
@return: Nonzero on success.
@rtype: int
'''
return self._set("append", key, val, time, min_compress_len) | [
"def",
"append",
"(",
"self",
",",
"key",
",",
"val",
",",
"time",
"=",
"0",
",",
"min_compress_len",
"=",
"0",
")",
":",
"return",
"self",
".",
"_set",
"(",
"\"append\"",
",",
"key",
",",
"val",
",",
"time",
",",
"min_compress_len",
")"
] | Append the value to the end of the existing key's value.
Only stores in memcache if key already exists.
Also see L{prepend}.
@return: Nonzero on success.
@rtype: int | [
"Append",
"the",
"value",
"to",
"the",
"end",
"of",
"the",
"existing",
"key",
"s",
"value",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/memcache/memcache.py#L528-L537 |
232,391 | nerdvegas/rez | src/rez/vendor/memcache/memcache.py | Client.prepend | def prepend(self, key, val, time=0, min_compress_len=0):
'''Prepend the value to the beginning of the existing key's value.
Only stores in memcache if key already exists.
Also see L{append}.
@return: Nonzero on success.
@rtype: int
'''
return self._set("prepend", key, val, time, min_compress_len) | python | def prepend(self, key, val, time=0, min_compress_len=0):
'''Prepend the value to the beginning of the existing key's value.
Only stores in memcache if key already exists.
Also see L{append}.
@return: Nonzero on success.
@rtype: int
'''
return self._set("prepend", key, val, time, min_compress_len) | [
"def",
"prepend",
"(",
"self",
",",
"key",
",",
"val",
",",
"time",
"=",
"0",
",",
"min_compress_len",
"=",
"0",
")",
":",
"return",
"self",
".",
"_set",
"(",
"\"prepend\"",
",",
"key",
",",
"val",
",",
"time",
",",
"min_compress_len",
")"
] | Prepend the value to the beginning of the existing key's value.
Only stores in memcache if key already exists.
Also see L{append}.
@return: Nonzero on success.
@rtype: int | [
"Prepend",
"the",
"value",
"to",
"the",
"beginning",
"of",
"the",
"existing",
"key",
"s",
"value",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/memcache/memcache.py#L539-L548 |
232,392 | nerdvegas/rez | src/rez/vendor/memcache/memcache.py | Client.replace | def replace(self, key, val, time=0, min_compress_len=0):
'''Replace existing key with value.
Like L{set}, but only stores in memcache if the key already exists.
The opposite of L{add}.
@return: Nonzero on success.
@rtype: int
'''
return self._set("replace", key, val, time, min_compress_len) | python | def replace(self, key, val, time=0, min_compress_len=0):
'''Replace existing key with value.
Like L{set}, but only stores in memcache if the key already exists.
The opposite of L{add}.
@return: Nonzero on success.
@rtype: int
'''
return self._set("replace", key, val, time, min_compress_len) | [
"def",
"replace",
"(",
"self",
",",
"key",
",",
"val",
",",
"time",
"=",
"0",
",",
"min_compress_len",
"=",
"0",
")",
":",
"return",
"self",
".",
"_set",
"(",
"\"replace\"",
",",
"key",
",",
"val",
",",
"time",
",",
"min_compress_len",
")"
] | Replace existing key with value.
Like L{set}, but only stores in memcache if the key already exists.
The opposite of L{add}.
@return: Nonzero on success.
@rtype: int | [
"Replace",
"existing",
"key",
"with",
"value",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/memcache/memcache.py#L550-L559 |
232,393 | nerdvegas/rez | src/rez/vendor/memcache/memcache.py | Client.set | def set(self, key, val, time=0, min_compress_len=0):
'''Unconditionally sets a key to a given value in the memcache.
The C{key} can optionally be an tuple, with the first element
being the server hash value and the second being the key.
If you want to avoid making this module calculate a hash value.
You may prefer, for example, to keep all of a given user's objects
on the same memcache server, so you could use the user's unique
id as the hash value.
@return: Nonzero on success.
@rtype: int
@param time: Tells memcached the time which this value should expire, either
as a delta number of seconds, or an absolute unix time-since-the-epoch
value. See the memcached protocol docs section "Storage Commands"
for more info on <exptime>. We default to 0 == cache forever.
@param min_compress_len: The threshold length to kick in auto-compression
of the value using the zlib.compress() routine. If the value being cached is
a string, then the length of the string is measured, else if the value is an
object, then the length of the pickle result is measured. If the resulting
attempt at compression yeilds a larger string than the input, then it is
discarded. For backwards compatability, this parameter defaults to 0,
indicating don't ever try to compress.
'''
return self._set("set", key, val, time, min_compress_len) | python | def set(self, key, val, time=0, min_compress_len=0):
'''Unconditionally sets a key to a given value in the memcache.
The C{key} can optionally be an tuple, with the first element
being the server hash value and the second being the key.
If you want to avoid making this module calculate a hash value.
You may prefer, for example, to keep all of a given user's objects
on the same memcache server, so you could use the user's unique
id as the hash value.
@return: Nonzero on success.
@rtype: int
@param time: Tells memcached the time which this value should expire, either
as a delta number of seconds, or an absolute unix time-since-the-epoch
value. See the memcached protocol docs section "Storage Commands"
for more info on <exptime>. We default to 0 == cache forever.
@param min_compress_len: The threshold length to kick in auto-compression
of the value using the zlib.compress() routine. If the value being cached is
a string, then the length of the string is measured, else if the value is an
object, then the length of the pickle result is measured. If the resulting
attempt at compression yeilds a larger string than the input, then it is
discarded. For backwards compatability, this parameter defaults to 0,
indicating don't ever try to compress.
'''
return self._set("set", key, val, time, min_compress_len) | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"val",
",",
"time",
"=",
"0",
",",
"min_compress_len",
"=",
"0",
")",
":",
"return",
"self",
".",
"_set",
"(",
"\"set\"",
",",
"key",
",",
"val",
",",
"time",
",",
"min_compress_len",
")"
] | Unconditionally sets a key to a given value in the memcache.
The C{key} can optionally be an tuple, with the first element
being the server hash value and the second being the key.
If you want to avoid making this module calculate a hash value.
You may prefer, for example, to keep all of a given user's objects
on the same memcache server, so you could use the user's unique
id as the hash value.
@return: Nonzero on success.
@rtype: int
@param time: Tells memcached the time which this value should expire, either
as a delta number of seconds, or an absolute unix time-since-the-epoch
value. See the memcached protocol docs section "Storage Commands"
for more info on <exptime>. We default to 0 == cache forever.
@param min_compress_len: The threshold length to kick in auto-compression
of the value using the zlib.compress() routine. If the value being cached is
a string, then the length of the string is measured, else if the value is an
object, then the length of the pickle result is measured. If the resulting
attempt at compression yeilds a larger string than the input, then it is
discarded. For backwards compatability, this parameter defaults to 0,
indicating don't ever try to compress. | [
"Unconditionally",
"sets",
"a",
"key",
"to",
"a",
"given",
"value",
"in",
"the",
"memcache",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/memcache/memcache.py#L561-L585 |
232,394 | nerdvegas/rez | src/rez/vendor/memcache/memcache.py | Client.set_multi | def set_multi(self, mapping, time=0, key_prefix='', min_compress_len=0):
'''
Sets multiple keys in the memcache doing just one query.
>>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'})
>>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'}
1
This method is recommended over regular L{set} as it lowers the
number of total packets flying around your network, reducing
total latency, since your app doesn't have to wait for each
round-trip of L{set} before sending the next one.
@param mapping: A dict of key/value pairs to set.
@param time: Tells memcached the time which this value should
expire, either as a delta number of seconds, or an absolute
unix time-since-the-epoch value. See the memcached protocol
docs section "Storage Commands" for more info on <exptime>. We
default to 0 == cache forever.
@param key_prefix: Optional string to prepend to each key when
sending to memcache. Allows you to efficiently stuff these
keys into a pseudo-namespace in memcache:
>>> notset_keys = mc.set_multi(
... {'key1' : 'val1', 'key2' : 'val2'}, key_prefix='subspace_')
>>> len(notset_keys) == 0
True
>>> mc.get_multi(['subspace_key1', 'subspace_key2']) == {'subspace_key1' : 'val1', 'subspace_key2' : 'val2'}
True
Causes key 'subspace_key1' and 'subspace_key2' to be
set. Useful in conjunction with a higher-level layer which
applies namespaces to data in memcache. In this case, the
return result would be the list of notset original keys,
prefix not applied.
@param min_compress_len: The threshold length to kick in
auto-compression of the value using the zlib.compress()
routine. If the value being cached is a string, then
the length of the string is measured, else if the value
is an object, then the length of the pickle result is
measured. If the resulting attempt at compression yeilds
a larger string than the input, then it is discarded. For
backwards compatability, this parameter defaults to 0,
indicating don't ever try to compress.
@return: List of keys which failed to be stored [ memcache out of
memory, etc. ].
@rtype: list
'''
self._statlog('set_multi')
server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(
mapping.iterkeys(), key_prefix)
# send out all requests on each server before reading anything
dead_servers = []
notstored = [] # original keys.
for server in server_keys.iterkeys():
bigcmd = []
write = bigcmd.append
try:
for key in server_keys[server]: # These are mangled keys
store_info = self._val_to_store_info(
mapping[prefixed_to_orig_key[key]],
min_compress_len)
if store_info:
write("set %s %d %d %d\r\n%s\r\n" % (key, store_info[0],
time, store_info[1], store_info[2]))
else:
notstored.append(prefixed_to_orig_key[key])
server.send_cmds(''.join(bigcmd))
except socket.error, msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
dead_servers.append(server)
# if any servers died on the way, don't expect them to respond.
for server in dead_servers:
del server_keys[server]
# short-circuit if there are no servers, just return all keys
if not server_keys: return(mapping.keys())
for server, keys in server_keys.iteritems():
try:
for key in keys:
if server.readline() == 'STORED':
continue
else:
notstored.append(prefixed_to_orig_key[key]) #un-mangle.
except (_Error, socket.error), msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
return notstored | python | def set_multi(self, mapping, time=0, key_prefix='', min_compress_len=0):
'''
Sets multiple keys in the memcache doing just one query.
>>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'})
>>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'}
1
This method is recommended over regular L{set} as it lowers the
number of total packets flying around your network, reducing
total latency, since your app doesn't have to wait for each
round-trip of L{set} before sending the next one.
@param mapping: A dict of key/value pairs to set.
@param time: Tells memcached the time which this value should
expire, either as a delta number of seconds, or an absolute
unix time-since-the-epoch value. See the memcached protocol
docs section "Storage Commands" for more info on <exptime>. We
default to 0 == cache forever.
@param key_prefix: Optional string to prepend to each key when
sending to memcache. Allows you to efficiently stuff these
keys into a pseudo-namespace in memcache:
>>> notset_keys = mc.set_multi(
... {'key1' : 'val1', 'key2' : 'val2'}, key_prefix='subspace_')
>>> len(notset_keys) == 0
True
>>> mc.get_multi(['subspace_key1', 'subspace_key2']) == {'subspace_key1' : 'val1', 'subspace_key2' : 'val2'}
True
Causes key 'subspace_key1' and 'subspace_key2' to be
set. Useful in conjunction with a higher-level layer which
applies namespaces to data in memcache. In this case, the
return result would be the list of notset original keys,
prefix not applied.
@param min_compress_len: The threshold length to kick in
auto-compression of the value using the zlib.compress()
routine. If the value being cached is a string, then
the length of the string is measured, else if the value
is an object, then the length of the pickle result is
measured. If the resulting attempt at compression yeilds
a larger string than the input, then it is discarded. For
backwards compatability, this parameter defaults to 0,
indicating don't ever try to compress.
@return: List of keys which failed to be stored [ memcache out of
memory, etc. ].
@rtype: list
'''
self._statlog('set_multi')
server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(
mapping.iterkeys(), key_prefix)
# send out all requests on each server before reading anything
dead_servers = []
notstored = [] # original keys.
for server in server_keys.iterkeys():
bigcmd = []
write = bigcmd.append
try:
for key in server_keys[server]: # These are mangled keys
store_info = self._val_to_store_info(
mapping[prefixed_to_orig_key[key]],
min_compress_len)
if store_info:
write("set %s %d %d %d\r\n%s\r\n" % (key, store_info[0],
time, store_info[1], store_info[2]))
else:
notstored.append(prefixed_to_orig_key[key])
server.send_cmds(''.join(bigcmd))
except socket.error, msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
dead_servers.append(server)
# if any servers died on the way, don't expect them to respond.
for server in dead_servers:
del server_keys[server]
# short-circuit if there are no servers, just return all keys
if not server_keys: return(mapping.keys())
for server, keys in server_keys.iteritems():
try:
for key in keys:
if server.readline() == 'STORED':
continue
else:
notstored.append(prefixed_to_orig_key[key]) #un-mangle.
except (_Error, socket.error), msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
return notstored | [
"def",
"set_multi",
"(",
"self",
",",
"mapping",
",",
"time",
"=",
"0",
",",
"key_prefix",
"=",
"''",
",",
"min_compress_len",
"=",
"0",
")",
":",
"self",
".",
"_statlog",
"(",
"'set_multi'",
")",
"server_keys",
",",
"prefixed_to_orig_key",
"=",
"self",
".",
"_map_and_prefix_keys",
"(",
"mapping",
".",
"iterkeys",
"(",
")",
",",
"key_prefix",
")",
"# send out all requests on each server before reading anything",
"dead_servers",
"=",
"[",
"]",
"notstored",
"=",
"[",
"]",
"# original keys.",
"for",
"server",
"in",
"server_keys",
".",
"iterkeys",
"(",
")",
":",
"bigcmd",
"=",
"[",
"]",
"write",
"=",
"bigcmd",
".",
"append",
"try",
":",
"for",
"key",
"in",
"server_keys",
"[",
"server",
"]",
":",
"# These are mangled keys",
"store_info",
"=",
"self",
".",
"_val_to_store_info",
"(",
"mapping",
"[",
"prefixed_to_orig_key",
"[",
"key",
"]",
"]",
",",
"min_compress_len",
")",
"if",
"store_info",
":",
"write",
"(",
"\"set %s %d %d %d\\r\\n%s\\r\\n\"",
"%",
"(",
"key",
",",
"store_info",
"[",
"0",
"]",
",",
"time",
",",
"store_info",
"[",
"1",
"]",
",",
"store_info",
"[",
"2",
"]",
")",
")",
"else",
":",
"notstored",
".",
"append",
"(",
"prefixed_to_orig_key",
"[",
"key",
"]",
")",
"server",
".",
"send_cmds",
"(",
"''",
".",
"join",
"(",
"bigcmd",
")",
")",
"except",
"socket",
".",
"error",
",",
"msg",
":",
"if",
"isinstance",
"(",
"msg",
",",
"tuple",
")",
":",
"msg",
"=",
"msg",
"[",
"1",
"]",
"server",
".",
"mark_dead",
"(",
"msg",
")",
"dead_servers",
".",
"append",
"(",
"server",
")",
"# if any servers died on the way, don't expect them to respond.",
"for",
"server",
"in",
"dead_servers",
":",
"del",
"server_keys",
"[",
"server",
"]",
"# short-circuit if there are no servers, just return all keys",
"if",
"not",
"server_keys",
":",
"return",
"(",
"mapping",
".",
"keys",
"(",
")",
")",
"for",
"server",
",",
"keys",
"in",
"server_keys",
".",
"iteritems",
"(",
")",
":",
"try",
":",
"for",
"key",
"in",
"keys",
":",
"if",
"server",
".",
"readline",
"(",
")",
"==",
"'STORED'",
":",
"continue",
"else",
":",
"notstored",
".",
"append",
"(",
"prefixed_to_orig_key",
"[",
"key",
"]",
")",
"#un-mangle.",
"except",
"(",
"_Error",
",",
"socket",
".",
"error",
")",
",",
"msg",
":",
"if",
"isinstance",
"(",
"msg",
",",
"tuple",
")",
":",
"msg",
"=",
"msg",
"[",
"1",
"]",
"server",
".",
"mark_dead",
"(",
"msg",
")",
"return",
"notstored"
] | Sets multiple keys in the memcache doing just one query.
>>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'})
>>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'}
1
This method is recommended over regular L{set} as it lowers the
number of total packets flying around your network, reducing
total latency, since your app doesn't have to wait for each
round-trip of L{set} before sending the next one.
@param mapping: A dict of key/value pairs to set.
@param time: Tells memcached the time which this value should
expire, either as a delta number of seconds, or an absolute
unix time-since-the-epoch value. See the memcached protocol
docs section "Storage Commands" for more info on <exptime>. We
default to 0 == cache forever.
@param key_prefix: Optional string to prepend to each key when
sending to memcache. Allows you to efficiently stuff these
keys into a pseudo-namespace in memcache:
>>> notset_keys = mc.set_multi(
... {'key1' : 'val1', 'key2' : 'val2'}, key_prefix='subspace_')
>>> len(notset_keys) == 0
True
>>> mc.get_multi(['subspace_key1', 'subspace_key2']) == {'subspace_key1' : 'val1', 'subspace_key2' : 'val2'}
True
Causes key 'subspace_key1' and 'subspace_key2' to be
set. Useful in conjunction with a higher-level layer which
applies namespaces to data in memcache. In this case, the
return result would be the list of notset original keys,
prefix not applied.
@param min_compress_len: The threshold length to kick in
auto-compression of the value using the zlib.compress()
routine. If the value being cached is a string, then
the length of the string is measured, else if the value
is an object, then the length of the pickle result is
measured. If the resulting attempt at compression yeilds
a larger string than the input, then it is discarded. For
backwards compatability, this parameter defaults to 0,
indicating don't ever try to compress.
@return: List of keys which failed to be stored [ memcache out of
memory, etc. ].
@rtype: list | [
"Sets",
"multiple",
"keys",
"in",
"the",
"memcache",
"doing",
"just",
"one",
"query",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/memcache/memcache.py#L658-L755 |
232,395 | nerdvegas/rez | src/rez/vendor/memcache/memcache.py | Client.get_multi | def get_multi(self, keys, key_prefix=''):
'''
Retrieves multiple keys from the memcache doing just one query.
>>> success = mc.set("foo", "bar")
>>> success = mc.set("baz", 42)
>>> mc.get_multi(["foo", "baz", "foobar"]) == {"foo": "bar", "baz": 42}
1
>>> mc.set_multi({'k1' : 1, 'k2' : 2}, key_prefix='pfx_') == []
1
This looks up keys 'pfx_k1', 'pfx_k2', ... . Returned dict will just have unprefixed keys 'k1', 'k2'.
>>> mc.get_multi(['k1', 'k2', 'nonexist'], key_prefix='pfx_') == {'k1' : 1, 'k2' : 2}
1
get_mult [ and L{set_multi} ] can take str()-ables like ints / longs as keys too. Such as your db pri key fields.
They're rotored through str() before being passed off to memcache, with or without the use of a key_prefix.
In this mode, the key_prefix could be a table name, and the key itself a db primary key number.
>>> mc.set_multi({42: 'douglass adams', 46 : 'and 2 just ahead of me'}, key_prefix='numkeys_') == []
1
>>> mc.get_multi([46, 42], key_prefix='numkeys_') == {42: 'douglass adams', 46 : 'and 2 just ahead of me'}
1
This method is recommended over regular L{get} as it lowers the number of
total packets flying around your network, reducing total latency, since
your app doesn't have to wait for each round-trip of L{get} before sending
the next one.
See also L{set_multi}.
@param keys: An array of keys.
@param key_prefix: A string to prefix each key when we communicate with memcache.
Facilitates pseudo-namespaces within memcache. Returned dictionary keys will not have this prefix.
@return: A dictionary of key/value pairs that were available. If key_prefix was provided, the keys in the retured dictionary will not have it present.
'''
self._statlog('get_multi')
server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(keys, key_prefix)
# send out all requests on each server before reading anything
dead_servers = []
for server in server_keys.iterkeys():
try:
server.send_cmd("get %s" % " ".join(server_keys[server]))
except socket.error, msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
dead_servers.append(server)
# if any servers died on the way, don't expect them to respond.
for server in dead_servers:
del server_keys[server]
retvals = {}
for server in server_keys.iterkeys():
try:
line = server.readline()
while line and line != 'END':
rkey, flags, rlen = self._expectvalue(server, line)
# Bo Yang reports that this can sometimes be None
if rkey is not None:
val = self._recv_value(server, flags, rlen)
retvals[prefixed_to_orig_key[rkey]] = val # un-prefix returned key.
line = server.readline()
except (_Error, socket.error), msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
return retvals | python | def get_multi(self, keys, key_prefix=''):
'''
Retrieves multiple keys from the memcache doing just one query.
>>> success = mc.set("foo", "bar")
>>> success = mc.set("baz", 42)
>>> mc.get_multi(["foo", "baz", "foobar"]) == {"foo": "bar", "baz": 42}
1
>>> mc.set_multi({'k1' : 1, 'k2' : 2}, key_prefix='pfx_') == []
1
This looks up keys 'pfx_k1', 'pfx_k2', ... . Returned dict will just have unprefixed keys 'k1', 'k2'.
>>> mc.get_multi(['k1', 'k2', 'nonexist'], key_prefix='pfx_') == {'k1' : 1, 'k2' : 2}
1
get_mult [ and L{set_multi} ] can take str()-ables like ints / longs as keys too. Such as your db pri key fields.
They're rotored through str() before being passed off to memcache, with or without the use of a key_prefix.
In this mode, the key_prefix could be a table name, and the key itself a db primary key number.
>>> mc.set_multi({42: 'douglass adams', 46 : 'and 2 just ahead of me'}, key_prefix='numkeys_') == []
1
>>> mc.get_multi([46, 42], key_prefix='numkeys_') == {42: 'douglass adams', 46 : 'and 2 just ahead of me'}
1
This method is recommended over regular L{get} as it lowers the number of
total packets flying around your network, reducing total latency, since
your app doesn't have to wait for each round-trip of L{get} before sending
the next one.
See also L{set_multi}.
@param keys: An array of keys.
@param key_prefix: A string to prefix each key when we communicate with memcache.
Facilitates pseudo-namespaces within memcache. Returned dictionary keys will not have this prefix.
@return: A dictionary of key/value pairs that were available. If key_prefix was provided, the keys in the retured dictionary will not have it present.
'''
self._statlog('get_multi')
server_keys, prefixed_to_orig_key = self._map_and_prefix_keys(keys, key_prefix)
# send out all requests on each server before reading anything
dead_servers = []
for server in server_keys.iterkeys():
try:
server.send_cmd("get %s" % " ".join(server_keys[server]))
except socket.error, msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
dead_servers.append(server)
# if any servers died on the way, don't expect them to respond.
for server in dead_servers:
del server_keys[server]
retvals = {}
for server in server_keys.iterkeys():
try:
line = server.readline()
while line and line != 'END':
rkey, flags, rlen = self._expectvalue(server, line)
# Bo Yang reports that this can sometimes be None
if rkey is not None:
val = self._recv_value(server, flags, rlen)
retvals[prefixed_to_orig_key[rkey]] = val # un-prefix returned key.
line = server.readline()
except (_Error, socket.error), msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
return retvals | [
"def",
"get_multi",
"(",
"self",
",",
"keys",
",",
"key_prefix",
"=",
"''",
")",
":",
"self",
".",
"_statlog",
"(",
"'get_multi'",
")",
"server_keys",
",",
"prefixed_to_orig_key",
"=",
"self",
".",
"_map_and_prefix_keys",
"(",
"keys",
",",
"key_prefix",
")",
"# send out all requests on each server before reading anything",
"dead_servers",
"=",
"[",
"]",
"for",
"server",
"in",
"server_keys",
".",
"iterkeys",
"(",
")",
":",
"try",
":",
"server",
".",
"send_cmd",
"(",
"\"get %s\"",
"%",
"\" \"",
".",
"join",
"(",
"server_keys",
"[",
"server",
"]",
")",
")",
"except",
"socket",
".",
"error",
",",
"msg",
":",
"if",
"isinstance",
"(",
"msg",
",",
"tuple",
")",
":",
"msg",
"=",
"msg",
"[",
"1",
"]",
"server",
".",
"mark_dead",
"(",
"msg",
")",
"dead_servers",
".",
"append",
"(",
"server",
")",
"# if any servers died on the way, don't expect them to respond.",
"for",
"server",
"in",
"dead_servers",
":",
"del",
"server_keys",
"[",
"server",
"]",
"retvals",
"=",
"{",
"}",
"for",
"server",
"in",
"server_keys",
".",
"iterkeys",
"(",
")",
":",
"try",
":",
"line",
"=",
"server",
".",
"readline",
"(",
")",
"while",
"line",
"and",
"line",
"!=",
"'END'",
":",
"rkey",
",",
"flags",
",",
"rlen",
"=",
"self",
".",
"_expectvalue",
"(",
"server",
",",
"line",
")",
"# Bo Yang reports that this can sometimes be None",
"if",
"rkey",
"is",
"not",
"None",
":",
"val",
"=",
"self",
".",
"_recv_value",
"(",
"server",
",",
"flags",
",",
"rlen",
")",
"retvals",
"[",
"prefixed_to_orig_key",
"[",
"rkey",
"]",
"]",
"=",
"val",
"# un-prefix returned key.",
"line",
"=",
"server",
".",
"readline",
"(",
")",
"except",
"(",
"_Error",
",",
"socket",
".",
"error",
")",
",",
"msg",
":",
"if",
"isinstance",
"(",
"msg",
",",
"tuple",
")",
":",
"msg",
"=",
"msg",
"[",
"1",
"]",
"server",
".",
"mark_dead",
"(",
"msg",
")",
"return",
"retvals"
] | Retrieves multiple keys from the memcache doing just one query.
>>> success = mc.set("foo", "bar")
>>> success = mc.set("baz", 42)
>>> mc.get_multi(["foo", "baz", "foobar"]) == {"foo": "bar", "baz": 42}
1
>>> mc.set_multi({'k1' : 1, 'k2' : 2}, key_prefix='pfx_') == []
1
This looks up keys 'pfx_k1', 'pfx_k2', ... . Returned dict will just have unprefixed keys 'k1', 'k2'.
>>> mc.get_multi(['k1', 'k2', 'nonexist'], key_prefix='pfx_') == {'k1' : 1, 'k2' : 2}
1
get_mult [ and L{set_multi} ] can take str()-ables like ints / longs as keys too. Such as your db pri key fields.
They're rotored through str() before being passed off to memcache, with or without the use of a key_prefix.
In this mode, the key_prefix could be a table name, and the key itself a db primary key number.
>>> mc.set_multi({42: 'douglass adams', 46 : 'and 2 just ahead of me'}, key_prefix='numkeys_') == []
1
>>> mc.get_multi([46, 42], key_prefix='numkeys_') == {42: 'douglass adams', 46 : 'and 2 just ahead of me'}
1
This method is recommended over regular L{get} as it lowers the number of
total packets flying around your network, reducing total latency, since
your app doesn't have to wait for each round-trip of L{get} before sending
the next one.
See also L{set_multi}.
@param keys: An array of keys.
@param key_prefix: A string to prefix each key when we communicate with memcache.
Facilitates pseudo-namespaces within memcache. Returned dictionary keys will not have this prefix.
@return: A dictionary of key/value pairs that were available. If key_prefix was provided, the keys in the retured dictionary will not have it present. | [
"Retrieves",
"multiple",
"keys",
"from",
"the",
"memcache",
"doing",
"just",
"one",
"query",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/memcache/memcache.py#L908-L978 |
232,396 | nerdvegas/rez | src/rez/vendor/memcache/memcache.py | _Host.readline | def readline(self, raise_exception=False):
"""Read a line and return it. If "raise_exception" is set,
raise _ConnectionDeadError if the read fails, otherwise return
an empty string.
"""
buf = self.buffer
if self.socket:
recv = self.socket.recv
else:
recv = lambda bufsize: ''
while True:
index = buf.find('\r\n')
if index >= 0:
break
data = recv(4096)
if not data:
# connection close, let's kill it and raise
self.mark_dead('connection closed in readline()')
if raise_exception:
raise _ConnectionDeadError()
else:
return ''
buf += data
self.buffer = buf[index+2:]
return buf[:index] | python | def readline(self, raise_exception=False):
"""Read a line and return it. If "raise_exception" is set,
raise _ConnectionDeadError if the read fails, otherwise return
an empty string.
"""
buf = self.buffer
if self.socket:
recv = self.socket.recv
else:
recv = lambda bufsize: ''
while True:
index = buf.find('\r\n')
if index >= 0:
break
data = recv(4096)
if not data:
# connection close, let's kill it and raise
self.mark_dead('connection closed in readline()')
if raise_exception:
raise _ConnectionDeadError()
else:
return ''
buf += data
self.buffer = buf[index+2:]
return buf[:index] | [
"def",
"readline",
"(",
"self",
",",
"raise_exception",
"=",
"False",
")",
":",
"buf",
"=",
"self",
".",
"buffer",
"if",
"self",
".",
"socket",
":",
"recv",
"=",
"self",
".",
"socket",
".",
"recv",
"else",
":",
"recv",
"=",
"lambda",
"bufsize",
":",
"''",
"while",
"True",
":",
"index",
"=",
"buf",
".",
"find",
"(",
"'\\r\\n'",
")",
"if",
"index",
">=",
"0",
":",
"break",
"data",
"=",
"recv",
"(",
"4096",
")",
"if",
"not",
"data",
":",
"# connection close, let's kill it and raise",
"self",
".",
"mark_dead",
"(",
"'connection closed in readline()'",
")",
"if",
"raise_exception",
":",
"raise",
"_ConnectionDeadError",
"(",
")",
"else",
":",
"return",
"''",
"buf",
"+=",
"data",
"self",
".",
"buffer",
"=",
"buf",
"[",
"index",
"+",
"2",
":",
"]",
"return",
"buf",
"[",
":",
"index",
"]"
] | Read a line and return it. If "raise_exception" is set,
raise _ConnectionDeadError if the read fails, otherwise return
an empty string. | [
"Read",
"a",
"line",
"and",
"return",
"it",
".",
"If",
"raise_exception",
"is",
"set",
"raise",
"_ConnectionDeadError",
"if",
"the",
"read",
"fails",
"otherwise",
"return",
"an",
"empty",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/memcache/memcache.py#L1168-L1194 |
232,397 | nerdvegas/rez | src/rezplugins/package_repository/memory.py | MemoryPackageRepository.create_repository | def create_repository(cls, repository_data):
"""Create a standalone, in-memory repository.
Using this function bypasses the `package_repository_manager` singleton.
This is usually desired however, since in-memory repositories are for
temporarily storing programmatically created packages, which we do not
want to cache and that do not persist.
Args:
repository_data (dict): Repository data, see class docstring.
Returns:
`MemoryPackageRepository` object.
"""
location = "memory{%s}" % hex(id(repository_data))
resource_pool = ResourcePool(cache_size=None)
repo = MemoryPackageRepository(location, resource_pool)
repo.data = repository_data
return repo | python | def create_repository(cls, repository_data):
"""Create a standalone, in-memory repository.
Using this function bypasses the `package_repository_manager` singleton.
This is usually desired however, since in-memory repositories are for
temporarily storing programmatically created packages, which we do not
want to cache and that do not persist.
Args:
repository_data (dict): Repository data, see class docstring.
Returns:
`MemoryPackageRepository` object.
"""
location = "memory{%s}" % hex(id(repository_data))
resource_pool = ResourcePool(cache_size=None)
repo = MemoryPackageRepository(location, resource_pool)
repo.data = repository_data
return repo | [
"def",
"create_repository",
"(",
"cls",
",",
"repository_data",
")",
":",
"location",
"=",
"\"memory{%s}\"",
"%",
"hex",
"(",
"id",
"(",
"repository_data",
")",
")",
"resource_pool",
"=",
"ResourcePool",
"(",
"cache_size",
"=",
"None",
")",
"repo",
"=",
"MemoryPackageRepository",
"(",
"location",
",",
"resource_pool",
")",
"repo",
".",
"data",
"=",
"repository_data",
"return",
"repo"
] | Create a standalone, in-memory repository.
Using this function bypasses the `package_repository_manager` singleton.
This is usually desired however, since in-memory repositories are for
temporarily storing programmatically created packages, which we do not
want to cache and that do not persist.
Args:
repository_data (dict): Repository data, see class docstring.
Returns:
`MemoryPackageRepository` object. | [
"Create",
"a",
"standalone",
"in",
"-",
"memory",
"repository",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezplugins/package_repository/memory.py#L134-L152 |
232,398 | nerdvegas/rez | src/build_utils/distlib/metadata.py | LegacyMetadata.read_file | def read_file(self, fileob):
"""Read the metadata values from a file object."""
msg = message_from_file(fileob)
self._fields['Metadata-Version'] = msg['metadata-version']
# When reading, get all the fields we can
for field in _ALL_FIELDS:
if field not in msg:
continue
if field in _LISTFIELDS:
# we can have multiple lines
values = msg.get_all(field)
if field in _LISTTUPLEFIELDS and values is not None:
values = [tuple(value.split(',')) for value in values]
self.set(field, values)
else:
# single line
value = msg[field]
if value is not None and value != 'UNKNOWN':
self.set(field, value)
self.set_metadata_version() | python | def read_file(self, fileob):
"""Read the metadata values from a file object."""
msg = message_from_file(fileob)
self._fields['Metadata-Version'] = msg['metadata-version']
# When reading, get all the fields we can
for field in _ALL_FIELDS:
if field not in msg:
continue
if field in _LISTFIELDS:
# we can have multiple lines
values = msg.get_all(field)
if field in _LISTTUPLEFIELDS and values is not None:
values = [tuple(value.split(',')) for value in values]
self.set(field, values)
else:
# single line
value = msg[field]
if value is not None and value != 'UNKNOWN':
self.set(field, value)
self.set_metadata_version() | [
"def",
"read_file",
"(",
"self",
",",
"fileob",
")",
":",
"msg",
"=",
"message_from_file",
"(",
"fileob",
")",
"self",
".",
"_fields",
"[",
"'Metadata-Version'",
"]",
"=",
"msg",
"[",
"'metadata-version'",
"]",
"# When reading, get all the fields we can",
"for",
"field",
"in",
"_ALL_FIELDS",
":",
"if",
"field",
"not",
"in",
"msg",
":",
"continue",
"if",
"field",
"in",
"_LISTFIELDS",
":",
"# we can have multiple lines",
"values",
"=",
"msg",
".",
"get_all",
"(",
"field",
")",
"if",
"field",
"in",
"_LISTTUPLEFIELDS",
"and",
"values",
"is",
"not",
"None",
":",
"values",
"=",
"[",
"tuple",
"(",
"value",
".",
"split",
"(",
"','",
")",
")",
"for",
"value",
"in",
"values",
"]",
"self",
".",
"set",
"(",
"field",
",",
"values",
")",
"else",
":",
"# single line",
"value",
"=",
"msg",
"[",
"field",
"]",
"if",
"value",
"is",
"not",
"None",
"and",
"value",
"!=",
"'UNKNOWN'",
":",
"self",
".",
"set",
"(",
"field",
",",
"value",
")",
"self",
".",
"set_metadata_version",
"(",
")"
] | Read the metadata values from a file object. | [
"Read",
"the",
"metadata",
"values",
"from",
"a",
"file",
"object",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/build_utils/distlib/metadata.py#L334-L354 |
232,399 | nerdvegas/rez | src/build_utils/distlib/metadata.py | LegacyMetadata.check | def check(self, strict=False):
"""Check if the metadata is compliant. If strict is True then raise if
no Name or Version are provided"""
self.set_metadata_version()
# XXX should check the versions (if the file was loaded)
missing, warnings = [], []
for attr in ('Name', 'Version'): # required by PEP 345
if attr not in self:
missing.append(attr)
if strict and missing != []:
msg = 'missing required metadata: %s' % ', '.join(missing)
raise MetadataMissingError(msg)
for attr in ('Home-page', 'Author'):
if attr not in self:
missing.append(attr)
# checking metadata 1.2 (XXX needs to check 1.1, 1.0)
if self['Metadata-Version'] != '1.2':
return missing, warnings
scheme = get_scheme(self.scheme)
def are_valid_constraints(value):
for v in value:
if not scheme.is_valid_matcher(v.split(';')[0]):
return False
return True
for fields, controller in ((_PREDICATE_FIELDS, are_valid_constraints),
(_VERSIONS_FIELDS,
scheme.is_valid_constraint_list),
(_VERSION_FIELDS,
scheme.is_valid_version)):
for field in fields:
value = self.get(field, None)
if value is not None and not controller(value):
warnings.append('Wrong value for %r: %s' % (field, value))
return missing, warnings | python | def check(self, strict=False):
"""Check if the metadata is compliant. If strict is True then raise if
no Name or Version are provided"""
self.set_metadata_version()
# XXX should check the versions (if the file was loaded)
missing, warnings = [], []
for attr in ('Name', 'Version'): # required by PEP 345
if attr not in self:
missing.append(attr)
if strict and missing != []:
msg = 'missing required metadata: %s' % ', '.join(missing)
raise MetadataMissingError(msg)
for attr in ('Home-page', 'Author'):
if attr not in self:
missing.append(attr)
# checking metadata 1.2 (XXX needs to check 1.1, 1.0)
if self['Metadata-Version'] != '1.2':
return missing, warnings
scheme = get_scheme(self.scheme)
def are_valid_constraints(value):
for v in value:
if not scheme.is_valid_matcher(v.split(';')[0]):
return False
return True
for fields, controller in ((_PREDICATE_FIELDS, are_valid_constraints),
(_VERSIONS_FIELDS,
scheme.is_valid_constraint_list),
(_VERSION_FIELDS,
scheme.is_valid_version)):
for field in fields:
value = self.get(field, None)
if value is not None and not controller(value):
warnings.append('Wrong value for %r: %s' % (field, value))
return missing, warnings | [
"def",
"check",
"(",
"self",
",",
"strict",
"=",
"False",
")",
":",
"self",
".",
"set_metadata_version",
"(",
")",
"# XXX should check the versions (if the file was loaded)",
"missing",
",",
"warnings",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"attr",
"in",
"(",
"'Name'",
",",
"'Version'",
")",
":",
"# required by PEP 345",
"if",
"attr",
"not",
"in",
"self",
":",
"missing",
".",
"append",
"(",
"attr",
")",
"if",
"strict",
"and",
"missing",
"!=",
"[",
"]",
":",
"msg",
"=",
"'missing required metadata: %s'",
"%",
"', '",
".",
"join",
"(",
"missing",
")",
"raise",
"MetadataMissingError",
"(",
"msg",
")",
"for",
"attr",
"in",
"(",
"'Home-page'",
",",
"'Author'",
")",
":",
"if",
"attr",
"not",
"in",
"self",
":",
"missing",
".",
"append",
"(",
"attr",
")",
"# checking metadata 1.2 (XXX needs to check 1.1, 1.0)",
"if",
"self",
"[",
"'Metadata-Version'",
"]",
"!=",
"'1.2'",
":",
"return",
"missing",
",",
"warnings",
"scheme",
"=",
"get_scheme",
"(",
"self",
".",
"scheme",
")",
"def",
"are_valid_constraints",
"(",
"value",
")",
":",
"for",
"v",
"in",
"value",
":",
"if",
"not",
"scheme",
".",
"is_valid_matcher",
"(",
"v",
".",
"split",
"(",
"';'",
")",
"[",
"0",
"]",
")",
":",
"return",
"False",
"return",
"True",
"for",
"fields",
",",
"controller",
"in",
"(",
"(",
"_PREDICATE_FIELDS",
",",
"are_valid_constraints",
")",
",",
"(",
"_VERSIONS_FIELDS",
",",
"scheme",
".",
"is_valid_constraint_list",
")",
",",
"(",
"_VERSION_FIELDS",
",",
"scheme",
".",
"is_valid_version",
")",
")",
":",
"for",
"field",
"in",
"fields",
":",
"value",
"=",
"self",
".",
"get",
"(",
"field",
",",
"None",
")",
"if",
"value",
"is",
"not",
"None",
"and",
"not",
"controller",
"(",
"value",
")",
":",
"warnings",
".",
"append",
"(",
"'Wrong value for %r: %s'",
"%",
"(",
"field",
",",
"value",
")",
")",
"return",
"missing",
",",
"warnings"
] | Check if the metadata is compliant. If strict is True then raise if
no Name or Version are provided | [
"Check",
"if",
"the",
"metadata",
"is",
"compliant",
".",
"If",
"strict",
"is",
"True",
"then",
"raise",
"if",
"no",
"Name",
"or",
"Version",
"are",
"provided"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/build_utils/distlib/metadata.py#L487-L529 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.