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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
228,500 | pyca/pynacl | src/nacl/bindings/crypto_secretstream.py | crypto_secretstream_xchacha20poly1305_rekey | def crypto_secretstream_xchacha20poly1305_rekey(state):
"""
Explicitly change the encryption key in the stream.
Normally the stream is re-keyed as needed or an explicit ``tag`` of
:data:`.crypto_secretstream_xchacha20poly1305_TAG_REKEY` is added to a
message to ensure forward secrecy, but this method can be used instead
if the re-keying is controlled without adding the tag.
:param state: a secretstream state object
:type state: crypto_secretstream_xchacha20poly1305_state
"""
ensure(
isinstance(state, crypto_secretstream_xchacha20poly1305_state),
'State must be a crypto_secretstream_xchacha20poly1305_state object',
raising=exc.TypeError,
)
lib.crypto_secretstream_xchacha20poly1305_rekey(state.statebuf) | python | def crypto_secretstream_xchacha20poly1305_rekey(state):
ensure(
isinstance(state, crypto_secretstream_xchacha20poly1305_state),
'State must be a crypto_secretstream_xchacha20poly1305_state object',
raising=exc.TypeError,
)
lib.crypto_secretstream_xchacha20poly1305_rekey(state.statebuf) | [
"def",
"crypto_secretstream_xchacha20poly1305_rekey",
"(",
"state",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"state",
",",
"crypto_secretstream_xchacha20poly1305_state",
")",
",",
"'State must be a crypto_secretstream_xchacha20poly1305_state object'",
",",
"raising",
"=",
"e... | Explicitly change the encryption key in the stream.
Normally the stream is re-keyed as needed or an explicit ``tag`` of
:data:`.crypto_secretstream_xchacha20poly1305_TAG_REKEY` is added to a
message to ensure forward secrecy, but this method can be used instead
if the re-keying is controlled without adding the tag.
:param state: a secretstream state object
:type state: crypto_secretstream_xchacha20poly1305_state | [
"Explicitly",
"change",
"the",
"encryption",
"key",
"in",
"the",
"stream",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_secretstream.py#L305-L323 |
228,501 | pyca/pynacl | src/nacl/pwhash/__init__.py | verify | def verify(password_hash, password):
"""
Takes a modular crypt encoded stored password hash derived using one
of the algorithms supported by `libsodium` and checks if the user provided
password will hash to the same string when using the parameters saved
in the stored hash
"""
if password_hash.startswith(argon2id.STRPREFIX):
return argon2id.verify(password_hash, password)
elif password_hash.startswith(argon2i.STRPREFIX):
return argon2id.verify(password_hash, password)
elif password_hash.startswith(scrypt.STRPREFIX):
return scrypt.verify(password_hash, password)
else:
raise(CryptPrefixError("given password_hash is not "
"in a supported format"
)
) | python | def verify(password_hash, password):
if password_hash.startswith(argon2id.STRPREFIX):
return argon2id.verify(password_hash, password)
elif password_hash.startswith(argon2i.STRPREFIX):
return argon2id.verify(password_hash, password)
elif password_hash.startswith(scrypt.STRPREFIX):
return scrypt.verify(password_hash, password)
else:
raise(CryptPrefixError("given password_hash is not "
"in a supported format"
)
) | [
"def",
"verify",
"(",
"password_hash",
",",
"password",
")",
":",
"if",
"password_hash",
".",
"startswith",
"(",
"argon2id",
".",
"STRPREFIX",
")",
":",
"return",
"argon2id",
".",
"verify",
"(",
"password_hash",
",",
"password",
")",
"elif",
"password_hash",
... | Takes a modular crypt encoded stored password hash derived using one
of the algorithms supported by `libsodium` and checks if the user provided
password will hash to the same string when using the parameters saved
in the stored hash | [
"Takes",
"a",
"modular",
"crypt",
"encoded",
"stored",
"password",
"hash",
"derived",
"using",
"one",
"of",
"the",
"algorithms",
"supported",
"by",
"libsodium",
"and",
"checks",
"if",
"the",
"user",
"provided",
"password",
"will",
"hash",
"to",
"the",
"same",
... | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/pwhash/__init__.py#L58-L75 |
228,502 | pyca/pynacl | src/nacl/pwhash/scrypt.py | kdf | def kdf(size, password, salt,
opslimit=OPSLIMIT_SENSITIVE,
memlimit=MEMLIMIT_SENSITIVE,
encoder=nacl.encoding.RawEncoder):
"""
Derive a ``size`` bytes long key from a caller-supplied
``password`` and ``salt`` pair using the scryptsalsa208sha256
memory-hard construct.
the enclosing module provides the constants
- :py:const:`.OPSLIMIT_INTERACTIVE`
- :py:const:`.MEMLIMIT_INTERACTIVE`
- :py:const:`.OPSLIMIT_SENSITIVE`
- :py:const:`.MEMLIMIT_SENSITIVE`
- :py:const:`.OPSLIMIT_MODERATE`
- :py:const:`.MEMLIMIT_MODERATE`
as a guidance for correct settings respectively for the
interactive login and the long term key protecting sensitive data
use cases.
:param size: derived key size, must be between
:py:const:`.BYTES_MIN` and
:py:const:`.BYTES_MAX`
:type size: int
:param password: password used to seed the key derivation procedure;
it length must be between
:py:const:`.PASSWD_MIN` and
:py:const:`.PASSWD_MAX`
:type password: bytes
:param salt: **RANDOM** salt used in the key derivation procedure;
its length must be exactly :py:const:`.SALTBYTES`
:type salt: bytes
:param opslimit: the time component (operation count)
of the key derivation procedure's computational cost;
it must be between
:py:const:`.OPSLIMIT_MIN` and
:py:const:`.OPSLIMIT_MAX`
:type opslimit: int
:param memlimit: the memory occupation component
of the key derivation procedure's computational cost;
it must be between
:py:const:`.MEMLIMIT_MIN` and
:py:const:`.MEMLIMIT_MAX`
:type memlimit: int
:rtype: bytes
.. versionadded:: 1.2
"""
ensure(
len(salt) == SALTBYTES,
"The salt must be exactly %s, not %s bytes long" % (
SALTBYTES,
len(salt)
),
raising=exc.ValueError
)
n_log2, r, p = nacl.bindings.nacl_bindings_pick_scrypt_params(opslimit,
memlimit)
maxmem = memlimit + (2 ** 16)
return encoder.encode(
nacl.bindings.crypto_pwhash_scryptsalsa208sha256_ll(
password, salt, 2 ** n_log2, r, p, maxmem=maxmem, dklen=size)
) | python | def kdf(size, password, salt,
opslimit=OPSLIMIT_SENSITIVE,
memlimit=MEMLIMIT_SENSITIVE,
encoder=nacl.encoding.RawEncoder):
ensure(
len(salt) == SALTBYTES,
"The salt must be exactly %s, not %s bytes long" % (
SALTBYTES,
len(salt)
),
raising=exc.ValueError
)
n_log2, r, p = nacl.bindings.nacl_bindings_pick_scrypt_params(opslimit,
memlimit)
maxmem = memlimit + (2 ** 16)
return encoder.encode(
nacl.bindings.crypto_pwhash_scryptsalsa208sha256_ll(
password, salt, 2 ** n_log2, r, p, maxmem=maxmem, dklen=size)
) | [
"def",
"kdf",
"(",
"size",
",",
"password",
",",
"salt",
",",
"opslimit",
"=",
"OPSLIMIT_SENSITIVE",
",",
"memlimit",
"=",
"MEMLIMIT_SENSITIVE",
",",
"encoder",
"=",
"nacl",
".",
"encoding",
".",
"RawEncoder",
")",
":",
"ensure",
"(",
"len",
"(",
"salt",
... | Derive a ``size`` bytes long key from a caller-supplied
``password`` and ``salt`` pair using the scryptsalsa208sha256
memory-hard construct.
the enclosing module provides the constants
- :py:const:`.OPSLIMIT_INTERACTIVE`
- :py:const:`.MEMLIMIT_INTERACTIVE`
- :py:const:`.OPSLIMIT_SENSITIVE`
- :py:const:`.MEMLIMIT_SENSITIVE`
- :py:const:`.OPSLIMIT_MODERATE`
- :py:const:`.MEMLIMIT_MODERATE`
as a guidance for correct settings respectively for the
interactive login and the long term key protecting sensitive data
use cases.
:param size: derived key size, must be between
:py:const:`.BYTES_MIN` and
:py:const:`.BYTES_MAX`
:type size: int
:param password: password used to seed the key derivation procedure;
it length must be between
:py:const:`.PASSWD_MIN` and
:py:const:`.PASSWD_MAX`
:type password: bytes
:param salt: **RANDOM** salt used in the key derivation procedure;
its length must be exactly :py:const:`.SALTBYTES`
:type salt: bytes
:param opslimit: the time component (operation count)
of the key derivation procedure's computational cost;
it must be between
:py:const:`.OPSLIMIT_MIN` and
:py:const:`.OPSLIMIT_MAX`
:type opslimit: int
:param memlimit: the memory occupation component
of the key derivation procedure's computational cost;
it must be between
:py:const:`.MEMLIMIT_MIN` and
:py:const:`.MEMLIMIT_MAX`
:type memlimit: int
:rtype: bytes
.. versionadded:: 1.2 | [
"Derive",
"a",
"size",
"bytes",
"long",
"key",
"from",
"a",
"caller",
"-",
"supplied",
"password",
"and",
"salt",
"pair",
"using",
"the",
"scryptsalsa208sha256",
"memory",
"-",
"hard",
"construct",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/pwhash/scrypt.py#L54-L121 |
228,503 | pyca/pynacl | src/nacl/pwhash/scrypt.py | str | def str(password,
opslimit=OPSLIMIT_INTERACTIVE,
memlimit=MEMLIMIT_INTERACTIVE):
"""
Hashes a password with a random salt, using the memory-hard
scryptsalsa208sha256 construct and returning an ascii string
that has all the needed info to check against a future password
The default settings for opslimit and memlimit are those deemed
correct for the interactive user login case.
:param bytes password:
:param int opslimit:
:param int memlimit:
:rtype: bytes
.. versionadded:: 1.2
"""
return nacl.bindings.crypto_pwhash_scryptsalsa208sha256_str(password,
opslimit,
memlimit) | python | def str(password,
opslimit=OPSLIMIT_INTERACTIVE,
memlimit=MEMLIMIT_INTERACTIVE):
return nacl.bindings.crypto_pwhash_scryptsalsa208sha256_str(password,
opslimit,
memlimit) | [
"def",
"str",
"(",
"password",
",",
"opslimit",
"=",
"OPSLIMIT_INTERACTIVE",
",",
"memlimit",
"=",
"MEMLIMIT_INTERACTIVE",
")",
":",
"return",
"nacl",
".",
"bindings",
".",
"crypto_pwhash_scryptsalsa208sha256_str",
"(",
"password",
",",
"opslimit",
",",
"memlimit",
... | Hashes a password with a random salt, using the memory-hard
scryptsalsa208sha256 construct and returning an ascii string
that has all the needed info to check against a future password
The default settings for opslimit and memlimit are those deemed
correct for the interactive user login case.
:param bytes password:
:param int opslimit:
:param int memlimit:
:rtype: bytes
.. versionadded:: 1.2 | [
"Hashes",
"a",
"password",
"with",
"a",
"random",
"salt",
"using",
"the",
"memory",
"-",
"hard",
"scryptsalsa208sha256",
"construct",
"and",
"returning",
"an",
"ascii",
"string",
"that",
"has",
"all",
"the",
"needed",
"info",
"to",
"check",
"against",
"a",
"... | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/pwhash/scrypt.py#L124-L145 |
228,504 | pyca/pynacl | src/nacl/pwhash/scrypt.py | verify | def verify(password_hash, password):
"""
Takes the output of scryptsalsa208sha256 and compares it against
a user provided password to see if they are the same
:param password_hash: bytes
:param password: bytes
:rtype: boolean
.. versionadded:: 1.2
"""
ensure(len(password_hash) == PWHASH_SIZE,
"The password hash must be exactly %s bytes long" %
nacl.bindings.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
raising=exc.ValueError)
return nacl.bindings.crypto_pwhash_scryptsalsa208sha256_str_verify(
password_hash, password
) | python | def verify(password_hash, password):
ensure(len(password_hash) == PWHASH_SIZE,
"The password hash must be exactly %s bytes long" %
nacl.bindings.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
raising=exc.ValueError)
return nacl.bindings.crypto_pwhash_scryptsalsa208sha256_str_verify(
password_hash, password
) | [
"def",
"verify",
"(",
"password_hash",
",",
"password",
")",
":",
"ensure",
"(",
"len",
"(",
"password_hash",
")",
"==",
"PWHASH_SIZE",
",",
"\"The password hash must be exactly %s bytes long\"",
"%",
"nacl",
".",
"bindings",
".",
"crypto_pwhash_scryptsalsa208sha256_STR... | Takes the output of scryptsalsa208sha256 and compares it against
a user provided password to see if they are the same
:param password_hash: bytes
:param password: bytes
:rtype: boolean
.. versionadded:: 1.2 | [
"Takes",
"the",
"output",
"of",
"scryptsalsa208sha256",
"and",
"compares",
"it",
"against",
"a",
"user",
"provided",
"password",
"to",
"see",
"if",
"they",
"are",
"the",
"same"
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/pwhash/scrypt.py#L148-L167 |
228,505 | pyca/pynacl | src/nacl/public.py | PrivateKey.from_seed | def from_seed(cls, seed, encoder=encoding.RawEncoder):
"""
Generate a PrivateKey using a deterministic construction
starting from a caller-provided seed
.. warning:: The seed **must** be high-entropy; therefore,
its generator **must** be a cryptographic quality
random function like, for example, :func:`~nacl.utils.random`.
.. warning:: The seed **must** be protected and remain secret.
Anyone who knows the seed is really in possession of
the corresponding PrivateKey.
:param seed: The seed used to generate the private key
:rtype: :class:`~nacl.public.PrivateKey`
"""
# decode the seed
seed = encoder.decode(seed)
# Verify the given seed type and size are correct
if not (isinstance(seed, bytes) and len(seed) == cls.SEED_SIZE):
raise exc.TypeError(("PrivateKey seed must be a {0} bytes long "
"binary sequence").format(cls.SEED_SIZE)
)
# generate a raw keypair from the given seed
raw_pk, raw_sk = nacl.bindings.crypto_box_seed_keypair(seed)
# construct a instance from the raw secret key
return cls(raw_sk) | python | def from_seed(cls, seed, encoder=encoding.RawEncoder):
# decode the seed
seed = encoder.decode(seed)
# Verify the given seed type and size are correct
if not (isinstance(seed, bytes) and len(seed) == cls.SEED_SIZE):
raise exc.TypeError(("PrivateKey seed must be a {0} bytes long "
"binary sequence").format(cls.SEED_SIZE)
)
# generate a raw keypair from the given seed
raw_pk, raw_sk = nacl.bindings.crypto_box_seed_keypair(seed)
# construct a instance from the raw secret key
return cls(raw_sk) | [
"def",
"from_seed",
"(",
"cls",
",",
"seed",
",",
"encoder",
"=",
"encoding",
".",
"RawEncoder",
")",
":",
"# decode the seed",
"seed",
"=",
"encoder",
".",
"decode",
"(",
"seed",
")",
"# Verify the given seed type and size are correct",
"if",
"not",
"(",
"isins... | Generate a PrivateKey using a deterministic construction
starting from a caller-provided seed
.. warning:: The seed **must** be high-entropy; therefore,
its generator **must** be a cryptographic quality
random function like, for example, :func:`~nacl.utils.random`.
.. warning:: The seed **must** be protected and remain secret.
Anyone who knows the seed is really in possession of
the corresponding PrivateKey.
:param seed: The seed used to generate the private key
:rtype: :class:`~nacl.public.PrivateKey` | [
"Generate",
"a",
"PrivateKey",
"using",
"a",
"deterministic",
"construction",
"starting",
"from",
"a",
"caller",
"-",
"provided",
"seed"
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/public.py#L99-L125 |
228,506 | pyca/pynacl | src/nacl/public.py | SealedBox.encrypt | def encrypt(self, plaintext, encoder=encoding.RawEncoder):
"""
Encrypts the plaintext message using a random-generated ephemeral
keypair and returns a "composed ciphertext", containing both
the public part of the keypair and the ciphertext proper,
encoded with the encoder.
The private part of the ephemeral key-pair will be scrubbed before
returning the ciphertext, therefore, the sender will not be able to
decrypt the generated ciphertext.
:param plaintext: [:class:`bytes`] The plaintext message to encrypt
:param encoder: The encoder to use to encode the ciphertext
:return bytes: encoded ciphertext
"""
ciphertext = nacl.bindings.crypto_box_seal(
plaintext,
self._public_key
)
encoded_ciphertext = encoder.encode(ciphertext)
return encoded_ciphertext | python | def encrypt(self, plaintext, encoder=encoding.RawEncoder):
ciphertext = nacl.bindings.crypto_box_seal(
plaintext,
self._public_key
)
encoded_ciphertext = encoder.encode(ciphertext)
return encoded_ciphertext | [
"def",
"encrypt",
"(",
"self",
",",
"plaintext",
",",
"encoder",
"=",
"encoding",
".",
"RawEncoder",
")",
":",
"ciphertext",
"=",
"nacl",
".",
"bindings",
".",
"crypto_box_seal",
"(",
"plaintext",
",",
"self",
".",
"_public_key",
")",
"encoded_ciphertext",
"... | Encrypts the plaintext message using a random-generated ephemeral
keypair and returns a "composed ciphertext", containing both
the public part of the keypair and the ciphertext proper,
encoded with the encoder.
The private part of the ephemeral key-pair will be scrubbed before
returning the ciphertext, therefore, the sender will not be able to
decrypt the generated ciphertext.
:param plaintext: [:class:`bytes`] The plaintext message to encrypt
:param encoder: The encoder to use to encode the ciphertext
:return bytes: encoded ciphertext | [
"Encrypts",
"the",
"plaintext",
"message",
"using",
"a",
"random",
"-",
"generated",
"ephemeral",
"keypair",
"and",
"returns",
"a",
"composed",
"ciphertext",
"containing",
"both",
"the",
"public",
"part",
"of",
"the",
"keypair",
"and",
"the",
"ciphertext",
"prop... | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/public.py#L320-L343 |
228,507 | pyca/pynacl | src/nacl/public.py | SealedBox.decrypt | def decrypt(self, ciphertext, encoder=encoding.RawEncoder):
"""
Decrypts the ciphertext using the ephemeral public key enclosed
in the ciphertext and the SealedBox private key, returning
the plaintext message.
:param ciphertext: [:class:`bytes`] The encrypted message to decrypt
:param encoder: The encoder used to decode the ciphertext.
:return bytes: The original plaintext
"""
# Decode our ciphertext
ciphertext = encoder.decode(ciphertext)
plaintext = nacl.bindings.crypto_box_seal_open(
ciphertext,
self._public_key,
self._private_key,
)
return plaintext | python | def decrypt(self, ciphertext, encoder=encoding.RawEncoder):
# Decode our ciphertext
ciphertext = encoder.decode(ciphertext)
plaintext = nacl.bindings.crypto_box_seal_open(
ciphertext,
self._public_key,
self._private_key,
)
return plaintext | [
"def",
"decrypt",
"(",
"self",
",",
"ciphertext",
",",
"encoder",
"=",
"encoding",
".",
"RawEncoder",
")",
":",
"# Decode our ciphertext",
"ciphertext",
"=",
"encoder",
".",
"decode",
"(",
"ciphertext",
")",
"plaintext",
"=",
"nacl",
".",
"bindings",
".",
"c... | Decrypts the ciphertext using the ephemeral public key enclosed
in the ciphertext and the SealedBox private key, returning
the plaintext message.
:param ciphertext: [:class:`bytes`] The encrypted message to decrypt
:param encoder: The encoder used to decode the ciphertext.
:return bytes: The original plaintext | [
"Decrypts",
"the",
"ciphertext",
"using",
"the",
"ephemeral",
"public",
"key",
"enclosed",
"in",
"the",
"ciphertext",
"and",
"the",
"SealedBox",
"private",
"key",
"returning",
"the",
"plaintext",
"message",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/public.py#L345-L364 |
228,508 | pyca/pynacl | tasks.py | release | def release(ctx, version):
"""
``version`` should be a string like '0.4' or '1.0'.
"""
invoke.run("git tag -s {0} -m '{0} release'".format(version))
invoke.run("git push --tags")
invoke.run("python setup.py sdist")
invoke.run("twine upload -s dist/PyNaCl-{0}* ".format(version))
session = requests.Session()
token = getpass.getpass("Input the Jenkins token: ")
response = session.post(
"{0}/build".format(JENKINS_URL),
params={
"cause": "Building wheels for {0}".format(version),
"token": token
}
)
response.raise_for_status()
wait_for_build_completed(session)
paths = download_artifacts(session)
invoke.run("twine upload {0}".format(" ".join(paths))) | python | def release(ctx, version):
invoke.run("git tag -s {0} -m '{0} release'".format(version))
invoke.run("git push --tags")
invoke.run("python setup.py sdist")
invoke.run("twine upload -s dist/PyNaCl-{0}* ".format(version))
session = requests.Session()
token = getpass.getpass("Input the Jenkins token: ")
response = session.post(
"{0}/build".format(JENKINS_URL),
params={
"cause": "Building wheels for {0}".format(version),
"token": token
}
)
response.raise_for_status()
wait_for_build_completed(session)
paths = download_artifacts(session)
invoke.run("twine upload {0}".format(" ".join(paths))) | [
"def",
"release",
"(",
"ctx",
",",
"version",
")",
":",
"invoke",
".",
"run",
"(",
"\"git tag -s {0} -m '{0} release'\"",
".",
"format",
"(",
"version",
")",
")",
"invoke",
".",
"run",
"(",
"\"git push --tags\"",
")",
"invoke",
".",
"run",
"(",
"\"python set... | ``version`` should be a string like '0.4' or '1.0'. | [
"version",
"should",
"be",
"a",
"string",
"like",
"0",
".",
"4",
"or",
"1",
".",
"0",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/tasks.py#L99-L123 |
228,509 | pyca/pynacl | src/nacl/bindings/randombytes.py | randombytes | def randombytes(size):
"""
Returns ``size`` number of random bytes from a cryptographically secure
random source.
:param size: int
:rtype: bytes
"""
buf = ffi.new("unsigned char[]", size)
lib.randombytes(buf, size)
return ffi.buffer(buf, size)[:] | python | def randombytes(size):
buf = ffi.new("unsigned char[]", size)
lib.randombytes(buf, size)
return ffi.buffer(buf, size)[:] | [
"def",
"randombytes",
"(",
"size",
")",
":",
"buf",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"size",
")",
"lib",
".",
"randombytes",
"(",
"buf",
",",
"size",
")",
"return",
"ffi",
".",
"buffer",
"(",
"buf",
",",
"size",
")",
"[",
":... | Returns ``size`` number of random bytes from a cryptographically secure
random source.
:param size: int
:rtype: bytes | [
"Returns",
"size",
"number",
"of",
"random",
"bytes",
"from",
"a",
"cryptographically",
"secure",
"random",
"source",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/randombytes.py#L20-L30 |
228,510 | pyca/pynacl | src/nacl/bindings/crypto_scalarmult.py | crypto_scalarmult_base | def crypto_scalarmult_base(n):
"""
Computes and returns the scalar product of a standard group element and an
integer ``n``.
:param n: bytes
:rtype: bytes
"""
q = ffi.new("unsigned char[]", crypto_scalarmult_BYTES)
rc = lib.crypto_scalarmult_base(q, n)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(q, crypto_scalarmult_SCALARBYTES)[:] | python | def crypto_scalarmult_base(n):
q = ffi.new("unsigned char[]", crypto_scalarmult_BYTES)
rc = lib.crypto_scalarmult_base(q, n)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(q, crypto_scalarmult_SCALARBYTES)[:] | [
"def",
"crypto_scalarmult_base",
"(",
"n",
")",
":",
"q",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"crypto_scalarmult_BYTES",
")",
"rc",
"=",
"lib",
".",
"crypto_scalarmult_base",
"(",
"q",
",",
"n",
")",
"ensure",
"(",
"rc",
"==",
"0",
"... | Computes and returns the scalar product of a standard group element and an
integer ``n``.
:param n: bytes
:rtype: bytes | [
"Computes",
"and",
"returns",
"the",
"scalar",
"product",
"of",
"a",
"standard",
"group",
"element",
"and",
"an",
"integer",
"n",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_scalarmult.py#L29-L44 |
228,511 | pyca/pynacl | src/nacl/bindings/crypto_scalarmult.py | crypto_scalarmult_ed25519_base | def crypto_scalarmult_ed25519_base(n):
"""
Computes and returns the scalar product of a standard group element and an
integer ``n`` on the edwards25519 curve.
:param n: a :py:data:`.crypto_scalarmult_ed25519_SCALARBYTES` long bytes
sequence representing a scalar
:type n: bytes
:return: a point on the edwards25519 curve, represented as a
:py:data:`.crypto_scalarmult_ed25519_BYTES` long bytes sequence
:rtype: bytes
"""
ensure(isinstance(n, bytes) and
len(n) == crypto_scalarmult_ed25519_SCALARBYTES,
'Input must be a {} long bytes sequence'.format(
'crypto_scalarmult_ed25519_SCALARBYTES'),
raising=exc.TypeError)
q = ffi.new("unsigned char[]", crypto_scalarmult_ed25519_BYTES)
rc = lib.crypto_scalarmult_ed25519_base(q, n)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(q, crypto_scalarmult_ed25519_BYTES)[:] | python | def crypto_scalarmult_ed25519_base(n):
ensure(isinstance(n, bytes) and
len(n) == crypto_scalarmult_ed25519_SCALARBYTES,
'Input must be a {} long bytes sequence'.format(
'crypto_scalarmult_ed25519_SCALARBYTES'),
raising=exc.TypeError)
q = ffi.new("unsigned char[]", crypto_scalarmult_ed25519_BYTES)
rc = lib.crypto_scalarmult_ed25519_base(q, n)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(q, crypto_scalarmult_ed25519_BYTES)[:] | [
"def",
"crypto_scalarmult_ed25519_base",
"(",
"n",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"n",
",",
"bytes",
")",
"and",
"len",
"(",
"n",
")",
"==",
"crypto_scalarmult_ed25519_SCALARBYTES",
",",
"'Input must be a {} long bytes sequence'",
".",
"format",
"(",
... | Computes and returns the scalar product of a standard group element and an
integer ``n`` on the edwards25519 curve.
:param n: a :py:data:`.crypto_scalarmult_ed25519_SCALARBYTES` long bytes
sequence representing a scalar
:type n: bytes
:return: a point on the edwards25519 curve, represented as a
:py:data:`.crypto_scalarmult_ed25519_BYTES` long bytes sequence
:rtype: bytes | [
"Computes",
"and",
"returns",
"the",
"scalar",
"product",
"of",
"a",
"standard",
"group",
"element",
"and",
"an",
"integer",
"n",
"on",
"the",
"edwards25519",
"curve",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_scalarmult.py#L66-L91 |
228,512 | pyca/pynacl | src/nacl/bindings/crypto_pwhash.py | nacl_bindings_pick_scrypt_params | def nacl_bindings_pick_scrypt_params(opslimit, memlimit):
"""Python implementation of libsodium's pickparams"""
if opslimit < 32768:
opslimit = 32768
r = 8
if opslimit < (memlimit // 32):
p = 1
maxn = opslimit // (4 * r)
for n_log2 in range(1, 63): # pragma: no branch
if (2 ** n_log2) > (maxn // 2):
break
else:
maxn = memlimit // (r * 128)
for n_log2 in range(1, 63): # pragma: no branch
if (2 ** n_log2) > maxn // 2:
break
maxrp = (opslimit // 4) // (2 ** n_log2)
if maxrp > 0x3fffffff: # pragma: no cover
maxrp = 0x3fffffff
p = maxrp // r
return n_log2, r, p | python | def nacl_bindings_pick_scrypt_params(opslimit, memlimit):
if opslimit < 32768:
opslimit = 32768
r = 8
if opslimit < (memlimit // 32):
p = 1
maxn = opslimit // (4 * r)
for n_log2 in range(1, 63): # pragma: no branch
if (2 ** n_log2) > (maxn // 2):
break
else:
maxn = memlimit // (r * 128)
for n_log2 in range(1, 63): # pragma: no branch
if (2 ** n_log2) > maxn // 2:
break
maxrp = (opslimit // 4) // (2 ** n_log2)
if maxrp > 0x3fffffff: # pragma: no cover
maxrp = 0x3fffffff
p = maxrp // r
return n_log2, r, p | [
"def",
"nacl_bindings_pick_scrypt_params",
"(",
"opslimit",
",",
"memlimit",
")",
":",
"if",
"opslimit",
"<",
"32768",
":",
"opslimit",
"=",
"32768",
"r",
"=",
"8",
"if",
"opslimit",
"<",
"(",
"memlimit",
"//",
"32",
")",
":",
"p",
"=",
"1",
"maxn",
"=... | Python implementation of libsodium's pickparams | [
"Python",
"implementation",
"of",
"libsodium",
"s",
"pickparams"
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_pwhash.py#L182-L209 |
228,513 | pyca/pynacl | src/nacl/bindings/crypto_pwhash.py | crypto_pwhash_scryptsalsa208sha256_ll | def crypto_pwhash_scryptsalsa208sha256_ll(passwd, salt, n, r, p, dklen=64,
maxmem=SCRYPT_MAX_MEM):
"""
Derive a cryptographic key using the ``passwd`` and ``salt``
given as input.
The work factor can be tuned by by picking different
values for the parameters
:param bytes passwd:
:param bytes salt:
:param bytes salt: *must* be *exactly* :py:const:`.SALTBYTES` long
:param int dklen:
:param int opslimit:
:param int n:
:param int r: block size,
:param int p: the parallelism factor
:param int maxmem: the maximum available memory available for scrypt's
operations
:rtype: bytes
"""
ensure(isinstance(n, integer_types),
raising=TypeError)
ensure(isinstance(r, integer_types),
raising=TypeError)
ensure(isinstance(p, integer_types),
raising=TypeError)
ensure(isinstance(passwd, bytes),
raising=TypeError)
ensure(isinstance(salt, bytes),
raising=TypeError)
_check_memory_occupation(n, r, p, maxmem)
buf = ffi.new("uint8_t[]", dklen)
ret = lib.crypto_pwhash_scryptsalsa208sha256_ll(passwd, len(passwd),
salt, len(salt),
n, r, p,
buf, dklen)
ensure(ret == 0, 'Unexpected failure in key derivation',
raising=exc.RuntimeError)
return ffi.buffer(ffi.cast("char *", buf), dklen)[:] | python | def crypto_pwhash_scryptsalsa208sha256_ll(passwd, salt, n, r, p, dklen=64,
maxmem=SCRYPT_MAX_MEM):
ensure(isinstance(n, integer_types),
raising=TypeError)
ensure(isinstance(r, integer_types),
raising=TypeError)
ensure(isinstance(p, integer_types),
raising=TypeError)
ensure(isinstance(passwd, bytes),
raising=TypeError)
ensure(isinstance(salt, bytes),
raising=TypeError)
_check_memory_occupation(n, r, p, maxmem)
buf = ffi.new("uint8_t[]", dklen)
ret = lib.crypto_pwhash_scryptsalsa208sha256_ll(passwd, len(passwd),
salt, len(salt),
n, r, p,
buf, dklen)
ensure(ret == 0, 'Unexpected failure in key derivation',
raising=exc.RuntimeError)
return ffi.buffer(ffi.cast("char *", buf), dklen)[:] | [
"def",
"crypto_pwhash_scryptsalsa208sha256_ll",
"(",
"passwd",
",",
"salt",
",",
"n",
",",
"r",
",",
"p",
",",
"dklen",
"=",
"64",
",",
"maxmem",
"=",
"SCRYPT_MAX_MEM",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"n",
",",
"integer_types",
")",
",",
"rai... | Derive a cryptographic key using the ``passwd`` and ``salt``
given as input.
The work factor can be tuned by by picking different
values for the parameters
:param bytes passwd:
:param bytes salt:
:param bytes salt: *must* be *exactly* :py:const:`.SALTBYTES` long
:param int dklen:
:param int opslimit:
:param int n:
:param int r: block size,
:param int p: the parallelism factor
:param int maxmem: the maximum available memory available for scrypt's
operations
:rtype: bytes | [
"Derive",
"a",
"cryptographic",
"key",
"using",
"the",
"passwd",
"and",
"salt",
"given",
"as",
"input",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_pwhash.py#L212-L257 |
228,514 | pyca/pynacl | src/nacl/bindings/crypto_pwhash.py | crypto_pwhash_scryptsalsa208sha256_str | def crypto_pwhash_scryptsalsa208sha256_str(
passwd, opslimit=SCRYPT_OPSLIMIT_INTERACTIVE,
memlimit=SCRYPT_MEMLIMIT_INTERACTIVE):
"""
Derive a cryptographic key using the ``passwd`` and ``salt``
given as input, returning a string representation which includes
the salt and the tuning parameters.
The returned string can be directly stored as a password hash.
See :py:func:`.crypto_pwhash_scryptsalsa208sha256` for a short
discussion about ``opslimit`` and ``memlimit`` values.
:param bytes passwd:
:param int opslimit:
:param int memlimit:
:return: serialized key hash, including salt and tuning parameters
:rtype: bytes
"""
buf = ffi.new("char[]", SCRYPT_STRBYTES)
ret = lib.crypto_pwhash_scryptsalsa208sha256_str(buf, passwd,
len(passwd),
opslimit,
memlimit)
ensure(ret == 0, 'Unexpected failure in password hashing',
raising=exc.RuntimeError)
return ffi.string(buf) | python | def crypto_pwhash_scryptsalsa208sha256_str(
passwd, opslimit=SCRYPT_OPSLIMIT_INTERACTIVE,
memlimit=SCRYPT_MEMLIMIT_INTERACTIVE):
buf = ffi.new("char[]", SCRYPT_STRBYTES)
ret = lib.crypto_pwhash_scryptsalsa208sha256_str(buf, passwd,
len(passwd),
opslimit,
memlimit)
ensure(ret == 0, 'Unexpected failure in password hashing',
raising=exc.RuntimeError)
return ffi.string(buf) | [
"def",
"crypto_pwhash_scryptsalsa208sha256_str",
"(",
"passwd",
",",
"opslimit",
"=",
"SCRYPT_OPSLIMIT_INTERACTIVE",
",",
"memlimit",
"=",
"SCRYPT_MEMLIMIT_INTERACTIVE",
")",
":",
"buf",
"=",
"ffi",
".",
"new",
"(",
"\"char[]\"",
",",
"SCRYPT_STRBYTES",
")",
"ret",
... | Derive a cryptographic key using the ``passwd`` and ``salt``
given as input, returning a string representation which includes
the salt and the tuning parameters.
The returned string can be directly stored as a password hash.
See :py:func:`.crypto_pwhash_scryptsalsa208sha256` for a short
discussion about ``opslimit`` and ``memlimit`` values.
:param bytes passwd:
:param int opslimit:
:param int memlimit:
:return: serialized key hash, including salt and tuning parameters
:rtype: bytes | [
"Derive",
"a",
"cryptographic",
"key",
"using",
"the",
"passwd",
"and",
"salt",
"given",
"as",
"input",
"returning",
"a",
"string",
"representation",
"which",
"includes",
"the",
"salt",
"and",
"the",
"tuning",
"parameters",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_pwhash.py#L260-L289 |
228,515 | pyca/pynacl | src/nacl/bindings/crypto_pwhash.py | crypto_pwhash_scryptsalsa208sha256_str_verify | def crypto_pwhash_scryptsalsa208sha256_str_verify(passwd_hash, passwd):
"""
Verifies the ``passwd`` against the ``passwd_hash`` that was generated.
Returns True or False depending on the success
:param passwd_hash: bytes
:param passwd: bytes
:rtype: boolean
"""
ensure(len(passwd_hash) == SCRYPT_STRBYTES - 1, 'Invalid password hash',
raising=exc.ValueError)
ret = lib.crypto_pwhash_scryptsalsa208sha256_str_verify(passwd_hash,
passwd,
len(passwd))
ensure(ret == 0,
"Wrong password",
raising=exc.InvalidkeyError)
# all went well, therefore:
return True | python | def crypto_pwhash_scryptsalsa208sha256_str_verify(passwd_hash, passwd):
ensure(len(passwd_hash) == SCRYPT_STRBYTES - 1, 'Invalid password hash',
raising=exc.ValueError)
ret = lib.crypto_pwhash_scryptsalsa208sha256_str_verify(passwd_hash,
passwd,
len(passwd))
ensure(ret == 0,
"Wrong password",
raising=exc.InvalidkeyError)
# all went well, therefore:
return True | [
"def",
"crypto_pwhash_scryptsalsa208sha256_str_verify",
"(",
"passwd_hash",
",",
"passwd",
")",
":",
"ensure",
"(",
"len",
"(",
"passwd_hash",
")",
"==",
"SCRYPT_STRBYTES",
"-",
"1",
",",
"'Invalid password hash'",
",",
"raising",
"=",
"exc",
".",
"ValueError",
")... | Verifies the ``passwd`` against the ``passwd_hash`` that was generated.
Returns True or False depending on the success
:param passwd_hash: bytes
:param passwd: bytes
:rtype: boolean | [
"Verifies",
"the",
"passwd",
"against",
"the",
"passwd_hash",
"that",
"was",
"generated",
".",
"Returns",
"True",
"or",
"False",
"depending",
"on",
"the",
"success"
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_pwhash.py#L292-L312 |
228,516 | pyca/pynacl | src/nacl/bindings/crypto_pwhash.py | crypto_pwhash_alg | def crypto_pwhash_alg(outlen, passwd, salt, opslimit, memlimit, alg):
"""
Derive a raw cryptographic key using the ``passwd`` and the ``salt``
given as input to the ``alg`` algorithm.
:param outlen: the length of the derived key
:type outlen: int
:param passwd: The input password
:type passwd: bytes
:param opslimit: computational cost
:type opslimit: int
:param memlimit: memory cost
:type memlimit: int
:param alg: algorithm identifier
:type alg: int
:return: derived key
:rtype: bytes
"""
ensure(isinstance(outlen, integer_types),
raising=exc.TypeError)
ensure(isinstance(opslimit, integer_types),
raising=exc.TypeError)
ensure(isinstance(memlimit, integer_types),
raising=exc.TypeError)
ensure(isinstance(alg, integer_types),
raising=exc.TypeError)
ensure(isinstance(passwd, bytes),
raising=exc.TypeError)
if len(salt) != crypto_pwhash_SALTBYTES:
raise exc.ValueError("salt must be exactly {0} bytes long".format(
crypto_pwhash_SALTBYTES))
if outlen < crypto_pwhash_BYTES_MIN:
raise exc.ValueError(
'derived key must be at least {0} bytes long'.format(
crypto_pwhash_BYTES_MIN))
elif outlen > crypto_pwhash_BYTES_MAX:
raise exc.ValueError(
'derived key must be at most {0} bytes long'.format(
crypto_pwhash_BYTES_MAX))
_check_argon2_limits_alg(opslimit, memlimit, alg)
outbuf = ffi.new("unsigned char[]", outlen)
ret = lib.crypto_pwhash(outbuf, outlen, passwd, len(passwd),
salt, opslimit, memlimit, alg)
ensure(ret == 0, 'Unexpected failure in key derivation',
raising=exc.RuntimeError)
return ffi.buffer(outbuf, outlen)[:] | python | def crypto_pwhash_alg(outlen, passwd, salt, opslimit, memlimit, alg):
ensure(isinstance(outlen, integer_types),
raising=exc.TypeError)
ensure(isinstance(opslimit, integer_types),
raising=exc.TypeError)
ensure(isinstance(memlimit, integer_types),
raising=exc.TypeError)
ensure(isinstance(alg, integer_types),
raising=exc.TypeError)
ensure(isinstance(passwd, bytes),
raising=exc.TypeError)
if len(salt) != crypto_pwhash_SALTBYTES:
raise exc.ValueError("salt must be exactly {0} bytes long".format(
crypto_pwhash_SALTBYTES))
if outlen < crypto_pwhash_BYTES_MIN:
raise exc.ValueError(
'derived key must be at least {0} bytes long'.format(
crypto_pwhash_BYTES_MIN))
elif outlen > crypto_pwhash_BYTES_MAX:
raise exc.ValueError(
'derived key must be at most {0} bytes long'.format(
crypto_pwhash_BYTES_MAX))
_check_argon2_limits_alg(opslimit, memlimit, alg)
outbuf = ffi.new("unsigned char[]", outlen)
ret = lib.crypto_pwhash(outbuf, outlen, passwd, len(passwd),
salt, opslimit, memlimit, alg)
ensure(ret == 0, 'Unexpected failure in key derivation',
raising=exc.RuntimeError)
return ffi.buffer(outbuf, outlen)[:] | [
"def",
"crypto_pwhash_alg",
"(",
"outlen",
",",
"passwd",
",",
"salt",
",",
"opslimit",
",",
"memlimit",
",",
"alg",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"outlen",
",",
"integer_types",
")",
",",
"raising",
"=",
"exc",
".",
"TypeError",
")",
"ensu... | Derive a raw cryptographic key using the ``passwd`` and the ``salt``
given as input to the ``alg`` algorithm.
:param outlen: the length of the derived key
:type outlen: int
:param passwd: The input password
:type passwd: bytes
:param opslimit: computational cost
:type opslimit: int
:param memlimit: memory cost
:type memlimit: int
:param alg: algorithm identifier
:type alg: int
:return: derived key
:rtype: bytes | [
"Derive",
"a",
"raw",
"cryptographic",
"key",
"using",
"the",
"passwd",
"and",
"the",
"salt",
"given",
"as",
"input",
"to",
"the",
"alg",
"algorithm",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_pwhash.py#L348-L401 |
228,517 | pyca/pynacl | src/nacl/bindings/crypto_pwhash.py | crypto_pwhash_str_alg | def crypto_pwhash_str_alg(passwd, opslimit, memlimit, alg):
"""
Derive a cryptographic key using the ``passwd`` given as input
and a random ``salt``, returning a string representation which
includes the salt, the tuning parameters and the used algorithm.
:param passwd: The input password
:type passwd: bytes
:param opslimit: computational cost
:type opslimit: int
:param memlimit: memory cost
:type memlimit: int
:param alg: The algorithm to use
:type alg: int
:return: serialized derived key and parameters
:rtype: bytes
"""
ensure(isinstance(opslimit, integer_types),
raising=TypeError)
ensure(isinstance(memlimit, integer_types),
raising=TypeError)
ensure(isinstance(passwd, bytes),
raising=TypeError)
_check_argon2_limits_alg(opslimit, memlimit, alg)
outbuf = ffi.new("char[]", 128)
ret = lib.crypto_pwhash_str_alg(outbuf, passwd, len(passwd),
opslimit, memlimit, alg)
ensure(ret == 0, 'Unexpected failure in key derivation',
raising=exc.RuntimeError)
return ffi.string(outbuf) | python | def crypto_pwhash_str_alg(passwd, opslimit, memlimit, alg):
ensure(isinstance(opslimit, integer_types),
raising=TypeError)
ensure(isinstance(memlimit, integer_types),
raising=TypeError)
ensure(isinstance(passwd, bytes),
raising=TypeError)
_check_argon2_limits_alg(opslimit, memlimit, alg)
outbuf = ffi.new("char[]", 128)
ret = lib.crypto_pwhash_str_alg(outbuf, passwd, len(passwd),
opslimit, memlimit, alg)
ensure(ret == 0, 'Unexpected failure in key derivation',
raising=exc.RuntimeError)
return ffi.string(outbuf) | [
"def",
"crypto_pwhash_str_alg",
"(",
"passwd",
",",
"opslimit",
",",
"memlimit",
",",
"alg",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"opslimit",
",",
"integer_types",
")",
",",
"raising",
"=",
"TypeError",
")",
"ensure",
"(",
"isinstance",
"(",
"memlimit... | Derive a cryptographic key using the ``passwd`` given as input
and a random ``salt``, returning a string representation which
includes the salt, the tuning parameters and the used algorithm.
:param passwd: The input password
:type passwd: bytes
:param opslimit: computational cost
:type opslimit: int
:param memlimit: memory cost
:type memlimit: int
:param alg: The algorithm to use
:type alg: int
:return: serialized derived key and parameters
:rtype: bytes | [
"Derive",
"a",
"cryptographic",
"key",
"using",
"the",
"passwd",
"given",
"as",
"input",
"and",
"a",
"random",
"salt",
"returning",
"a",
"string",
"representation",
"which",
"includes",
"the",
"salt",
"the",
"tuning",
"parameters",
"and",
"the",
"used",
"algor... | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_pwhash.py#L404-L438 |
228,518 | pyca/pynacl | src/nacl/bindings/crypto_pwhash.py | crypto_pwhash_str_verify | def crypto_pwhash_str_verify(passwd_hash, passwd):
"""
Verifies the ``passwd`` against a given password hash.
Returns True on success, raises InvalidkeyError on failure
:param passwd_hash: saved password hash
:type passwd_hash: bytes
:param passwd: password to be checked
:type passwd: bytes
:return: success
:rtype: boolean
"""
ensure(isinstance(passwd_hash, bytes),
raising=TypeError)
ensure(isinstance(passwd, bytes),
raising=TypeError)
ensure(len(passwd_hash) <= 127,
"Hash must be at most 127 bytes long",
raising=exc.ValueError)
ret = lib.crypto_pwhash_str_verify(passwd_hash, passwd, len(passwd))
ensure(ret == 0,
"Wrong password",
raising=exc.InvalidkeyError)
# all went well, therefore:
return True | python | def crypto_pwhash_str_verify(passwd_hash, passwd):
ensure(isinstance(passwd_hash, bytes),
raising=TypeError)
ensure(isinstance(passwd, bytes),
raising=TypeError)
ensure(len(passwd_hash) <= 127,
"Hash must be at most 127 bytes long",
raising=exc.ValueError)
ret = lib.crypto_pwhash_str_verify(passwd_hash, passwd, len(passwd))
ensure(ret == 0,
"Wrong password",
raising=exc.InvalidkeyError)
# all went well, therefore:
return True | [
"def",
"crypto_pwhash_str_verify",
"(",
"passwd_hash",
",",
"passwd",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"passwd_hash",
",",
"bytes",
")",
",",
"raising",
"=",
"TypeError",
")",
"ensure",
"(",
"isinstance",
"(",
"passwd",
",",
"bytes",
")",
",",
"... | Verifies the ``passwd`` against a given password hash.
Returns True on success, raises InvalidkeyError on failure
:param passwd_hash: saved password hash
:type passwd_hash: bytes
:param passwd: password to be checked
:type passwd: bytes
:return: success
:rtype: boolean | [
"Verifies",
"the",
"passwd",
"against",
"a",
"given",
"password",
"hash",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_pwhash.py#L441-L467 |
228,519 | pyca/pynacl | src/nacl/bindings/crypto_aead.py | crypto_aead_chacha20poly1305_ietf_encrypt | def crypto_aead_chacha20poly1305_ietf_encrypt(message, aad, nonce, key):
"""
Encrypt the given ``message`` using the IETF ratified chacha20poly1305
construction described in RFC7539.
:param message:
:type message: bytes
:param aad:
:type aad: bytes
:param nonce:
:type nonce: bytes
:param key:
:type key: bytes
:return: authenticated ciphertext
:rtype: bytes
"""
ensure(isinstance(message, bytes), 'Input message type must be bytes',
raising=exc.TypeError)
mlen = len(message)
ensure(mlen <= crypto_aead_chacha20poly1305_ietf_MESSAGEBYTES_MAX,
'Message must be at most {0} bytes long'.format(
crypto_aead_chacha20poly1305_ietf_MESSAGEBYTES_MAX),
raising=exc.ValueError)
ensure(isinstance(aad, bytes) or (aad is None),
'Additional data must be bytes or None',
raising=exc.TypeError)
ensure(isinstance(nonce, bytes) and
len(nonce) == crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
'Nonce must be a {0} bytes long bytes sequence'.format(
crypto_aead_chacha20poly1305_ietf_NPUBBYTES),
raising=exc.TypeError)
ensure(isinstance(key, bytes) and
len(key) == crypto_aead_chacha20poly1305_ietf_KEYBYTES,
'Key must be a {0} bytes long bytes sequence'.format(
crypto_aead_chacha20poly1305_ietf_KEYBYTES),
raising=exc.TypeError)
if aad:
_aad = aad
aalen = len(aad)
else:
_aad = ffi.NULL
aalen = 0
mxout = mlen + crypto_aead_chacha20poly1305_ietf_ABYTES
clen = ffi.new("unsigned long long *")
ciphertext = ffi.new("unsigned char[]", mxout)
res = lib.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext,
clen,
message,
mlen,
_aad,
aalen,
ffi.NULL,
nonce,
key)
ensure(res == 0, "Encryption failed.", raising=exc.CryptoError)
return ffi.buffer(ciphertext, clen[0])[:] | python | def crypto_aead_chacha20poly1305_ietf_encrypt(message, aad, nonce, key):
ensure(isinstance(message, bytes), 'Input message type must be bytes',
raising=exc.TypeError)
mlen = len(message)
ensure(mlen <= crypto_aead_chacha20poly1305_ietf_MESSAGEBYTES_MAX,
'Message must be at most {0} bytes long'.format(
crypto_aead_chacha20poly1305_ietf_MESSAGEBYTES_MAX),
raising=exc.ValueError)
ensure(isinstance(aad, bytes) or (aad is None),
'Additional data must be bytes or None',
raising=exc.TypeError)
ensure(isinstance(nonce, bytes) and
len(nonce) == crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
'Nonce must be a {0} bytes long bytes sequence'.format(
crypto_aead_chacha20poly1305_ietf_NPUBBYTES),
raising=exc.TypeError)
ensure(isinstance(key, bytes) and
len(key) == crypto_aead_chacha20poly1305_ietf_KEYBYTES,
'Key must be a {0} bytes long bytes sequence'.format(
crypto_aead_chacha20poly1305_ietf_KEYBYTES),
raising=exc.TypeError)
if aad:
_aad = aad
aalen = len(aad)
else:
_aad = ffi.NULL
aalen = 0
mxout = mlen + crypto_aead_chacha20poly1305_ietf_ABYTES
clen = ffi.new("unsigned long long *")
ciphertext = ffi.new("unsigned char[]", mxout)
res = lib.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext,
clen,
message,
mlen,
_aad,
aalen,
ffi.NULL,
nonce,
key)
ensure(res == 0, "Encryption failed.", raising=exc.CryptoError)
return ffi.buffer(ciphertext, clen[0])[:] | [
"def",
"crypto_aead_chacha20poly1305_ietf_encrypt",
"(",
"message",
",",
"aad",
",",
"nonce",
",",
"key",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"message",
",",
"bytes",
")",
",",
"'Input message type must be bytes'",
",",
"raising",
"=",
"exc",
".",
"TypeE... | Encrypt the given ``message`` using the IETF ratified chacha20poly1305
construction described in RFC7539.
:param message:
:type message: bytes
:param aad:
:type aad: bytes
:param nonce:
:type nonce: bytes
:param key:
:type key: bytes
:return: authenticated ciphertext
:rtype: bytes | [
"Encrypt",
"the",
"given",
"message",
"using",
"the",
"IETF",
"ratified",
"chacha20poly1305",
"construction",
"described",
"in",
"RFC7539",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_aead.py#L70-L136 |
228,520 | pyca/pynacl | src/nacl/bindings/crypto_aead.py | crypto_aead_chacha20poly1305_encrypt | def crypto_aead_chacha20poly1305_encrypt(message, aad, nonce, key):
"""
Encrypt the given ``message`` using the "legacy" construction
described in draft-agl-tls-chacha20poly1305.
:param message:
:type message: bytes
:param aad:
:type aad: bytes
:param nonce:
:type nonce: bytes
:param key:
:type key: bytes
:return: authenticated ciphertext
:rtype: bytes
"""
ensure(isinstance(message, bytes), 'Input message type must be bytes',
raising=exc.TypeError)
mlen = len(message)
ensure(mlen <= crypto_aead_chacha20poly1305_MESSAGEBYTES_MAX,
'Message must be at most {0} bytes long'.format(
crypto_aead_chacha20poly1305_MESSAGEBYTES_MAX),
raising=exc.ValueError)
ensure(isinstance(aad, bytes) or (aad is None),
'Additional data must be bytes or None',
raising=exc.TypeError)
ensure(isinstance(nonce, bytes) and
len(nonce) == crypto_aead_chacha20poly1305_NPUBBYTES,
'Nonce must be a {0} bytes long bytes sequence'.format(
crypto_aead_chacha20poly1305_NPUBBYTES),
raising=exc.TypeError)
ensure(isinstance(key, bytes) and
len(key) == crypto_aead_chacha20poly1305_KEYBYTES,
'Key must be a {0} bytes long bytes sequence'.format(
crypto_aead_chacha20poly1305_KEYBYTES),
raising=exc.TypeError)
if aad:
_aad = aad
aalen = len(aad)
else:
_aad = ffi.NULL
aalen = 0
mlen = len(message)
mxout = mlen + crypto_aead_chacha20poly1305_ietf_ABYTES
clen = ffi.new("unsigned long long *")
ciphertext = ffi.new("unsigned char[]", mxout)
res = lib.crypto_aead_chacha20poly1305_encrypt(ciphertext,
clen,
message,
mlen,
_aad,
aalen,
ffi.NULL,
nonce,
key)
ensure(res == 0, "Encryption failed.", raising=exc.CryptoError)
return ffi.buffer(ciphertext, clen[0])[:] | python | def crypto_aead_chacha20poly1305_encrypt(message, aad, nonce, key):
ensure(isinstance(message, bytes), 'Input message type must be bytes',
raising=exc.TypeError)
mlen = len(message)
ensure(mlen <= crypto_aead_chacha20poly1305_MESSAGEBYTES_MAX,
'Message must be at most {0} bytes long'.format(
crypto_aead_chacha20poly1305_MESSAGEBYTES_MAX),
raising=exc.ValueError)
ensure(isinstance(aad, bytes) or (aad is None),
'Additional data must be bytes or None',
raising=exc.TypeError)
ensure(isinstance(nonce, bytes) and
len(nonce) == crypto_aead_chacha20poly1305_NPUBBYTES,
'Nonce must be a {0} bytes long bytes sequence'.format(
crypto_aead_chacha20poly1305_NPUBBYTES),
raising=exc.TypeError)
ensure(isinstance(key, bytes) and
len(key) == crypto_aead_chacha20poly1305_KEYBYTES,
'Key must be a {0} bytes long bytes sequence'.format(
crypto_aead_chacha20poly1305_KEYBYTES),
raising=exc.TypeError)
if aad:
_aad = aad
aalen = len(aad)
else:
_aad = ffi.NULL
aalen = 0
mlen = len(message)
mxout = mlen + crypto_aead_chacha20poly1305_ietf_ABYTES
clen = ffi.new("unsigned long long *")
ciphertext = ffi.new("unsigned char[]", mxout)
res = lib.crypto_aead_chacha20poly1305_encrypt(ciphertext,
clen,
message,
mlen,
_aad,
aalen,
ffi.NULL,
nonce,
key)
ensure(res == 0, "Encryption failed.", raising=exc.CryptoError)
return ffi.buffer(ciphertext, clen[0])[:] | [
"def",
"crypto_aead_chacha20poly1305_encrypt",
"(",
"message",
",",
"aad",
",",
"nonce",
",",
"key",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"message",
",",
"bytes",
")",
",",
"'Input message type must be bytes'",
",",
"raising",
"=",
"exc",
".",
"TypeError"... | Encrypt the given ``message`` using the "legacy" construction
described in draft-agl-tls-chacha20poly1305.
:param message:
:type message: bytes
:param aad:
:type aad: bytes
:param nonce:
:type nonce: bytes
:param key:
:type key: bytes
:return: authenticated ciphertext
:rtype: bytes | [
"Encrypt",
"the",
"given",
"message",
"using",
"the",
"legacy",
"construction",
"described",
"in",
"draft",
"-",
"agl",
"-",
"tls",
"-",
"chacha20poly1305",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_aead.py#L209-L276 |
228,521 | pyca/pynacl | src/nacl/bindings/crypto_aead.py | crypto_aead_xchacha20poly1305_ietf_encrypt | def crypto_aead_xchacha20poly1305_ietf_encrypt(message, aad, nonce, key):
"""
Encrypt the given ``message`` using the long-nonces xchacha20poly1305
construction.
:param message:
:type message: bytes
:param aad:
:type aad: bytes
:param nonce:
:type nonce: bytes
:param key:
:type key: bytes
:return: authenticated ciphertext
:rtype: bytes
"""
ensure(isinstance(message, bytes), 'Input message type must be bytes',
raising=exc.TypeError)
mlen = len(message)
ensure(mlen <= crypto_aead_xchacha20poly1305_ietf_MESSAGEBYTES_MAX,
'Message must be at most {0} bytes long'.format(
crypto_aead_xchacha20poly1305_ietf_MESSAGEBYTES_MAX),
raising=exc.ValueError)
ensure(isinstance(aad, bytes) or (aad is None),
'Additional data must be bytes or None',
raising=exc.TypeError)
ensure(isinstance(nonce, bytes) and
len(nonce) == crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
'Nonce must be a {0} bytes long bytes sequence'.format(
crypto_aead_xchacha20poly1305_ietf_NPUBBYTES),
raising=exc.TypeError)
ensure(isinstance(key, bytes) and
len(key) == crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
'Key must be a {0} bytes long bytes sequence'.format(
crypto_aead_xchacha20poly1305_ietf_KEYBYTES),
raising=exc.TypeError)
if aad:
_aad = aad
aalen = len(aad)
else:
_aad = ffi.NULL
aalen = 0
mlen = len(message)
mxout = mlen + crypto_aead_xchacha20poly1305_ietf_ABYTES
clen = ffi.new("unsigned long long *")
ciphertext = ffi.new("unsigned char[]", mxout)
res = lib.crypto_aead_xchacha20poly1305_ietf_encrypt(ciphertext,
clen,
message,
mlen,
_aad,
aalen,
ffi.NULL,
nonce,
key)
ensure(res == 0, "Encryption failed.", raising=exc.CryptoError)
return ffi.buffer(ciphertext, clen[0])[:] | python | def crypto_aead_xchacha20poly1305_ietf_encrypt(message, aad, nonce, key):
ensure(isinstance(message, bytes), 'Input message type must be bytes',
raising=exc.TypeError)
mlen = len(message)
ensure(mlen <= crypto_aead_xchacha20poly1305_ietf_MESSAGEBYTES_MAX,
'Message must be at most {0} bytes long'.format(
crypto_aead_xchacha20poly1305_ietf_MESSAGEBYTES_MAX),
raising=exc.ValueError)
ensure(isinstance(aad, bytes) or (aad is None),
'Additional data must be bytes or None',
raising=exc.TypeError)
ensure(isinstance(nonce, bytes) and
len(nonce) == crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
'Nonce must be a {0} bytes long bytes sequence'.format(
crypto_aead_xchacha20poly1305_ietf_NPUBBYTES),
raising=exc.TypeError)
ensure(isinstance(key, bytes) and
len(key) == crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
'Key must be a {0} bytes long bytes sequence'.format(
crypto_aead_xchacha20poly1305_ietf_KEYBYTES),
raising=exc.TypeError)
if aad:
_aad = aad
aalen = len(aad)
else:
_aad = ffi.NULL
aalen = 0
mlen = len(message)
mxout = mlen + crypto_aead_xchacha20poly1305_ietf_ABYTES
clen = ffi.new("unsigned long long *")
ciphertext = ffi.new("unsigned char[]", mxout)
res = lib.crypto_aead_xchacha20poly1305_ietf_encrypt(ciphertext,
clen,
message,
mlen,
_aad,
aalen,
ffi.NULL,
nonce,
key)
ensure(res == 0, "Encryption failed.", raising=exc.CryptoError)
return ffi.buffer(ciphertext, clen[0])[:] | [
"def",
"crypto_aead_xchacha20poly1305_ietf_encrypt",
"(",
"message",
",",
"aad",
",",
"nonce",
",",
"key",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"message",
",",
"bytes",
")",
",",
"'Input message type must be bytes'",
",",
"raising",
"=",
"exc",
".",
"Type... | Encrypt the given ``message`` using the long-nonces xchacha20poly1305
construction.
:param message:
:type message: bytes
:param aad:
:type aad: bytes
:param nonce:
:type nonce: bytes
:param key:
:type key: bytes
:return: authenticated ciphertext
:rtype: bytes | [
"Encrypt",
"the",
"given",
"message",
"using",
"the",
"long",
"-",
"nonces",
"xchacha20poly1305",
"construction",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_aead.py#L349-L416 |
228,522 | pyca/pynacl | src/nacl/bindings/crypto_core.py | crypto_core_ed25519_is_valid_point | def crypto_core_ed25519_is_valid_point(p):
"""
Check if ``p`` represents a point on the edwards25519 curve, in canonical
form, on the main subgroup, and that the point doesn't have a small order.
:param p: a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence
representing a point on the edwards25519 curve
:type p: bytes
:return: point validity
:rtype: bool
"""
ensure(isinstance(p, bytes) and len(p) == crypto_core_ed25519_BYTES,
'Point must be a crypto_core_ed25519_BYTES long bytes sequence',
raising=exc.TypeError)
rc = lib.crypto_core_ed25519_is_valid_point(p)
return rc == 1 | python | def crypto_core_ed25519_is_valid_point(p):
ensure(isinstance(p, bytes) and len(p) == crypto_core_ed25519_BYTES,
'Point must be a crypto_core_ed25519_BYTES long bytes sequence',
raising=exc.TypeError)
rc = lib.crypto_core_ed25519_is_valid_point(p)
return rc == 1 | [
"def",
"crypto_core_ed25519_is_valid_point",
"(",
"p",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"p",
",",
"bytes",
")",
"and",
"len",
"(",
"p",
")",
"==",
"crypto_core_ed25519_BYTES",
",",
"'Point must be a crypto_core_ed25519_BYTES long bytes sequence'",
",",
"rai... | Check if ``p`` represents a point on the edwards25519 curve, in canonical
form, on the main subgroup, and that the point doesn't have a small order.
:param p: a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence
representing a point on the edwards25519 curve
:type p: bytes
:return: point validity
:rtype: bool | [
"Check",
"if",
"p",
"represents",
"a",
"point",
"on",
"the",
"edwards25519",
"curve",
"in",
"canonical",
"form",
"on",
"the",
"main",
"subgroup",
"and",
"that",
"the",
"point",
"doesn",
"t",
"have",
"a",
"small",
"order",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_core.py#L25-L42 |
228,523 | pyca/pynacl | src/nacl/bindings/crypto_core.py | crypto_core_ed25519_add | def crypto_core_ed25519_add(p, q):
"""
Add two points on the edwards25519 curve.
:param p: a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence
representing a point on the edwards25519 curve
:type p: bytes
:param q: a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence
representing a point on the edwards25519 curve
:type q: bytes
:return: a point on the edwards25519 curve represented as
a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence
:rtype: bytes
"""
ensure(isinstance(p, bytes) and isinstance(q, bytes) and
len(p) == crypto_core_ed25519_BYTES and
len(q) == crypto_core_ed25519_BYTES,
'Each point must be a {} long bytes sequence'.format(
'crypto_core_ed25519_BYTES'),
raising=exc.TypeError)
r = ffi.new("unsigned char[]", crypto_core_ed25519_BYTES)
rc = lib.crypto_core_ed25519_add(r, p, q)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(r, crypto_core_ed25519_BYTES)[:] | python | def crypto_core_ed25519_add(p, q):
ensure(isinstance(p, bytes) and isinstance(q, bytes) and
len(p) == crypto_core_ed25519_BYTES and
len(q) == crypto_core_ed25519_BYTES,
'Each point must be a {} long bytes sequence'.format(
'crypto_core_ed25519_BYTES'),
raising=exc.TypeError)
r = ffi.new("unsigned char[]", crypto_core_ed25519_BYTES)
rc = lib.crypto_core_ed25519_add(r, p, q)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(r, crypto_core_ed25519_BYTES)[:] | [
"def",
"crypto_core_ed25519_add",
"(",
"p",
",",
"q",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"p",
",",
"bytes",
")",
"and",
"isinstance",
"(",
"q",
",",
"bytes",
")",
"and",
"len",
"(",
"p",
")",
"==",
"crypto_core_ed25519_BYTES",
"and",
"len",
"(... | Add two points on the edwards25519 curve.
:param p: a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence
representing a point on the edwards25519 curve
:type p: bytes
:param q: a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence
representing a point on the edwards25519 curve
:type q: bytes
:return: a point on the edwards25519 curve represented as
a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence
:rtype: bytes | [
"Add",
"two",
"points",
"on",
"the",
"edwards25519",
"curve",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_core.py#L45-L73 |
228,524 | pyca/pynacl | src/nacl/bindings/crypto_box.py | crypto_box_keypair | def crypto_box_keypair():
"""
Returns a randomly generated public and secret key.
:rtype: (bytes(public_key), bytes(secret_key))
"""
pk = ffi.new("unsigned char[]", crypto_box_PUBLICKEYBYTES)
sk = ffi.new("unsigned char[]", crypto_box_SECRETKEYBYTES)
rc = lib.crypto_box_keypair(pk, sk)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return (
ffi.buffer(pk, crypto_box_PUBLICKEYBYTES)[:],
ffi.buffer(sk, crypto_box_SECRETKEYBYTES)[:],
) | python | def crypto_box_keypair():
pk = ffi.new("unsigned char[]", crypto_box_PUBLICKEYBYTES)
sk = ffi.new("unsigned char[]", crypto_box_SECRETKEYBYTES)
rc = lib.crypto_box_keypair(pk, sk)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return (
ffi.buffer(pk, crypto_box_PUBLICKEYBYTES)[:],
ffi.buffer(sk, crypto_box_SECRETKEYBYTES)[:],
) | [
"def",
"crypto_box_keypair",
"(",
")",
":",
"pk",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"crypto_box_PUBLICKEYBYTES",
")",
"sk",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"crypto_box_SECRETKEYBYTES",
")",
"rc",
"=",
"lib",
".",... | Returns a randomly generated public and secret key.
:rtype: (bytes(public_key), bytes(secret_key)) | [
"Returns",
"a",
"randomly",
"generated",
"public",
"and",
"secret",
"key",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_box.py#L35-L52 |
228,525 | pyca/pynacl | src/nacl/bindings/crypto_box.py | crypto_box | def crypto_box(message, nonce, pk, sk):
"""
Encrypts and returns a message ``message`` using the secret key ``sk``,
public key ``pk``, and the nonce ``nonce``.
:param message: bytes
:param nonce: bytes
:param pk: bytes
:param sk: bytes
:rtype: bytes
"""
if len(nonce) != crypto_box_NONCEBYTES:
raise exc.ValueError("Invalid nonce size")
if len(pk) != crypto_box_PUBLICKEYBYTES:
raise exc.ValueError("Invalid public key")
if len(sk) != crypto_box_SECRETKEYBYTES:
raise exc.ValueError("Invalid secret key")
padded = (b"\x00" * crypto_box_ZEROBYTES) + message
ciphertext = ffi.new("unsigned char[]", len(padded))
rc = lib.crypto_box(ciphertext, padded, len(padded), nonce, pk, sk)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(ciphertext, len(padded))[crypto_box_BOXZEROBYTES:] | python | def crypto_box(message, nonce, pk, sk):
if len(nonce) != crypto_box_NONCEBYTES:
raise exc.ValueError("Invalid nonce size")
if len(pk) != crypto_box_PUBLICKEYBYTES:
raise exc.ValueError("Invalid public key")
if len(sk) != crypto_box_SECRETKEYBYTES:
raise exc.ValueError("Invalid secret key")
padded = (b"\x00" * crypto_box_ZEROBYTES) + message
ciphertext = ffi.new("unsigned char[]", len(padded))
rc = lib.crypto_box(ciphertext, padded, len(padded), nonce, pk, sk)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(ciphertext, len(padded))[crypto_box_BOXZEROBYTES:] | [
"def",
"crypto_box",
"(",
"message",
",",
"nonce",
",",
"pk",
",",
"sk",
")",
":",
"if",
"len",
"(",
"nonce",
")",
"!=",
"crypto_box_NONCEBYTES",
":",
"raise",
"exc",
".",
"ValueError",
"(",
"\"Invalid nonce size\"",
")",
"if",
"len",
"(",
"pk",
")",
"... | Encrypts and returns a message ``message`` using the secret key ``sk``,
public key ``pk``, and the nonce ``nonce``.
:param message: bytes
:param nonce: bytes
:param pk: bytes
:param sk: bytes
:rtype: bytes | [
"Encrypts",
"and",
"returns",
"a",
"message",
"message",
"using",
"the",
"secret",
"key",
"sk",
"public",
"key",
"pk",
"and",
"the",
"nonce",
"nonce",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_box.py#L93-L121 |
228,526 | pyca/pynacl | src/nacl/bindings/crypto_box.py | crypto_box_open | def crypto_box_open(ciphertext, nonce, pk, sk):
"""
Decrypts and returns an encrypted message ``ciphertext``, using the secret
key ``sk``, public key ``pk``, and the nonce ``nonce``.
:param ciphertext: bytes
:param nonce: bytes
:param pk: bytes
:param sk: bytes
:rtype: bytes
"""
if len(nonce) != crypto_box_NONCEBYTES:
raise exc.ValueError("Invalid nonce size")
if len(pk) != crypto_box_PUBLICKEYBYTES:
raise exc.ValueError("Invalid public key")
if len(sk) != crypto_box_SECRETKEYBYTES:
raise exc.ValueError("Invalid secret key")
padded = (b"\x00" * crypto_box_BOXZEROBYTES) + ciphertext
plaintext = ffi.new("unsigned char[]", len(padded))
res = lib.crypto_box_open(plaintext, padded, len(padded), nonce, pk, sk)
ensure(res == 0, "An error occurred trying to decrypt the message",
raising=exc.CryptoError)
return ffi.buffer(plaintext, len(padded))[crypto_box_ZEROBYTES:] | python | def crypto_box_open(ciphertext, nonce, pk, sk):
if len(nonce) != crypto_box_NONCEBYTES:
raise exc.ValueError("Invalid nonce size")
if len(pk) != crypto_box_PUBLICKEYBYTES:
raise exc.ValueError("Invalid public key")
if len(sk) != crypto_box_SECRETKEYBYTES:
raise exc.ValueError("Invalid secret key")
padded = (b"\x00" * crypto_box_BOXZEROBYTES) + ciphertext
plaintext = ffi.new("unsigned char[]", len(padded))
res = lib.crypto_box_open(plaintext, padded, len(padded), nonce, pk, sk)
ensure(res == 0, "An error occurred trying to decrypt the message",
raising=exc.CryptoError)
return ffi.buffer(plaintext, len(padded))[crypto_box_ZEROBYTES:] | [
"def",
"crypto_box_open",
"(",
"ciphertext",
",",
"nonce",
",",
"pk",
",",
"sk",
")",
":",
"if",
"len",
"(",
"nonce",
")",
"!=",
"crypto_box_NONCEBYTES",
":",
"raise",
"exc",
".",
"ValueError",
"(",
"\"Invalid nonce size\"",
")",
"if",
"len",
"(",
"pk",
... | Decrypts and returns an encrypted message ``ciphertext``, using the secret
key ``sk``, public key ``pk``, and the nonce ``nonce``.
:param ciphertext: bytes
:param nonce: bytes
:param pk: bytes
:param sk: bytes
:rtype: bytes | [
"Decrypts",
"and",
"returns",
"an",
"encrypted",
"message",
"ciphertext",
"using",
"the",
"secret",
"key",
"sk",
"public",
"key",
"pk",
"and",
"the",
"nonce",
"nonce",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_box.py#L124-L151 |
228,527 | pyca/pynacl | src/nacl/bindings/crypto_box.py | crypto_box_beforenm | def crypto_box_beforenm(pk, sk):
"""
Computes and returns the shared key for the public key ``pk`` and the
secret key ``sk``. This can be used to speed up operations where the same
set of keys is going to be used multiple times.
:param pk: bytes
:param sk: bytes
:rtype: bytes
"""
if len(pk) != crypto_box_PUBLICKEYBYTES:
raise exc.ValueError("Invalid public key")
if len(sk) != crypto_box_SECRETKEYBYTES:
raise exc.ValueError("Invalid secret key")
k = ffi.new("unsigned char[]", crypto_box_BEFORENMBYTES)
rc = lib.crypto_box_beforenm(k, pk, sk)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(k, crypto_box_BEFORENMBYTES)[:] | python | def crypto_box_beforenm(pk, sk):
if len(pk) != crypto_box_PUBLICKEYBYTES:
raise exc.ValueError("Invalid public key")
if len(sk) != crypto_box_SECRETKEYBYTES:
raise exc.ValueError("Invalid secret key")
k = ffi.new("unsigned char[]", crypto_box_BEFORENMBYTES)
rc = lib.crypto_box_beforenm(k, pk, sk)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(k, crypto_box_BEFORENMBYTES)[:] | [
"def",
"crypto_box_beforenm",
"(",
"pk",
",",
"sk",
")",
":",
"if",
"len",
"(",
"pk",
")",
"!=",
"crypto_box_PUBLICKEYBYTES",
":",
"raise",
"exc",
".",
"ValueError",
"(",
"\"Invalid public key\"",
")",
"if",
"len",
"(",
"sk",
")",
"!=",
"crypto_box_SECRETKEY... | Computes and returns the shared key for the public key ``pk`` and the
secret key ``sk``. This can be used to speed up operations where the same
set of keys is going to be used multiple times.
:param pk: bytes
:param sk: bytes
:rtype: bytes | [
"Computes",
"and",
"returns",
"the",
"shared",
"key",
"for",
"the",
"public",
"key",
"pk",
"and",
"the",
"secret",
"key",
"sk",
".",
"This",
"can",
"be",
"used",
"to",
"speed",
"up",
"operations",
"where",
"the",
"same",
"set",
"of",
"keys",
"is",
"goi... | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_box.py#L154-L177 |
228,528 | pyca/pynacl | src/nacl/bindings/crypto_box.py | crypto_box_afternm | def crypto_box_afternm(message, nonce, k):
"""
Encrypts and returns the message ``message`` using the shared key ``k`` and
the nonce ``nonce``.
:param message: bytes
:param nonce: bytes
:param k: bytes
:rtype: bytes
"""
if len(nonce) != crypto_box_NONCEBYTES:
raise exc.ValueError("Invalid nonce")
if len(k) != crypto_box_BEFORENMBYTES:
raise exc.ValueError("Invalid shared key")
padded = b"\x00" * crypto_box_ZEROBYTES + message
ciphertext = ffi.new("unsigned char[]", len(padded))
rc = lib.crypto_box_afternm(ciphertext, padded, len(padded), nonce, k)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(ciphertext, len(padded))[crypto_box_BOXZEROBYTES:] | python | def crypto_box_afternm(message, nonce, k):
if len(nonce) != crypto_box_NONCEBYTES:
raise exc.ValueError("Invalid nonce")
if len(k) != crypto_box_BEFORENMBYTES:
raise exc.ValueError("Invalid shared key")
padded = b"\x00" * crypto_box_ZEROBYTES + message
ciphertext = ffi.new("unsigned char[]", len(padded))
rc = lib.crypto_box_afternm(ciphertext, padded, len(padded), nonce, k)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(ciphertext, len(padded))[crypto_box_BOXZEROBYTES:] | [
"def",
"crypto_box_afternm",
"(",
"message",
",",
"nonce",
",",
"k",
")",
":",
"if",
"len",
"(",
"nonce",
")",
"!=",
"crypto_box_NONCEBYTES",
":",
"raise",
"exc",
".",
"ValueError",
"(",
"\"Invalid nonce\"",
")",
"if",
"len",
"(",
"k",
")",
"!=",
"crypto... | Encrypts and returns the message ``message`` using the shared key ``k`` and
the nonce ``nonce``.
:param message: bytes
:param nonce: bytes
:param k: bytes
:rtype: bytes | [
"Encrypts",
"and",
"returns",
"the",
"message",
"message",
"using",
"the",
"shared",
"key",
"k",
"and",
"the",
"nonce",
"nonce",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_box.py#L180-L204 |
228,529 | pyca/pynacl | src/nacl/bindings/crypto_box.py | crypto_box_open_afternm | def crypto_box_open_afternm(ciphertext, nonce, k):
"""
Decrypts and returns the encrypted message ``ciphertext``, using the shared
key ``k`` and the nonce ``nonce``.
:param ciphertext: bytes
:param nonce: bytes
:param k: bytes
:rtype: bytes
"""
if len(nonce) != crypto_box_NONCEBYTES:
raise exc.ValueError("Invalid nonce")
if len(k) != crypto_box_BEFORENMBYTES:
raise exc.ValueError("Invalid shared key")
padded = (b"\x00" * crypto_box_BOXZEROBYTES) + ciphertext
plaintext = ffi.new("unsigned char[]", len(padded))
res = lib.crypto_box_open_afternm(
plaintext, padded, len(padded), nonce, k)
ensure(res == 0, "An error occurred trying to decrypt the message",
raising=exc.CryptoError)
return ffi.buffer(plaintext, len(padded))[crypto_box_ZEROBYTES:] | python | def crypto_box_open_afternm(ciphertext, nonce, k):
if len(nonce) != crypto_box_NONCEBYTES:
raise exc.ValueError("Invalid nonce")
if len(k) != crypto_box_BEFORENMBYTES:
raise exc.ValueError("Invalid shared key")
padded = (b"\x00" * crypto_box_BOXZEROBYTES) + ciphertext
plaintext = ffi.new("unsigned char[]", len(padded))
res = lib.crypto_box_open_afternm(
plaintext, padded, len(padded), nonce, k)
ensure(res == 0, "An error occurred trying to decrypt the message",
raising=exc.CryptoError)
return ffi.buffer(plaintext, len(padded))[crypto_box_ZEROBYTES:] | [
"def",
"crypto_box_open_afternm",
"(",
"ciphertext",
",",
"nonce",
",",
"k",
")",
":",
"if",
"len",
"(",
"nonce",
")",
"!=",
"crypto_box_NONCEBYTES",
":",
"raise",
"exc",
".",
"ValueError",
"(",
"\"Invalid nonce\"",
")",
"if",
"len",
"(",
"k",
")",
"!=",
... | Decrypts and returns the encrypted message ``ciphertext``, using the shared
key ``k`` and the nonce ``nonce``.
:param ciphertext: bytes
:param nonce: bytes
:param k: bytes
:rtype: bytes | [
"Decrypts",
"and",
"returns",
"the",
"encrypted",
"message",
"ciphertext",
"using",
"the",
"shared",
"key",
"k",
"and",
"the",
"nonce",
"nonce",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_box.py#L207-L231 |
228,530 | pyca/pynacl | src/nacl/bindings/crypto_box.py | crypto_box_seal | def crypto_box_seal(message, pk):
"""
Encrypts and returns a message ``message`` using an ephemeral secret key
and the public key ``pk``.
The ephemeral public key, which is embedded in the sealed box, is also
used, in combination with ``pk``, to derive the nonce needed for the
underlying box construct.
:param message: bytes
:param pk: bytes
:rtype: bytes
.. versionadded:: 1.2
"""
ensure(isinstance(message, bytes),
"input message must be bytes",
raising=TypeError)
ensure(isinstance(pk, bytes),
"public key must be bytes",
raising=TypeError)
if len(pk) != crypto_box_PUBLICKEYBYTES:
raise exc.ValueError("Invalid public key")
_mlen = len(message)
_clen = crypto_box_SEALBYTES + _mlen
ciphertext = ffi.new("unsigned char[]", _clen)
rc = lib.crypto_box_seal(ciphertext, message, _mlen, pk)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(ciphertext, _clen)[:] | python | def crypto_box_seal(message, pk):
ensure(isinstance(message, bytes),
"input message must be bytes",
raising=TypeError)
ensure(isinstance(pk, bytes),
"public key must be bytes",
raising=TypeError)
if len(pk) != crypto_box_PUBLICKEYBYTES:
raise exc.ValueError("Invalid public key")
_mlen = len(message)
_clen = crypto_box_SEALBYTES + _mlen
ciphertext = ffi.new("unsigned char[]", _clen)
rc = lib.crypto_box_seal(ciphertext, message, _mlen, pk)
ensure(rc == 0,
'Unexpected library error',
raising=exc.RuntimeError)
return ffi.buffer(ciphertext, _clen)[:] | [
"def",
"crypto_box_seal",
"(",
"message",
",",
"pk",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"message",
",",
"bytes",
")",
",",
"\"input message must be bytes\"",
",",
"raising",
"=",
"TypeError",
")",
"ensure",
"(",
"isinstance",
"(",
"pk",
",",
"bytes"... | Encrypts and returns a message ``message`` using an ephemeral secret key
and the public key ``pk``.
The ephemeral public key, which is embedded in the sealed box, is also
used, in combination with ``pk``, to derive the nonce needed for the
underlying box construct.
:param message: bytes
:param pk: bytes
:rtype: bytes
.. versionadded:: 1.2 | [
"Encrypts",
"and",
"returns",
"a",
"message",
"message",
"using",
"an",
"ephemeral",
"secret",
"key",
"and",
"the",
"public",
"key",
"pk",
".",
"The",
"ephemeral",
"public",
"key",
"which",
"is",
"embedded",
"in",
"the",
"sealed",
"box",
"is",
"also",
"use... | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_box.py#L234-L269 |
228,531 | pyca/pynacl | src/nacl/bindings/crypto_box.py | crypto_box_seal_open | def crypto_box_seal_open(ciphertext, pk, sk):
"""
Decrypts and returns an encrypted message ``ciphertext``, using the
recipent's secret key ``sk`` and the sender's ephemeral public key
embedded in the sealed box. The box contruct nonce is derived from
the recipient's public key ``pk`` and the sender's public key.
:param ciphertext: bytes
:param pk: bytes
:param sk: bytes
:rtype: bytes
.. versionadded:: 1.2
"""
ensure(isinstance(ciphertext, bytes),
"input ciphertext must be bytes",
raising=TypeError)
ensure(isinstance(pk, bytes),
"public key must be bytes",
raising=TypeError)
ensure(isinstance(sk, bytes),
"secret key must be bytes",
raising=TypeError)
if len(pk) != crypto_box_PUBLICKEYBYTES:
raise exc.ValueError("Invalid public key")
if len(sk) != crypto_box_SECRETKEYBYTES:
raise exc.ValueError("Invalid secret key")
_clen = len(ciphertext)
ensure(_clen >= crypto_box_SEALBYTES,
("Input cyphertext must be "
"at least {} long").format(crypto_box_SEALBYTES),
raising=exc.TypeError)
_mlen = _clen - crypto_box_SEALBYTES
# zero-length malloc results are implementation.dependent
plaintext = ffi.new("unsigned char[]", max(1, _mlen))
res = lib.crypto_box_seal_open(plaintext, ciphertext, _clen, pk, sk)
ensure(res == 0, "An error occurred trying to decrypt the message",
raising=exc.CryptoError)
return ffi.buffer(plaintext, _mlen)[:] | python | def crypto_box_seal_open(ciphertext, pk, sk):
ensure(isinstance(ciphertext, bytes),
"input ciphertext must be bytes",
raising=TypeError)
ensure(isinstance(pk, bytes),
"public key must be bytes",
raising=TypeError)
ensure(isinstance(sk, bytes),
"secret key must be bytes",
raising=TypeError)
if len(pk) != crypto_box_PUBLICKEYBYTES:
raise exc.ValueError("Invalid public key")
if len(sk) != crypto_box_SECRETKEYBYTES:
raise exc.ValueError("Invalid secret key")
_clen = len(ciphertext)
ensure(_clen >= crypto_box_SEALBYTES,
("Input cyphertext must be "
"at least {} long").format(crypto_box_SEALBYTES),
raising=exc.TypeError)
_mlen = _clen - crypto_box_SEALBYTES
# zero-length malloc results are implementation.dependent
plaintext = ffi.new("unsigned char[]", max(1, _mlen))
res = lib.crypto_box_seal_open(plaintext, ciphertext, _clen, pk, sk)
ensure(res == 0, "An error occurred trying to decrypt the message",
raising=exc.CryptoError)
return ffi.buffer(plaintext, _mlen)[:] | [
"def",
"crypto_box_seal_open",
"(",
"ciphertext",
",",
"pk",
",",
"sk",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"ciphertext",
",",
"bytes",
")",
",",
"\"input ciphertext must be bytes\"",
",",
"raising",
"=",
"TypeError",
")",
"ensure",
"(",
"isinstance",
... | Decrypts and returns an encrypted message ``ciphertext``, using the
recipent's secret key ``sk`` and the sender's ephemeral public key
embedded in the sealed box. The box contruct nonce is derived from
the recipient's public key ``pk`` and the sender's public key.
:param ciphertext: bytes
:param pk: bytes
:param sk: bytes
:rtype: bytes
.. versionadded:: 1.2 | [
"Decrypts",
"and",
"returns",
"an",
"encrypted",
"message",
"ciphertext",
"using",
"the",
"recipent",
"s",
"secret",
"key",
"sk",
"and",
"the",
"sender",
"s",
"ephemeral",
"public",
"key",
"embedded",
"in",
"the",
"sealed",
"box",
".",
"The",
"box",
"contruc... | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_box.py#L272-L320 |
228,532 | pyca/pynacl | src/nacl/bindings/utils.py | sodium_memcmp | def sodium_memcmp(inp1, inp2):
"""
Compare contents of two memory regions in constant time
"""
ensure(isinstance(inp1, bytes),
raising=exc.TypeError)
ensure(isinstance(inp2, bytes),
raising=exc.TypeError)
ln = max(len(inp1), len(inp2))
buf1 = ffi.new("char []", ln)
buf2 = ffi.new("char []", ln)
ffi.memmove(buf1, inp1, len(inp1))
ffi.memmove(buf2, inp2, len(inp2))
eqL = len(inp1) == len(inp2)
eqC = lib.sodium_memcmp(buf1, buf2, ln) == 0
return eqL and eqC | python | def sodium_memcmp(inp1, inp2):
ensure(isinstance(inp1, bytes),
raising=exc.TypeError)
ensure(isinstance(inp2, bytes),
raising=exc.TypeError)
ln = max(len(inp1), len(inp2))
buf1 = ffi.new("char []", ln)
buf2 = ffi.new("char []", ln)
ffi.memmove(buf1, inp1, len(inp1))
ffi.memmove(buf2, inp2, len(inp2))
eqL = len(inp1) == len(inp2)
eqC = lib.sodium_memcmp(buf1, buf2, ln) == 0
return eqL and eqC | [
"def",
"sodium_memcmp",
"(",
"inp1",
",",
"inp2",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"inp1",
",",
"bytes",
")",
",",
"raising",
"=",
"exc",
".",
"TypeError",
")",
"ensure",
"(",
"isinstance",
"(",
"inp2",
",",
"bytes",
")",
",",
"raising",
"... | Compare contents of two memory regions in constant time | [
"Compare",
"contents",
"of",
"two",
"memory",
"regions",
"in",
"constant",
"time"
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/utils.py#L23-L43 |
228,533 | pyca/pynacl | src/nacl/bindings/utils.py | sodium_increment | def sodium_increment(inp):
"""
Increment the value of a byte-sequence interpreted
as the little-endian representation of a unsigned big integer.
:param inp: input bytes buffer
:type inp: bytes
:return: a byte-sequence representing, as a little-endian
unsigned big integer, the value ``to_int(inp)``
incremented by one.
:rtype: bytes
"""
ensure(isinstance(inp, bytes),
raising=exc.TypeError)
ln = len(inp)
buf = ffi.new("unsigned char []", ln)
ffi.memmove(buf, inp, ln)
lib.sodium_increment(buf, ln)
return ffi.buffer(buf, ln)[:] | python | def sodium_increment(inp):
ensure(isinstance(inp, bytes),
raising=exc.TypeError)
ln = len(inp)
buf = ffi.new("unsigned char []", ln)
ffi.memmove(buf, inp, ln)
lib.sodium_increment(buf, ln)
return ffi.buffer(buf, ln)[:] | [
"def",
"sodium_increment",
"(",
"inp",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"inp",
",",
"bytes",
")",
",",
"raising",
"=",
"exc",
".",
"TypeError",
")",
"ln",
"=",
"len",
"(",
"inp",
")",
"buf",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char []... | Increment the value of a byte-sequence interpreted
as the little-endian representation of a unsigned big integer.
:param inp: input bytes buffer
:type inp: bytes
:return: a byte-sequence representing, as a little-endian
unsigned big integer, the value ``to_int(inp)``
incremented by one.
:rtype: bytes | [
"Increment",
"the",
"value",
"of",
"a",
"byte",
"-",
"sequence",
"interpreted",
"as",
"the",
"little",
"-",
"endian",
"representation",
"of",
"a",
"unsigned",
"big",
"integer",
"."
] | 0df0c2c7693fa5d316846111ce510702756f5feb | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/utils.py#L97-L120 |
228,534 | PyCQA/pydocstyle | src/pydocstyle/parser.py | Definition.error_lineno | def error_lineno(self):
"""Get the line number with which to report violations."""
if isinstance(self.docstring, Docstring):
return self.docstring.start
return self.start | python | def error_lineno(self):
if isinstance(self.docstring, Docstring):
return self.docstring.start
return self.start | [
"def",
"error_lineno",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"docstring",
",",
"Docstring",
")",
":",
"return",
"self",
".",
"docstring",
".",
"start",
"return",
"self",
".",
"start"
] | Get the line number with which to report violations. | [
"Get",
"the",
"line",
"number",
"with",
"which",
"to",
"report",
"violations",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/parser.py#L74-L78 |
228,535 | PyCQA/pydocstyle | src/pydocstyle/parser.py | Definition.source | def source(self):
"""Return the source code for the definition."""
full_src = self._source[self._slice]
def is_empty_or_comment(line):
return line.strip() == '' or line.strip().startswith('#')
filtered_src = dropwhile(is_empty_or_comment, reversed(full_src))
return ''.join(reversed(list(filtered_src))) | python | def source(self):
full_src = self._source[self._slice]
def is_empty_or_comment(line):
return line.strip() == '' or line.strip().startswith('#')
filtered_src = dropwhile(is_empty_or_comment, reversed(full_src))
return ''.join(reversed(list(filtered_src))) | [
"def",
"source",
"(",
"self",
")",
":",
"full_src",
"=",
"self",
".",
"_source",
"[",
"self",
".",
"_slice",
"]",
"def",
"is_empty_or_comment",
"(",
"line",
")",
":",
"return",
"line",
".",
"strip",
"(",
")",
"==",
"''",
"or",
"line",
".",
"strip",
... | Return the source code for the definition. | [
"Return",
"the",
"source",
"code",
"for",
"the",
"definition",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/parser.py#L85-L93 |
228,536 | PyCQA/pydocstyle | src/pydocstyle/parser.py | Function.is_public | def is_public(self):
"""Return True iff this function should be considered public."""
if self.dunder_all is not None:
return self.name in self.dunder_all
else:
return not self.name.startswith('_') | python | def is_public(self):
if self.dunder_all is not None:
return self.name in self.dunder_all
else:
return not self.name.startswith('_') | [
"def",
"is_public",
"(",
"self",
")",
":",
"if",
"self",
".",
"dunder_all",
"is",
"not",
"None",
":",
"return",
"self",
".",
"name",
"in",
"self",
".",
"dunder_all",
"else",
":",
"return",
"not",
"self",
".",
"name",
".",
"startswith",
"(",
"'_'",
")... | Return True iff this function should be considered public. | [
"Return",
"True",
"iff",
"this",
"function",
"should",
"be",
"considered",
"public",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/parser.py#L131-L136 |
228,537 | PyCQA/pydocstyle | src/pydocstyle/parser.py | Parser.parse | def parse(self, filelike, filename):
"""Parse the given file-like object and return its Module object."""
self.log = log
self.source = filelike.readlines()
src = ''.join(self.source)
try:
compile(src, filename, 'exec')
except SyntaxError as error:
raise ParseError() from error
self.stream = TokenStream(StringIO(src))
self.filename = filename
self.dunder_all = None
self.dunder_all_error = None
self.future_imports = set()
self._accumulated_decorators = []
return self.parse_module() | python | def parse(self, filelike, filename):
self.log = log
self.source = filelike.readlines()
src = ''.join(self.source)
try:
compile(src, filename, 'exec')
except SyntaxError as error:
raise ParseError() from error
self.stream = TokenStream(StringIO(src))
self.filename = filename
self.dunder_all = None
self.dunder_all_error = None
self.future_imports = set()
self._accumulated_decorators = []
return self.parse_module() | [
"def",
"parse",
"(",
"self",
",",
"filelike",
",",
"filename",
")",
":",
"self",
".",
"log",
"=",
"log",
"self",
".",
"source",
"=",
"filelike",
".",
"readlines",
"(",
")",
"src",
"=",
"''",
".",
"join",
"(",
"self",
".",
"source",
")",
"try",
":... | Parse the given file-like object and return its Module object. | [
"Parse",
"the",
"given",
"file",
"-",
"like",
"object",
"and",
"return",
"its",
"Module",
"object",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/parser.py#L301-L316 |
228,538 | PyCQA/pydocstyle | src/pydocstyle/parser.py | Parser.consume | def consume(self, kind):
"""Consume one token and verify it is of the expected kind."""
next_token = self.stream.move()
if next_token.kind != kind:
raise UnexpectedTokenError(token=next_token, expected_kind=kind) | python | def consume(self, kind):
next_token = self.stream.move()
if next_token.kind != kind:
raise UnexpectedTokenError(token=next_token, expected_kind=kind) | [
"def",
"consume",
"(",
"self",
",",
"kind",
")",
":",
"next_token",
"=",
"self",
".",
"stream",
".",
"move",
"(",
")",
"if",
"next_token",
".",
"kind",
"!=",
"kind",
":",
"raise",
"UnexpectedTokenError",
"(",
"token",
"=",
"next_token",
",",
"expected_ki... | Consume one token and verify it is of the expected kind. | [
"Consume",
"one",
"token",
"and",
"verify",
"it",
"is",
"of",
"the",
"expected",
"kind",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/parser.py#L326-L330 |
228,539 | PyCQA/pydocstyle | src/pydocstyle/parser.py | Parser.parse_definition | def parse_definition(self, class_):
"""Parse a definition and return its value in a `class_` object."""
start = self.line
self.consume(tk.NAME)
name = self.current.value
self.log.debug("parsing %s '%s'", class_.__name__, name)
self.stream.move()
if self.current.kind == tk.OP and self.current.value == '(':
parenthesis_level = 0
while True:
if self.current.kind == tk.OP:
if self.current.value == '(':
parenthesis_level += 1
elif self.current.value == ')':
parenthesis_level -= 1
if parenthesis_level == 0:
break
self.stream.move()
if self.current.kind != tk.OP or self.current.value != ':':
self.leapfrog(tk.OP, value=":")
else:
self.consume(tk.OP)
if self.current.kind in (tk.NEWLINE, tk.COMMENT):
skipped_error_codes = self.parse_skip_comment()
self.leapfrog(tk.INDENT)
assert self.current.kind != tk.INDENT
docstring = self.parse_docstring()
decorators = self._accumulated_decorators
self.log.debug("current accumulated decorators: %s", decorators)
self._accumulated_decorators = []
self.log.debug("parsing nested definitions.")
children = list(self.parse_definitions(class_))
self.log.debug("finished parsing nested definitions for '%s'",
name)
end = self.line - 1
else: # one-liner definition
skipped_error_codes = ''
docstring = self.parse_docstring()
decorators = [] # TODO
children = []
end = self.line
self.leapfrog(tk.NEWLINE)
definition = class_(name, self.source, start, end,
decorators, docstring, children, None,
skipped_error_codes)
for child in definition.children:
child.parent = definition
self.log.debug("finished parsing %s '%s'. Next token is %r",
class_.__name__, name, self.current)
return definition | python | def parse_definition(self, class_):
start = self.line
self.consume(tk.NAME)
name = self.current.value
self.log.debug("parsing %s '%s'", class_.__name__, name)
self.stream.move()
if self.current.kind == tk.OP and self.current.value == '(':
parenthesis_level = 0
while True:
if self.current.kind == tk.OP:
if self.current.value == '(':
parenthesis_level += 1
elif self.current.value == ')':
parenthesis_level -= 1
if parenthesis_level == 0:
break
self.stream.move()
if self.current.kind != tk.OP or self.current.value != ':':
self.leapfrog(tk.OP, value=":")
else:
self.consume(tk.OP)
if self.current.kind in (tk.NEWLINE, tk.COMMENT):
skipped_error_codes = self.parse_skip_comment()
self.leapfrog(tk.INDENT)
assert self.current.kind != tk.INDENT
docstring = self.parse_docstring()
decorators = self._accumulated_decorators
self.log.debug("current accumulated decorators: %s", decorators)
self._accumulated_decorators = []
self.log.debug("parsing nested definitions.")
children = list(self.parse_definitions(class_))
self.log.debug("finished parsing nested definitions for '%s'",
name)
end = self.line - 1
else: # one-liner definition
skipped_error_codes = ''
docstring = self.parse_docstring()
decorators = [] # TODO
children = []
end = self.line
self.leapfrog(tk.NEWLINE)
definition = class_(name, self.source, start, end,
decorators, docstring, children, None,
skipped_error_codes)
for child in definition.children:
child.parent = definition
self.log.debug("finished parsing %s '%s'. Next token is %r",
class_.__name__, name, self.current)
return definition | [
"def",
"parse_definition",
"(",
"self",
",",
"class_",
")",
":",
"start",
"=",
"self",
".",
"line",
"self",
".",
"consume",
"(",
"tk",
".",
"NAME",
")",
"name",
"=",
"self",
".",
"current",
".",
"value",
"self",
".",
"log",
".",
"debug",
"(",
"\"pa... | Parse a definition and return its value in a `class_` object. | [
"Parse",
"a",
"definition",
"and",
"return",
"its",
"value",
"in",
"a",
"class_",
"object",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/parser.py#L511-L560 |
228,540 | PyCQA/pydocstyle | src/pydocstyle/parser.py | Parser.parse_skip_comment | def parse_skip_comment(self):
"""Parse a definition comment for noqa skips."""
skipped_error_codes = ''
if self.current.kind == tk.COMMENT:
if 'noqa: ' in self.current.value:
skipped_error_codes = ''.join(
self.current.value.split('noqa: ')[1:])
elif self.current.value.startswith('# noqa'):
skipped_error_codes = 'all'
return skipped_error_codes | python | def parse_skip_comment(self):
skipped_error_codes = ''
if self.current.kind == tk.COMMENT:
if 'noqa: ' in self.current.value:
skipped_error_codes = ''.join(
self.current.value.split('noqa: ')[1:])
elif self.current.value.startswith('# noqa'):
skipped_error_codes = 'all'
return skipped_error_codes | [
"def",
"parse_skip_comment",
"(",
"self",
")",
":",
"skipped_error_codes",
"=",
"''",
"if",
"self",
".",
"current",
".",
"kind",
"==",
"tk",
".",
"COMMENT",
":",
"if",
"'noqa: '",
"in",
"self",
".",
"current",
".",
"value",
":",
"skipped_error_codes",
"=",... | Parse a definition comment for noqa skips. | [
"Parse",
"a",
"definition",
"comment",
"for",
"noqa",
"skips",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/parser.py#L562-L571 |
228,541 | PyCQA/pydocstyle | src/pydocstyle/parser.py | Parser._parse_from_import_source | def _parse_from_import_source(self):
"""Parse the 'from x import' part in a 'from x import y' statement.
Return true iff `x` is __future__.
"""
assert self.current.value == 'from', self.current.value
self.stream.move()
is_future_import = self.current.value == '__future__'
self.stream.move()
while (self.current is not None and
self.current.kind in (tk.DOT, tk.NAME, tk.OP) and
self.current.value != 'import'):
self.stream.move()
if self.current is None or self.current.value != 'import':
return False
self.check_current(value='import')
assert self.current.value == 'import', self.current.value
self.stream.move()
return is_future_import | python | def _parse_from_import_source(self):
assert self.current.value == 'from', self.current.value
self.stream.move()
is_future_import = self.current.value == '__future__'
self.stream.move()
while (self.current is not None and
self.current.kind in (tk.DOT, tk.NAME, tk.OP) and
self.current.value != 'import'):
self.stream.move()
if self.current is None or self.current.value != 'import':
return False
self.check_current(value='import')
assert self.current.value == 'import', self.current.value
self.stream.move()
return is_future_import | [
"def",
"_parse_from_import_source",
"(",
"self",
")",
":",
"assert",
"self",
".",
"current",
".",
"value",
"==",
"'from'",
",",
"self",
".",
"current",
".",
"value",
"self",
".",
"stream",
".",
"move",
"(",
")",
"is_future_import",
"=",
"self",
".",
"cur... | Parse the 'from x import' part in a 'from x import y' statement.
Return true iff `x` is __future__. | [
"Parse",
"the",
"from",
"x",
"import",
"part",
"in",
"a",
"from",
"x",
"import",
"y",
"statement",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/parser.py#L597-L615 |
228,542 | PyCQA/pydocstyle | src/pydocstyle/cli.py | setup_stream_handlers | def setup_stream_handlers(conf):
"""Setup logging stream handlers according to the options."""
class StdoutFilter(logging.Filter):
def filter(self, record):
return record.levelno in (logging.DEBUG, logging.INFO)
log.handlers = []
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.WARNING)
stdout_handler.addFilter(StdoutFilter())
if conf.debug:
stdout_handler.setLevel(logging.DEBUG)
elif conf.verbose:
stdout_handler.setLevel(logging.INFO)
else:
stdout_handler.setLevel(logging.WARNING)
log.addHandler(stdout_handler)
stderr_handler = logging.StreamHandler(sys.stderr)
msg_format = "%(levelname)s: %(message)s"
stderr_handler.setFormatter(logging.Formatter(fmt=msg_format))
stderr_handler.setLevel(logging.WARNING)
log.addHandler(stderr_handler) | python | def setup_stream_handlers(conf):
class StdoutFilter(logging.Filter):
def filter(self, record):
return record.levelno in (logging.DEBUG, logging.INFO)
log.handlers = []
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.WARNING)
stdout_handler.addFilter(StdoutFilter())
if conf.debug:
stdout_handler.setLevel(logging.DEBUG)
elif conf.verbose:
stdout_handler.setLevel(logging.INFO)
else:
stdout_handler.setLevel(logging.WARNING)
log.addHandler(stdout_handler)
stderr_handler = logging.StreamHandler(sys.stderr)
msg_format = "%(levelname)s: %(message)s"
stderr_handler.setFormatter(logging.Formatter(fmt=msg_format))
stderr_handler.setLevel(logging.WARNING)
log.addHandler(stderr_handler) | [
"def",
"setup_stream_handlers",
"(",
"conf",
")",
":",
"class",
"StdoutFilter",
"(",
"logging",
".",
"Filter",
")",
":",
"def",
"filter",
"(",
"self",
",",
"record",
")",
":",
"return",
"record",
".",
"levelno",
"in",
"(",
"logging",
".",
"DEBUG",
",",
... | Setup logging stream handlers according to the options. | [
"Setup",
"logging",
"stream",
"handlers",
"according",
"to",
"the",
"options",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/cli.py#L73-L96 |
228,543 | PyCQA/pydocstyle | src/pydocstyle/checker.py | check | def check(filenames, select=None, ignore=None, ignore_decorators=None):
"""Generate docstring errors that exist in `filenames` iterable.
By default, the PEP-257 convention is checked. To specifically define the
set of error codes to check for, supply either `select` or `ignore` (but
not both). In either case, the parameter should be a collection of error
code strings, e.g., {'D100', 'D404'}.
When supplying `select`, only specified error codes will be reported.
When supplying `ignore`, all error codes which were not specified will be
reported.
Note that ignored error code refer to the entire set of possible
error codes, which is larger than just the PEP-257 convention. To your
convenience, you may use `pydocstyle.violations.conventions.pep257` as
a base set to add or remove errors from.
Examples
---------
>>> check(['pydocstyle.py'])
<generator object check at 0x...>
>>> check(['pydocstyle.py'], select=['D100'])
<generator object check at 0x...>
>>> check(['pydocstyle.py'], ignore=conventions.pep257 - {'D100'})
<generator object check at 0x...>
"""
if select is not None and ignore is not None:
raise IllegalConfiguration('Cannot pass both select and ignore. '
'They are mutually exclusive.')
elif select is not None:
checked_codes = select
elif ignore is not None:
checked_codes = list(set(violations.ErrorRegistry.get_error_codes()) -
set(ignore))
else:
checked_codes = violations.conventions.pep257
for filename in filenames:
log.info('Checking file %s.', filename)
try:
with tk.open(filename) as file:
source = file.read()
for error in ConventionChecker().check_source(source, filename,
ignore_decorators):
code = getattr(error, 'code', None)
if code in checked_codes:
yield error
except (EnvironmentError, AllError, ParseError) as error:
log.warning('Error in file %s: %s', filename, error)
yield error
except tk.TokenError:
yield SyntaxError('invalid syntax in file %s' % filename) | python | def check(filenames, select=None, ignore=None, ignore_decorators=None):
if select is not None and ignore is not None:
raise IllegalConfiguration('Cannot pass both select and ignore. '
'They are mutually exclusive.')
elif select is not None:
checked_codes = select
elif ignore is not None:
checked_codes = list(set(violations.ErrorRegistry.get_error_codes()) -
set(ignore))
else:
checked_codes = violations.conventions.pep257
for filename in filenames:
log.info('Checking file %s.', filename)
try:
with tk.open(filename) as file:
source = file.read()
for error in ConventionChecker().check_source(source, filename,
ignore_decorators):
code = getattr(error, 'code', None)
if code in checked_codes:
yield error
except (EnvironmentError, AllError, ParseError) as error:
log.warning('Error in file %s: %s', filename, error)
yield error
except tk.TokenError:
yield SyntaxError('invalid syntax in file %s' % filename) | [
"def",
"check",
"(",
"filenames",
",",
"select",
"=",
"None",
",",
"ignore",
"=",
"None",
",",
"ignore_decorators",
"=",
"None",
")",
":",
"if",
"select",
"is",
"not",
"None",
"and",
"ignore",
"is",
"not",
"None",
":",
"raise",
"IllegalConfiguration",
"(... | Generate docstring errors that exist in `filenames` iterable.
By default, the PEP-257 convention is checked. To specifically define the
set of error codes to check for, supply either `select` or `ignore` (but
not both). In either case, the parameter should be a collection of error
code strings, e.g., {'D100', 'D404'}.
When supplying `select`, only specified error codes will be reported.
When supplying `ignore`, all error codes which were not specified will be
reported.
Note that ignored error code refer to the entire set of possible
error codes, which is larger than just the PEP-257 convention. To your
convenience, you may use `pydocstyle.violations.conventions.pep257` as
a base set to add or remove errors from.
Examples
---------
>>> check(['pydocstyle.py'])
<generator object check at 0x...>
>>> check(['pydocstyle.py'], select=['D100'])
<generator object check at 0x...>
>>> check(['pydocstyle.py'], ignore=conventions.pep257 - {'D100'})
<generator object check at 0x...> | [
"Generate",
"docstring",
"errors",
"that",
"exist",
"in",
"filenames",
"iterable",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/checker.py#L664-L718 |
228,544 | PyCQA/pydocstyle | src/pydocstyle/checker.py | ConventionChecker._get_docstring_indent | def _get_docstring_indent(definition, docstring):
"""Return the indentation of the docstring's opening quotes."""
before_docstring, _, _ = definition.source.partition(docstring)
_, _, indent = before_docstring.rpartition('\n')
return indent | python | def _get_docstring_indent(definition, docstring):
before_docstring, _, _ = definition.source.partition(docstring)
_, _, indent = before_docstring.rpartition('\n')
return indent | [
"def",
"_get_docstring_indent",
"(",
"definition",
",",
"docstring",
")",
":",
"before_docstring",
",",
"_",
",",
"_",
"=",
"definition",
".",
"source",
".",
"partition",
"(",
"docstring",
")",
"_",
",",
"_",
",",
"indent",
"=",
"before_docstring",
".",
"r... | Return the indentation of the docstring's opening quotes. | [
"Return",
"the",
"indentation",
"of",
"the",
"docstring",
"s",
"opening",
"quotes",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/checker.py#L204-L208 |
228,545 | PyCQA/pydocstyle | src/pydocstyle/checker.py | ConventionChecker._get_leading_words | def _get_leading_words(line):
"""Return any leading set of words from `line`.
For example, if `line` is " Hello world!!!", returns "Hello world".
"""
result = re("[\w ]+").match(line.strip())
if result is not None:
return result.group() | python | def _get_leading_words(line):
result = re("[\w ]+").match(line.strip())
if result is not None:
return result.group() | [
"def",
"_get_leading_words",
"(",
"line",
")",
":",
"result",
"=",
"re",
"(",
"\"[\\w ]+\"",
")",
".",
"match",
"(",
"line",
".",
"strip",
"(",
")",
")",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
".",
"group",
"(",
")"
] | Return any leading set of words from `line`.
For example, if `line` is " Hello world!!!", returns "Hello world". | [
"Return",
"any",
"leading",
"set",
"of",
"words",
"from",
"line",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/checker.py#L426-L433 |
228,546 | PyCQA/pydocstyle | src/pydocstyle/checker.py | ConventionChecker._is_a_docstring_section | def _is_a_docstring_section(context):
"""Check if the suspected context is really a section header.
Lets have a look at the following example docstring:
'''Title.
Some part of the docstring that specifies what the function
returns. <----- Not a real section name. It has a suffix and the
previous line is not empty and does not end with
a punctuation sign.
This is another line in the docstring. It describes stuff,
but we forgot to add a blank line between it and the section name.
Parameters <-- A real section name. The previous line ends with
---------- a period, therefore it is in a new
grammatical context.
param : int
examples : list <------- Not a section - previous line doesn't end
A list of examples. with punctuation.
notes : list <---------- Not a section - there's text after the
A list of notes. colon.
Notes: <--- Suspected as a context because there's a suffix to the
----- section, but it's a colon so it's probably a mistake.
Bla.
'''
To make sure this is really a section we check these conditions:
* There's no suffix to the section name or it's just a colon AND
* The previous line is empty OR it ends with punctuation.
If one of the conditions is true, we will consider the line as
a section name.
"""
section_name_suffix = \
context.line.strip().lstrip(context.section_name.strip()).strip()
section_suffix_is_only_colon = section_name_suffix == ':'
punctuation = [',', ';', '.', '-', '\\', '/', ']', '}', ')']
prev_line_ends_with_punctuation = \
any(context.previous_line.strip().endswith(x) for x in punctuation)
this_line_looks_like_a_section_name = \
is_blank(section_name_suffix) or section_suffix_is_only_colon
prev_line_looks_like_end_of_paragraph = \
prev_line_ends_with_punctuation or is_blank(context.previous_line)
return (this_line_looks_like_a_section_name and
prev_line_looks_like_end_of_paragraph) | python | def _is_a_docstring_section(context):
section_name_suffix = \
context.line.strip().lstrip(context.section_name.strip()).strip()
section_suffix_is_only_colon = section_name_suffix == ':'
punctuation = [',', ';', '.', '-', '\\', '/', ']', '}', ')']
prev_line_ends_with_punctuation = \
any(context.previous_line.strip().endswith(x) for x in punctuation)
this_line_looks_like_a_section_name = \
is_blank(section_name_suffix) or section_suffix_is_only_colon
prev_line_looks_like_end_of_paragraph = \
prev_line_ends_with_punctuation or is_blank(context.previous_line)
return (this_line_looks_like_a_section_name and
prev_line_looks_like_end_of_paragraph) | [
"def",
"_is_a_docstring_section",
"(",
"context",
")",
":",
"section_name_suffix",
"=",
"context",
".",
"line",
".",
"strip",
"(",
")",
".",
"lstrip",
"(",
"context",
".",
"section_name",
".",
"strip",
"(",
")",
")",
".",
"strip",
"(",
")",
"section_suffix... | Check if the suspected context is really a section header.
Lets have a look at the following example docstring:
'''Title.
Some part of the docstring that specifies what the function
returns. <----- Not a real section name. It has a suffix and the
previous line is not empty and does not end with
a punctuation sign.
This is another line in the docstring. It describes stuff,
but we forgot to add a blank line between it and the section name.
Parameters <-- A real section name. The previous line ends with
---------- a period, therefore it is in a new
grammatical context.
param : int
examples : list <------- Not a section - previous line doesn't end
A list of examples. with punctuation.
notes : list <---------- Not a section - there's text after the
A list of notes. colon.
Notes: <--- Suspected as a context because there's a suffix to the
----- section, but it's a colon so it's probably a mistake.
Bla.
'''
To make sure this is really a section we check these conditions:
* There's no suffix to the section name or it's just a colon AND
* The previous line is empty OR it ends with punctuation.
If one of the conditions is true, we will consider the line as
a section name. | [
"Check",
"if",
"the",
"suspected",
"context",
"is",
"really",
"a",
"section",
"header",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/checker.py#L436-L487 |
228,547 | PyCQA/pydocstyle | src/pydocstyle/violations.py | Error.set_context | def set_context(self, definition: Definition, explanation: str) -> None:
"""Set the source code context for this error."""
self.definition = definition
self.explanation = explanation | python | def set_context(self, definition: Definition, explanation: str) -> None:
self.definition = definition
self.explanation = explanation | [
"def",
"set_context",
"(",
"self",
",",
"definition",
":",
"Definition",
",",
"explanation",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"definition",
"=",
"definition",
"self",
".",
"explanation",
"=",
"explanation"
] | Set the source code context for this error. | [
"Set",
"the",
"source",
"code",
"context",
"for",
"this",
"error",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/violations.py#L44-L47 |
228,548 | PyCQA/pydocstyle | src/pydocstyle/violations.py | Error.message | def message(self) -> str:
"""Return the message to print to the user."""
ret = '{}: {}'.format(self.code, self.short_desc)
if self.context is not None:
specific_error_msg = self.context.format(*self.parameters)
ret += ' ({})'.format(specific_error_msg)
return ret | python | def message(self) -> str:
ret = '{}: {}'.format(self.code, self.short_desc)
if self.context is not None:
specific_error_msg = self.context.format(*self.parameters)
ret += ' ({})'.format(specific_error_msg)
return ret | [
"def",
"message",
"(",
"self",
")",
"->",
"str",
":",
"ret",
"=",
"'{}: {}'",
".",
"format",
"(",
"self",
".",
"code",
",",
"self",
".",
"short_desc",
")",
"if",
"self",
".",
"context",
"is",
"not",
"None",
":",
"specific_error_msg",
"=",
"self",
"."... | Return the message to print to the user. | [
"Return",
"the",
"message",
"to",
"print",
"to",
"the",
"user",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/violations.py#L53-L59 |
228,549 | PyCQA/pydocstyle | src/pydocstyle/violations.py | Error.lines | def lines(self) -> str:
"""Return the source code lines for this error."""
if self.definition is None:
return ''
source = ''
lines = self.definition.source
offset = self.definition.start # type: ignore
lines_stripped = list(reversed(list(dropwhile(is_blank,
reversed(lines)))))
numbers_width = len(str(offset + len(lines_stripped)))
line_format = '{{:{}}}:{{}}'.format(numbers_width)
for n, line in enumerate(lines_stripped):
if line:
line = ' ' + line
source += line_format.format(n + offset, line)
if n > 5:
source += ' ...\n'
break
return source | python | def lines(self) -> str:
if self.definition is None:
return ''
source = ''
lines = self.definition.source
offset = self.definition.start # type: ignore
lines_stripped = list(reversed(list(dropwhile(is_blank,
reversed(lines)))))
numbers_width = len(str(offset + len(lines_stripped)))
line_format = '{{:{}}}:{{}}'.format(numbers_width)
for n, line in enumerate(lines_stripped):
if line:
line = ' ' + line
source += line_format.format(n + offset, line)
if n > 5:
source += ' ...\n'
break
return source | [
"def",
"lines",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"definition",
"is",
"None",
":",
"return",
"''",
"source",
"=",
"''",
"lines",
"=",
"self",
".",
"definition",
".",
"source",
"offset",
"=",
"self",
".",
"definition",
".",
"start... | Return the source code lines for this error. | [
"Return",
"the",
"source",
"code",
"lines",
"for",
"this",
"error",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/violations.py#L62-L80 |
228,550 | PyCQA/pydocstyle | src/pydocstyle/violations.py | ErrorRegistry.create_group | def create_group(cls, prefix: str, name: str) -> ErrorGroup:
"""Create a new error group and return it."""
group = cls.ErrorGroup(prefix, name)
cls.groups.append(group)
return group | python | def create_group(cls, prefix: str, name: str) -> ErrorGroup:
group = cls.ErrorGroup(prefix, name)
cls.groups.append(group)
return group | [
"def",
"create_group",
"(",
"cls",
",",
"prefix",
":",
"str",
",",
"name",
":",
"str",
")",
"->",
"ErrorGroup",
":",
"group",
"=",
"cls",
".",
"ErrorGroup",
"(",
"prefix",
",",
"name",
")",
"cls",
".",
"groups",
".",
"append",
"(",
"group",
")",
"r... | Create a new error group and return it. | [
"Create",
"a",
"new",
"error",
"group",
"and",
"return",
"it",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/violations.py#L139-L143 |
228,551 | PyCQA/pydocstyle | src/pydocstyle/violations.py | ErrorRegistry.get_error_codes | def get_error_codes(cls) -> Iterable[str]:
"""Yield all registered codes."""
for group in cls.groups:
for error in group.errors:
yield error.code | python | def get_error_codes(cls) -> Iterable[str]:
for group in cls.groups:
for error in group.errors:
yield error.code | [
"def",
"get_error_codes",
"(",
"cls",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"for",
"group",
"in",
"cls",
".",
"groups",
":",
"for",
"error",
"in",
"group",
".",
"errors",
":",
"yield",
"error",
".",
"code"
] | Yield all registered codes. | [
"Yield",
"all",
"registered",
"codes",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/violations.py#L146-L150 |
228,552 | PyCQA/pydocstyle | src/pydocstyle/violations.py | ErrorRegistry.to_rst | def to_rst(cls) -> str:
"""Output the registry as reStructuredText, for documentation."""
sep_line = '+' + 6 * '-' + '+' + '-' * 71 + '+\n'
blank_line = '|' + 78 * ' ' + '|\n'
table = ''
for group in cls.groups:
table += sep_line
table += blank_line
table += '|' + '**{}**'.format(group.name).center(78) + '|\n'
table += blank_line
for error in group.errors:
table += sep_line
table += ('|' + error.code.center(6) + '| ' +
error.short_desc.ljust(70) + '|\n')
table += sep_line
return table | python | def to_rst(cls) -> str:
sep_line = '+' + 6 * '-' + '+' + '-' * 71 + '+\n'
blank_line = '|' + 78 * ' ' + '|\n'
table = ''
for group in cls.groups:
table += sep_line
table += blank_line
table += '|' + '**{}**'.format(group.name).center(78) + '|\n'
table += blank_line
for error in group.errors:
table += sep_line
table += ('|' + error.code.center(6) + '| ' +
error.short_desc.ljust(70) + '|\n')
table += sep_line
return table | [
"def",
"to_rst",
"(",
"cls",
")",
"->",
"str",
":",
"sep_line",
"=",
"'+'",
"+",
"6",
"*",
"'-'",
"+",
"'+'",
"+",
"'-'",
"*",
"71",
"+",
"'+\\n'",
"blank_line",
"=",
"'|'",
"+",
"78",
"*",
"' '",
"+",
"'|\\n'",
"table",
"=",
"''",
"for",
"grou... | Output the registry as reStructuredText, for documentation. | [
"Output",
"the",
"registry",
"as",
"reStructuredText",
"for",
"documentation",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/violations.py#L153-L168 |
228,553 | PyCQA/pydocstyle | src/pydocstyle/config.py | check_initialized | def check_initialized(method):
"""Check that the configuration object was initialized."""
def _decorator(self, *args, **kwargs):
if self._arguments is None or self._options is None:
raise RuntimeError('using an uninitialized configuration')
return method(self, *args, **kwargs)
return _decorator | python | def check_initialized(method):
def _decorator(self, *args, **kwargs):
if self._arguments is None or self._options is None:
raise RuntimeError('using an uninitialized configuration')
return method(self, *args, **kwargs)
return _decorator | [
"def",
"check_initialized",
"(",
"method",
")",
":",
"def",
"_decorator",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_arguments",
"is",
"None",
"or",
"self",
".",
"_options",
"is",
"None",
":",
"raise",
"Run... | Check that the configuration object was initialized. | [
"Check",
"that",
"the",
"configuration",
"object",
"was",
"initialized",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L20-L26 |
228,554 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser.parse | def parse(self):
"""Parse the configuration.
If one of `BASE_ERROR_SELECTION_OPTIONS` was selected, overrides all
error codes to check and disregards any error code related
configurations from the configuration files.
"""
self._options, self._arguments = self._parse_args()
self._arguments = self._arguments or ['.']
if not self._validate_options(self._options):
raise IllegalConfiguration()
self._run_conf = self._create_run_config(self._options)
config = self._create_check_config(self._options, use_defaults=False)
self._override_by_cli = config | python | def parse(self):
self._options, self._arguments = self._parse_args()
self._arguments = self._arguments or ['.']
if not self._validate_options(self._options):
raise IllegalConfiguration()
self._run_conf = self._create_run_config(self._options)
config = self._create_check_config(self._options, use_defaults=False)
self._override_by_cli = config | [
"def",
"parse",
"(",
"self",
")",
":",
"self",
".",
"_options",
",",
"self",
".",
"_arguments",
"=",
"self",
".",
"_parse_args",
"(",
")",
"self",
".",
"_arguments",
"=",
"self",
".",
"_arguments",
"or",
"[",
"'.'",
"]",
"if",
"not",
"self",
".",
"... | Parse the configuration.
If one of `BASE_ERROR_SELECTION_OPTIONS` was selected, overrides all
error codes to check and disregards any error code related
configurations from the configuration files. | [
"Parse",
"the",
"configuration",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L104-L121 |
228,555 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser.get_files_to_check | def get_files_to_check(self):
"""Generate files and error codes to check on each one.
Walk dir trees under `self._arguments` and yield file names
that `match` under each directory that `match_dir`.
The method locates the configuration for each file name and yields a
tuple of (filename, [error_codes]).
With every discovery of a new configuration file `IllegalConfiguration`
might be raised.
"""
def _get_matches(conf):
"""Return the `match` and `match_dir` functions for `config`."""
match_func = re(conf.match + '$').match
match_dir_func = re(conf.match_dir + '$').match
return match_func, match_dir_func
def _get_ignore_decorators(conf):
"""Return the `ignore_decorators` as None or regex."""
return (re(conf.ignore_decorators) if conf.ignore_decorators
else None)
for name in self._arguments:
if os.path.isdir(name):
for root, dirs, filenames in os.walk(name):
config = self._get_config(os.path.abspath(root))
match, match_dir = _get_matches(config)
ignore_decorators = _get_ignore_decorators(config)
# Skip any dirs that do not match match_dir
dirs[:] = [d for d in dirs if match_dir(d)]
for filename in filenames:
if match(filename):
full_path = os.path.join(root, filename)
yield (full_path, list(config.checked_codes),
ignore_decorators)
else:
config = self._get_config(os.path.abspath(name))
match, _ = _get_matches(config)
ignore_decorators = _get_ignore_decorators(config)
if match(name):
yield (name, list(config.checked_codes), ignore_decorators) | python | def get_files_to_check(self):
def _get_matches(conf):
"""Return the `match` and `match_dir` functions for `config`."""
match_func = re(conf.match + '$').match
match_dir_func = re(conf.match_dir + '$').match
return match_func, match_dir_func
def _get_ignore_decorators(conf):
"""Return the `ignore_decorators` as None or regex."""
return (re(conf.ignore_decorators) if conf.ignore_decorators
else None)
for name in self._arguments:
if os.path.isdir(name):
for root, dirs, filenames in os.walk(name):
config = self._get_config(os.path.abspath(root))
match, match_dir = _get_matches(config)
ignore_decorators = _get_ignore_decorators(config)
# Skip any dirs that do not match match_dir
dirs[:] = [d for d in dirs if match_dir(d)]
for filename in filenames:
if match(filename):
full_path = os.path.join(root, filename)
yield (full_path, list(config.checked_codes),
ignore_decorators)
else:
config = self._get_config(os.path.abspath(name))
match, _ = _get_matches(config)
ignore_decorators = _get_ignore_decorators(config)
if match(name):
yield (name, list(config.checked_codes), ignore_decorators) | [
"def",
"get_files_to_check",
"(",
"self",
")",
":",
"def",
"_get_matches",
"(",
"conf",
")",
":",
"\"\"\"Return the `match` and `match_dir` functions for `config`.\"\"\"",
"match_func",
"=",
"re",
"(",
"conf",
".",
"match",
"+",
"'$'",
")",
".",
"match",
"match_dir_... | Generate files and error codes to check on each one.
Walk dir trees under `self._arguments` and yield file names
that `match` under each directory that `match_dir`.
The method locates the configuration for each file name and yields a
tuple of (filename, [error_codes]).
With every discovery of a new configuration file `IllegalConfiguration`
might be raised. | [
"Generate",
"files",
"and",
"error",
"codes",
"to",
"check",
"on",
"each",
"one",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L129-L172 |
228,556 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser._get_config_by_discovery | def _get_config_by_discovery(self, node):
"""Get a configuration for checking `node` by config discovery.
Config discovery happens when no explicit config file is specified. The
file system is searched for config files starting from the directory
containing the file being checked, and up until the root directory of
the project.
See `_get_config` for further details.
"""
path = self._get_node_dir(node)
if path in self._cache:
return self._cache[path]
config_file = self._get_config_file_in_folder(path)
if config_file is None:
parent_dir, tail = os.path.split(path)
if tail:
# No configuration file, simply take the parent's.
config = self._get_config(parent_dir)
else:
# There's no configuration file and no parent directory.
# Use the default configuration or the one given in the CLI.
config = self._create_check_config(self._options)
else:
# There's a config file! Read it and merge if necessary.
options, inherit = self._read_configuration_file(config_file)
parent_dir, tail = os.path.split(path)
if tail and inherit:
# There is a parent dir and we should try to merge.
parent_config = self._get_config(parent_dir)
config = self._merge_configuration(parent_config, options)
else:
# No need to merge or parent dir does not exist.
config = self._create_check_config(options)
return config | python | def _get_config_by_discovery(self, node):
path = self._get_node_dir(node)
if path in self._cache:
return self._cache[path]
config_file = self._get_config_file_in_folder(path)
if config_file is None:
parent_dir, tail = os.path.split(path)
if tail:
# No configuration file, simply take the parent's.
config = self._get_config(parent_dir)
else:
# There's no configuration file and no parent directory.
# Use the default configuration or the one given in the CLI.
config = self._create_check_config(self._options)
else:
# There's a config file! Read it and merge if necessary.
options, inherit = self._read_configuration_file(config_file)
parent_dir, tail = os.path.split(path)
if tail and inherit:
# There is a parent dir and we should try to merge.
parent_config = self._get_config(parent_dir)
config = self._merge_configuration(parent_config, options)
else:
# No need to merge or parent dir does not exist.
config = self._create_check_config(options)
return config | [
"def",
"_get_config_by_discovery",
"(",
"self",
",",
"node",
")",
":",
"path",
"=",
"self",
".",
"_get_node_dir",
"(",
"node",
")",
"if",
"path",
"in",
"self",
".",
"_cache",
":",
"return",
"self",
".",
"_cache",
"[",
"path",
"]",
"config_file",
"=",
"... | Get a configuration for checking `node` by config discovery.
Config discovery happens when no explicit config file is specified. The
file system is searched for config files starting from the directory
containing the file being checked, and up until the root directory of
the project.
See `_get_config` for further details. | [
"Get",
"a",
"configuration",
"for",
"checking",
"node",
"by",
"config",
"discovery",
".",
"Config",
"discovery",
"happens",
"when",
"no",
"explicit",
"config",
"file",
"is",
"specified",
".",
"The",
"file",
"system",
"is",
"searched",
"for",
"config",
"files",... | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L176-L216 |
228,557 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser._get_config | def _get_config(self, node):
"""Get and cache the run configuration for `node`.
If no configuration exists (not local and not for the parent node),
returns and caches a default configuration.
The algorithm:
-------------
* If the current directory's configuration exists in
`self._cache` - return it.
* If a configuration file does not exist in this directory:
* If the directory is not a root directory:
* Cache its configuration as this directory's and return it.
* Else:
* Cache a default configuration and return it.
* Else:
* Read the configuration file.
* If a parent directory exists AND the configuration file
allows inheritance:
* Read the parent configuration by calling this function with the
parent directory as `node`.
* Merge the parent configuration with the current one and
cache it.
* If the user has specified one of `BASE_ERROR_SELECTION_OPTIONS` in
the CLI - return the CLI configuration with the configuration match
clauses
* Set the `--add-select` and `--add-ignore` CLI configurations.
"""
if self._run_conf.config is None:
log.debug('No config file specified, discovering.')
config = self._get_config_by_discovery(node)
else:
log.debug('Using config file %r', self._run_conf.config)
if not os.path.exists(self._run_conf.config):
raise IllegalConfiguration('Configuration file {!r} specified '
'via --config was not found.'
.format(self._run_conf.config))
if None in self._cache:
return self._cache[None]
options, _ = self._read_configuration_file(self._run_conf.config)
if options is None:
log.warning('Configuration file does not contain a '
'pydocstyle section. Using default configuration.')
config = self._create_check_config(self._options)
else:
config = self._create_check_config(options)
# Make the CLI always win
final_config = {}
for attr in CheckConfiguration._fields:
cli_val = getattr(self._override_by_cli, attr)
conf_val = getattr(config, attr)
final_config[attr] = cli_val if cli_val is not None else conf_val
config = CheckConfiguration(**final_config)
self._set_add_options(config.checked_codes, self._options)
# Handle caching
if self._run_conf.config is not None:
self._cache[None] = config
else:
self._cache[self._get_node_dir(node)] = config
return config | python | def _get_config(self, node):
if self._run_conf.config is None:
log.debug('No config file specified, discovering.')
config = self._get_config_by_discovery(node)
else:
log.debug('Using config file %r', self._run_conf.config)
if not os.path.exists(self._run_conf.config):
raise IllegalConfiguration('Configuration file {!r} specified '
'via --config was not found.'
.format(self._run_conf.config))
if None in self._cache:
return self._cache[None]
options, _ = self._read_configuration_file(self._run_conf.config)
if options is None:
log.warning('Configuration file does not contain a '
'pydocstyle section. Using default configuration.')
config = self._create_check_config(self._options)
else:
config = self._create_check_config(options)
# Make the CLI always win
final_config = {}
for attr in CheckConfiguration._fields:
cli_val = getattr(self._override_by_cli, attr)
conf_val = getattr(config, attr)
final_config[attr] = cli_val if cli_val is not None else conf_val
config = CheckConfiguration(**final_config)
self._set_add_options(config.checked_codes, self._options)
# Handle caching
if self._run_conf.config is not None:
self._cache[None] = config
else:
self._cache[self._get_node_dir(node)] = config
return config | [
"def",
"_get_config",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"_run_conf",
".",
"config",
"is",
"None",
":",
"log",
".",
"debug",
"(",
"'No config file specified, discovering.'",
")",
"config",
"=",
"self",
".",
"_get_config_by_discovery",
"(",
... | Get and cache the run configuration for `node`.
If no configuration exists (not local and not for the parent node),
returns and caches a default configuration.
The algorithm:
-------------
* If the current directory's configuration exists in
`self._cache` - return it.
* If a configuration file does not exist in this directory:
* If the directory is not a root directory:
* Cache its configuration as this directory's and return it.
* Else:
* Cache a default configuration and return it.
* Else:
* Read the configuration file.
* If a parent directory exists AND the configuration file
allows inheritance:
* Read the parent configuration by calling this function with the
parent directory as `node`.
* Merge the parent configuration with the current one and
cache it.
* If the user has specified one of `BASE_ERROR_SELECTION_OPTIONS` in
the CLI - return the CLI configuration with the configuration match
clauses
* Set the `--add-select` and `--add-ignore` CLI configurations. | [
"Get",
"and",
"cache",
"the",
"run",
"configuration",
"for",
"node",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L218-L284 |
228,558 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser._get_node_dir | def _get_node_dir(node):
"""Return the absolute path of the directory of a filesystem node."""
path = os.path.abspath(node)
return path if os.path.isdir(path) else os.path.dirname(path) | python | def _get_node_dir(node):
path = os.path.abspath(node)
return path if os.path.isdir(path) else os.path.dirname(path) | [
"def",
"_get_node_dir",
"(",
"node",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"node",
")",
"return",
"path",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
"else",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")... | Return the absolute path of the directory of a filesystem node. | [
"Return",
"the",
"absolute",
"path",
"of",
"the",
"directory",
"of",
"a",
"filesystem",
"node",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L287-L290 |
228,559 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser._read_configuration_file | def _read_configuration_file(self, path):
"""Try to read and parse `path` as a configuration file.
If the configurations were illegal (checked with
`self._validate_options`), raises `IllegalConfiguration`.
Returns (options, should_inherit).
"""
parser = RawConfigParser(inline_comment_prefixes=('#', ';'))
options = None
should_inherit = True
if parser.read(path) and self._get_section_name(parser):
all_options = self._parser.option_list[:]
for group in self._parser.option_groups:
all_options.extend(group.option_list)
option_list = {o.dest: o.type or o.action
for o in all_options}
# First, read the default values
new_options, _ = self._parse_args([])
# Second, parse the configuration
section_name = self._get_section_name(parser)
for opt in parser.options(section_name):
if opt == 'inherit':
should_inherit = parser.getboolean(section_name, opt)
continue
if opt.replace('_', '-') not in self.CONFIG_FILE_OPTIONS:
log.warning("Unknown option '{}' ignored".format(opt))
continue
normalized_opt = opt.replace('-', '_')
opt_type = option_list[normalized_opt]
if opt_type in ('int', 'count'):
value = parser.getint(section_name, opt)
elif opt_type == 'string':
value = parser.get(section_name, opt)
else:
assert opt_type in ('store_true', 'store_false')
value = parser.getboolean(section_name, opt)
setattr(new_options, normalized_opt, value)
# Third, fix the set-options
options = self._fix_set_options(new_options)
if options is not None:
if not self._validate_options(options):
raise IllegalConfiguration('in file: {}'.format(path))
return options, should_inherit | python | def _read_configuration_file(self, path):
parser = RawConfigParser(inline_comment_prefixes=('#', ';'))
options = None
should_inherit = True
if parser.read(path) and self._get_section_name(parser):
all_options = self._parser.option_list[:]
for group in self._parser.option_groups:
all_options.extend(group.option_list)
option_list = {o.dest: o.type or o.action
for o in all_options}
# First, read the default values
new_options, _ = self._parse_args([])
# Second, parse the configuration
section_name = self._get_section_name(parser)
for opt in parser.options(section_name):
if opt == 'inherit':
should_inherit = parser.getboolean(section_name, opt)
continue
if opt.replace('_', '-') not in self.CONFIG_FILE_OPTIONS:
log.warning("Unknown option '{}' ignored".format(opt))
continue
normalized_opt = opt.replace('-', '_')
opt_type = option_list[normalized_opt]
if opt_type in ('int', 'count'):
value = parser.getint(section_name, opt)
elif opt_type == 'string':
value = parser.get(section_name, opt)
else:
assert opt_type in ('store_true', 'store_false')
value = parser.getboolean(section_name, opt)
setattr(new_options, normalized_opt, value)
# Third, fix the set-options
options = self._fix_set_options(new_options)
if options is not None:
if not self._validate_options(options):
raise IllegalConfiguration('in file: {}'.format(path))
return options, should_inherit | [
"def",
"_read_configuration_file",
"(",
"self",
",",
"path",
")",
":",
"parser",
"=",
"RawConfigParser",
"(",
"inline_comment_prefixes",
"=",
"(",
"'#'",
",",
"';'",
")",
")",
"options",
"=",
"None",
"should_inherit",
"=",
"True",
"if",
"parser",
".",
"read"... | Try to read and parse `path` as a configuration file.
If the configurations were illegal (checked with
`self._validate_options`), raises `IllegalConfiguration`.
Returns (options, should_inherit). | [
"Try",
"to",
"read",
"and",
"parse",
"path",
"as",
"a",
"configuration",
"file",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L292-L345 |
228,560 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser._merge_configuration | def _merge_configuration(self, parent_config, child_options):
"""Merge parent config into the child options.
The migration process requires an `options` object for the child in
order to distinguish between mutually exclusive codes, add-select and
add-ignore error codes.
"""
# Copy the parent error codes so we won't override them
error_codes = copy.deepcopy(parent_config.checked_codes)
if self._has_exclusive_option(child_options):
error_codes = self._get_exclusive_error_codes(child_options)
self._set_add_options(error_codes, child_options)
kwargs = dict(checked_codes=error_codes)
for key in ('match', 'match_dir', 'ignore_decorators'):
kwargs[key] = \
getattr(child_options, key) or getattr(parent_config, key)
return CheckConfiguration(**kwargs) | python | def _merge_configuration(self, parent_config, child_options):
# Copy the parent error codes so we won't override them
error_codes = copy.deepcopy(parent_config.checked_codes)
if self._has_exclusive_option(child_options):
error_codes = self._get_exclusive_error_codes(child_options)
self._set_add_options(error_codes, child_options)
kwargs = dict(checked_codes=error_codes)
for key in ('match', 'match_dir', 'ignore_decorators'):
kwargs[key] = \
getattr(child_options, key) or getattr(parent_config, key)
return CheckConfiguration(**kwargs) | [
"def",
"_merge_configuration",
"(",
"self",
",",
"parent_config",
",",
"child_options",
")",
":",
"# Copy the parent error codes so we won't override them",
"error_codes",
"=",
"copy",
".",
"deepcopy",
"(",
"parent_config",
".",
"checked_codes",
")",
"if",
"self",
".",
... | Merge parent config into the child options.
The migration process requires an `options` object for the child in
order to distinguish between mutually exclusive codes, add-select and
add-ignore error codes. | [
"Merge",
"parent",
"config",
"into",
"the",
"child",
"options",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L347-L366 |
228,561 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser._parse_args | def _parse_args(self, args=None, values=None):
"""Parse the options using `self._parser` and reformat the options."""
options, arguments = self._parser.parse_args(args, values)
return self._fix_set_options(options), arguments | python | def _parse_args(self, args=None, values=None):
options, arguments = self._parser.parse_args(args, values)
return self._fix_set_options(options), arguments | [
"def",
"_parse_args",
"(",
"self",
",",
"args",
"=",
"None",
",",
"values",
"=",
"None",
")",
":",
"options",
",",
"arguments",
"=",
"self",
".",
"_parser",
".",
"parse_args",
"(",
"args",
",",
"values",
")",
"return",
"self",
".",
"_fix_set_options",
... | Parse the options using `self._parser` and reformat the options. | [
"Parse",
"the",
"options",
"using",
"self",
".",
"_parser",
"and",
"reformat",
"the",
"options",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L368-L371 |
228,562 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser._create_run_config | def _create_run_config(options):
"""Create a `RunConfiguration` object from `options`."""
values = {opt: getattr(options, opt) for opt in
RunConfiguration._fields}
return RunConfiguration(**values) | python | def _create_run_config(options):
values = {opt: getattr(options, opt) for opt in
RunConfiguration._fields}
return RunConfiguration(**values) | [
"def",
"_create_run_config",
"(",
"options",
")",
":",
"values",
"=",
"{",
"opt",
":",
"getattr",
"(",
"options",
",",
"opt",
")",
"for",
"opt",
"in",
"RunConfiguration",
".",
"_fields",
"}",
"return",
"RunConfiguration",
"(",
"*",
"*",
"values",
")"
] | Create a `RunConfiguration` object from `options`. | [
"Create",
"a",
"RunConfiguration",
"object",
"from",
"options",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L374-L378 |
228,563 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser._create_check_config | def _create_check_config(cls, options, use_defaults=True):
"""Create a `CheckConfiguration` object from `options`.
If `use_defaults`, any of the match options that are `None` will
be replaced with their default value and the default convention will be
set for the checked codes.
"""
checked_codes = None
if cls._has_exclusive_option(options) or use_defaults:
checked_codes = cls._get_checked_errors(options)
kwargs = dict(checked_codes=checked_codes)
for key in ('match', 'match_dir', 'ignore_decorators'):
kwargs[key] = getattr(cls, 'DEFAULT_{}_RE'.format(key.upper())) \
if getattr(options, key) is None and use_defaults \
else getattr(options, key)
return CheckConfiguration(**kwargs) | python | def _create_check_config(cls, options, use_defaults=True):
checked_codes = None
if cls._has_exclusive_option(options) or use_defaults:
checked_codes = cls._get_checked_errors(options)
kwargs = dict(checked_codes=checked_codes)
for key in ('match', 'match_dir', 'ignore_decorators'):
kwargs[key] = getattr(cls, 'DEFAULT_{}_RE'.format(key.upper())) \
if getattr(options, key) is None and use_defaults \
else getattr(options, key)
return CheckConfiguration(**kwargs) | [
"def",
"_create_check_config",
"(",
"cls",
",",
"options",
",",
"use_defaults",
"=",
"True",
")",
":",
"checked_codes",
"=",
"None",
"if",
"cls",
".",
"_has_exclusive_option",
"(",
"options",
")",
"or",
"use_defaults",
":",
"checked_codes",
"=",
"cls",
".",
... | Create a `CheckConfiguration` object from `options`.
If `use_defaults`, any of the match options that are `None` will
be replaced with their default value and the default convention will be
set for the checked codes. | [
"Create",
"a",
"CheckConfiguration",
"object",
"from",
"options",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L381-L399 |
228,564 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser._get_section_name | def _get_section_name(cls, parser):
"""Parse options from relevant section."""
for section_name in cls.POSSIBLE_SECTION_NAMES:
if parser.has_section(section_name):
return section_name
return None | python | def _get_section_name(cls, parser):
for section_name in cls.POSSIBLE_SECTION_NAMES:
if parser.has_section(section_name):
return section_name
return None | [
"def",
"_get_section_name",
"(",
"cls",
",",
"parser",
")",
":",
"for",
"section_name",
"in",
"cls",
".",
"POSSIBLE_SECTION_NAMES",
":",
"if",
"parser",
".",
"has_section",
"(",
"section_name",
")",
":",
"return",
"section_name",
"return",
"None"
] | Parse options from relevant section. | [
"Parse",
"options",
"from",
"relevant",
"section",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L402-L408 |
228,565 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser._get_config_file_in_folder | def _get_config_file_in_folder(cls, path):
"""Look for a configuration file in `path`.
If exists return its full path, otherwise None.
"""
if os.path.isfile(path):
path = os.path.dirname(path)
for fn in cls.PROJECT_CONFIG_FILES:
config = RawConfigParser()
full_path = os.path.join(path, fn)
if config.read(full_path) and cls._get_section_name(config):
return full_path | python | def _get_config_file_in_folder(cls, path):
if os.path.isfile(path):
path = os.path.dirname(path)
for fn in cls.PROJECT_CONFIG_FILES:
config = RawConfigParser()
full_path = os.path.join(path, fn)
if config.read(full_path) and cls._get_section_name(config):
return full_path | [
"def",
"_get_config_file_in_folder",
"(",
"cls",
",",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"for",
"fn",
"in",
"cls",
".",
"PROJECT_CONFIG_FI... | Look for a configuration file in `path`.
If exists return its full path, otherwise None. | [
"Look",
"for",
"a",
"configuration",
"file",
"in",
"path",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L411-L424 |
228,566 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser._get_exclusive_error_codes | def _get_exclusive_error_codes(cls, options):
"""Extract the error codes from the selected exclusive option."""
codes = set(ErrorRegistry.get_error_codes())
checked_codes = None
if options.ignore is not None:
ignored = cls._expand_error_codes(options.ignore)
checked_codes = codes - ignored
elif options.select is not None:
checked_codes = cls._expand_error_codes(options.select)
elif options.convention is not None:
checked_codes = getattr(conventions, options.convention)
# To not override the conventions nor the options - copy them.
return copy.deepcopy(checked_codes) | python | def _get_exclusive_error_codes(cls, options):
codes = set(ErrorRegistry.get_error_codes())
checked_codes = None
if options.ignore is not None:
ignored = cls._expand_error_codes(options.ignore)
checked_codes = codes - ignored
elif options.select is not None:
checked_codes = cls._expand_error_codes(options.select)
elif options.convention is not None:
checked_codes = getattr(conventions, options.convention)
# To not override the conventions nor the options - copy them.
return copy.deepcopy(checked_codes) | [
"def",
"_get_exclusive_error_codes",
"(",
"cls",
",",
"options",
")",
":",
"codes",
"=",
"set",
"(",
"ErrorRegistry",
".",
"get_error_codes",
"(",
")",
")",
"checked_codes",
"=",
"None",
"if",
"options",
".",
"ignore",
"is",
"not",
"None",
":",
"ignored",
... | Extract the error codes from the selected exclusive option. | [
"Extract",
"the",
"error",
"codes",
"from",
"the",
"selected",
"exclusive",
"option",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L427-L441 |
228,567 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser._set_add_options | def _set_add_options(cls, checked_codes, options):
"""Set `checked_codes` by the `add_ignore` or `add_select` options."""
checked_codes |= cls._expand_error_codes(options.add_select)
checked_codes -= cls._expand_error_codes(options.add_ignore) | python | def _set_add_options(cls, checked_codes, options):
checked_codes |= cls._expand_error_codes(options.add_select)
checked_codes -= cls._expand_error_codes(options.add_ignore) | [
"def",
"_set_add_options",
"(",
"cls",
",",
"checked_codes",
",",
"options",
")",
":",
"checked_codes",
"|=",
"cls",
".",
"_expand_error_codes",
"(",
"options",
".",
"add_select",
")",
"checked_codes",
"-=",
"cls",
".",
"_expand_error_codes",
"(",
"options",
"."... | Set `checked_codes` by the `add_ignore` or `add_select` options. | [
"Set",
"checked_codes",
"by",
"the",
"add_ignore",
"or",
"add_select",
"options",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L444-L447 |
228,568 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser._expand_error_codes | def _expand_error_codes(code_parts):
"""Return an expanded set of error codes to ignore."""
codes = set(ErrorRegistry.get_error_codes())
expanded_codes = set()
try:
for part in code_parts:
# Dealing with split-lined configurations; The part might begin
# with a whitespace due to the newline character.
part = part.strip()
if not part:
continue
codes_to_add = {code for code in codes
if code.startswith(part)}
if not codes_to_add:
log.warning(
'Error code passed is not a prefix of any '
'known errors: %s', part)
expanded_codes.update(codes_to_add)
except TypeError as e:
raise IllegalConfiguration(e)
return expanded_codes | python | def _expand_error_codes(code_parts):
codes = set(ErrorRegistry.get_error_codes())
expanded_codes = set()
try:
for part in code_parts:
# Dealing with split-lined configurations; The part might begin
# with a whitespace due to the newline character.
part = part.strip()
if not part:
continue
codes_to_add = {code for code in codes
if code.startswith(part)}
if not codes_to_add:
log.warning(
'Error code passed is not a prefix of any '
'known errors: %s', part)
expanded_codes.update(codes_to_add)
except TypeError as e:
raise IllegalConfiguration(e)
return expanded_codes | [
"def",
"_expand_error_codes",
"(",
"code_parts",
")",
":",
"codes",
"=",
"set",
"(",
"ErrorRegistry",
".",
"get_error_codes",
"(",
")",
")",
"expanded_codes",
"=",
"set",
"(",
")",
"try",
":",
"for",
"part",
"in",
"code_parts",
":",
"# Dealing with split-lined... | Return an expanded set of error codes to ignore. | [
"Return",
"an",
"expanded",
"set",
"of",
"error",
"codes",
"to",
"ignore",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L450-L473 |
228,569 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser._get_checked_errors | def _get_checked_errors(cls, options):
"""Extract the codes needed to be checked from `options`."""
checked_codes = cls._get_exclusive_error_codes(options)
if checked_codes is None:
checked_codes = cls.DEFAULT_CONVENTION
cls._set_add_options(checked_codes, options)
return checked_codes | python | def _get_checked_errors(cls, options):
checked_codes = cls._get_exclusive_error_codes(options)
if checked_codes is None:
checked_codes = cls.DEFAULT_CONVENTION
cls._set_add_options(checked_codes, options)
return checked_codes | [
"def",
"_get_checked_errors",
"(",
"cls",
",",
"options",
")",
":",
"checked_codes",
"=",
"cls",
".",
"_get_exclusive_error_codes",
"(",
"options",
")",
"if",
"checked_codes",
"is",
"None",
":",
"checked_codes",
"=",
"cls",
".",
"DEFAULT_CONVENTION",
"cls",
".",... | Extract the codes needed to be checked from `options`. | [
"Extract",
"the",
"codes",
"needed",
"to",
"be",
"checked",
"from",
"options",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L476-L484 |
228,570 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser._validate_options | def _validate_options(cls, options):
"""Validate the mutually exclusive options.
Return `True` iff only zero or one of `BASE_ERROR_SELECTION_OPTIONS`
was selected.
"""
for opt1, opt2 in \
itertools.permutations(cls.BASE_ERROR_SELECTION_OPTIONS, 2):
if getattr(options, opt1) and getattr(options, opt2):
log.error('Cannot pass both {} and {}. They are '
'mutually exclusive.'.format(opt1, opt2))
return False
if options.convention and options.convention not in conventions:
log.error("Illegal convention '{}'. Possible conventions: {}"
.format(options.convention,
', '.join(conventions.keys())))
return False
return True | python | def _validate_options(cls, options):
for opt1, opt2 in \
itertools.permutations(cls.BASE_ERROR_SELECTION_OPTIONS, 2):
if getattr(options, opt1) and getattr(options, opt2):
log.error('Cannot pass both {} and {}. They are '
'mutually exclusive.'.format(opt1, opt2))
return False
if options.convention and options.convention not in conventions:
log.error("Illegal convention '{}'. Possible conventions: {}"
.format(options.convention,
', '.join(conventions.keys())))
return False
return True | [
"def",
"_validate_options",
"(",
"cls",
",",
"options",
")",
":",
"for",
"opt1",
",",
"opt2",
"in",
"itertools",
".",
"permutations",
"(",
"cls",
".",
"BASE_ERROR_SELECTION_OPTIONS",
",",
"2",
")",
":",
"if",
"getattr",
"(",
"options",
",",
"opt1",
")",
... | Validate the mutually exclusive options.
Return `True` iff only zero or one of `BASE_ERROR_SELECTION_OPTIONS`
was selected. | [
"Validate",
"the",
"mutually",
"exclusive",
"options",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L487-L506 |
228,571 | PyCQA/pydocstyle | src/pydocstyle/config.py | ConfigurationParser._has_exclusive_option | def _has_exclusive_option(cls, options):
"""Return `True` iff one or more exclusive options were selected."""
return any([getattr(options, opt) is not None for opt in
cls.BASE_ERROR_SELECTION_OPTIONS]) | python | def _has_exclusive_option(cls, options):
return any([getattr(options, opt) is not None for opt in
cls.BASE_ERROR_SELECTION_OPTIONS]) | [
"def",
"_has_exclusive_option",
"(",
"cls",
",",
"options",
")",
":",
"return",
"any",
"(",
"[",
"getattr",
"(",
"options",
",",
"opt",
")",
"is",
"not",
"None",
"for",
"opt",
"in",
"cls",
".",
"BASE_ERROR_SELECTION_OPTIONS",
"]",
")"
] | Return `True` iff one or more exclusive options were selected. | [
"Return",
"True",
"iff",
"one",
"or",
"more",
"exclusive",
"options",
"were",
"selected",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L509-L512 |
228,572 | PyCQA/pydocstyle | src/pydocstyle/utils.py | pairwise | def pairwise(
iterable: Iterable,
default_value: Any,
) -> Iterable[Tuple[Any, Any]]:
"""Return pairs of items from `iterable`.
pairwise([1, 2, 3], default_value=None) -> (1, 2) (2, 3), (3, None)
"""
a, b = tee(iterable)
_ = next(b, default_value)
return zip_longest(a, b, fillvalue=default_value) | python | def pairwise(
iterable: Iterable,
default_value: Any,
) -> Iterable[Tuple[Any, Any]]:
a, b = tee(iterable)
_ = next(b, default_value)
return zip_longest(a, b, fillvalue=default_value) | [
"def",
"pairwise",
"(",
"iterable",
":",
"Iterable",
",",
"default_value",
":",
"Any",
",",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"Any",
",",
"Any",
"]",
"]",
":",
"a",
",",
"b",
"=",
"tee",
"(",
"iterable",
")",
"_",
"=",
"next",
"(",
"b",
... | Return pairs of items from `iterable`.
pairwise([1, 2, 3], default_value=None) -> (1, 2) (2, 3), (3, None) | [
"Return",
"pairs",
"of",
"items",
"from",
"iterable",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/utils.py#L17-L27 |
228,573 | PyCQA/pydocstyle | src/pydocstyle/wordlists.py | load_wordlist | def load_wordlist(name: str) -> Iterator[str]:
"""Iterate over lines of a wordlist data file.
`name` should be the name of a package data file within the data/
directory.
Whitespace and #-prefixed comments are stripped from each line.
"""
data = pkgutil.get_data('pydocstyle', 'data/' + name)
if data is not None:
text = data.decode('utf8')
for line in text.splitlines():
line = COMMENT_RE.sub('', line).strip()
if line:
yield line | python | def load_wordlist(name: str) -> Iterator[str]:
data = pkgutil.get_data('pydocstyle', 'data/' + name)
if data is not None:
text = data.decode('utf8')
for line in text.splitlines():
line = COMMENT_RE.sub('', line).strip()
if line:
yield line | [
"def",
"load_wordlist",
"(",
"name",
":",
"str",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"data",
"=",
"pkgutil",
".",
"get_data",
"(",
"'pydocstyle'",
",",
"'data/'",
"+",
"name",
")",
"if",
"data",
"is",
"not",
"None",
":",
"text",
"=",
"data",... | Iterate over lines of a wordlist data file.
`name` should be the name of a package data file within the data/
directory.
Whitespace and #-prefixed comments are stripped from each line. | [
"Iterate",
"over",
"lines",
"of",
"a",
"wordlist",
"data",
"file",
"."
] | 2549847f9efad225789f931e83dfe782418ca13e | https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/wordlists.py#L20-L35 |
228,574 | rsteca/sklearn-deap | evolutionary_search/cv.py | EvolutionaryAlgorithmSearchCV.possible_params | def possible_params(self):
""" Used when assuming params is a list. """
return self.params if isinstance(self.params, list) else [self.params] | python | def possible_params(self):
return self.params if isinstance(self.params, list) else [self.params] | [
"def",
"possible_params",
"(",
"self",
")",
":",
"return",
"self",
".",
"params",
"if",
"isinstance",
"(",
"self",
".",
"params",
",",
"list",
")",
"else",
"[",
"self",
".",
"params",
"]"
] | Used when assuming params is a list. | [
"Used",
"when",
"assuming",
"params",
"is",
"a",
"list",
"."
] | b7ee1722a40cc0c6550d32a2714ab220db2b7430 | https://github.com/rsteca/sklearn-deap/blob/b7ee1722a40cc0c6550d32a2714ab220db2b7430/evolutionary_search/cv.py#L316-L318 |
228,575 | googleapis/google-auth-library-python | google/auth/transport/urllib3.py | AuthorizedHttp.urlopen | def urlopen(self, method, url, body=None, headers=None, **kwargs):
"""Implementation of urllib3's urlopen."""
# pylint: disable=arguments-differ
# We use kwargs to collect additional args that we don't need to
# introspect here. However, we do explicitly collect the two
# positional arguments.
# Use a kwarg for this instead of an attribute to maintain
# thread-safety.
_credential_refresh_attempt = kwargs.pop(
'_credential_refresh_attempt', 0)
if headers is None:
headers = self.headers
# Make a copy of the headers. They will be modified by the credentials
# and we want to pass the original headers if we recurse.
request_headers = headers.copy()
self.credentials.before_request(
self._request, method, url, request_headers)
response = self.http.urlopen(
method, url, body=body, headers=request_headers, **kwargs)
# If the response indicated that the credentials needed to be
# refreshed, then refresh the credentials and re-attempt the
# request.
# A stored token may expire between the time it is retrieved and
# the time the request is made, so we may need to try twice.
# The reason urllib3's retries aren't used is because they
# don't allow you to modify the request headers. :/
if (response.status in self._refresh_status_codes
and _credential_refresh_attempt < self._max_refresh_attempts):
_LOGGER.info(
'Refreshing credentials due to a %s response. Attempt %s/%s.',
response.status, _credential_refresh_attempt + 1,
self._max_refresh_attempts)
self.credentials.refresh(self._request)
# Recurse. Pass in the original headers, not our modified set.
return self.urlopen(
method, url, body=body, headers=headers,
_credential_refresh_attempt=_credential_refresh_attempt + 1,
**kwargs)
return response | python | def urlopen(self, method, url, body=None, headers=None, **kwargs):
# pylint: disable=arguments-differ
# We use kwargs to collect additional args that we don't need to
# introspect here. However, we do explicitly collect the two
# positional arguments.
# Use a kwarg for this instead of an attribute to maintain
# thread-safety.
_credential_refresh_attempt = kwargs.pop(
'_credential_refresh_attempt', 0)
if headers is None:
headers = self.headers
# Make a copy of the headers. They will be modified by the credentials
# and we want to pass the original headers if we recurse.
request_headers = headers.copy()
self.credentials.before_request(
self._request, method, url, request_headers)
response = self.http.urlopen(
method, url, body=body, headers=request_headers, **kwargs)
# If the response indicated that the credentials needed to be
# refreshed, then refresh the credentials and re-attempt the
# request.
# A stored token may expire between the time it is retrieved and
# the time the request is made, so we may need to try twice.
# The reason urllib3's retries aren't used is because they
# don't allow you to modify the request headers. :/
if (response.status in self._refresh_status_codes
and _credential_refresh_attempt < self._max_refresh_attempts):
_LOGGER.info(
'Refreshing credentials due to a %s response. Attempt %s/%s.',
response.status, _credential_refresh_attempt + 1,
self._max_refresh_attempts)
self.credentials.refresh(self._request)
# Recurse. Pass in the original headers, not our modified set.
return self.urlopen(
method, url, body=body, headers=headers,
_credential_refresh_attempt=_credential_refresh_attempt + 1,
**kwargs)
return response | [
"def",
"urlopen",
"(",
"self",
",",
"method",
",",
"url",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=arguments-differ",
"# We use kwargs to collect additional args that we don't need to",
"# introspect ... | Implementation of urllib3's urlopen. | [
"Implementation",
"of",
"urllib3",
"s",
"urlopen",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/transport/urllib3.py#L198-L246 |
228,576 | googleapis/google-auth-library-python | google/auth/app_engine.py | Credentials.service_account_email | def service_account_email(self):
"""The service account email."""
if self._service_account_id is None:
self._service_account_id = app_identity.get_service_account_name()
return self._service_account_id | python | def service_account_email(self):
if self._service_account_id is None:
self._service_account_id = app_identity.get_service_account_name()
return self._service_account_id | [
"def",
"service_account_email",
"(",
"self",
")",
":",
"if",
"self",
".",
"_service_account_id",
"is",
"None",
":",
"self",
".",
"_service_account_id",
"=",
"app_identity",
".",
"get_service_account_name",
"(",
")",
"return",
"self",
".",
"_service_account_id"
] | The service account email. | [
"The",
"service",
"account",
"email",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/app_engine.py#L124-L128 |
228,577 | googleapis/google-auth-library-python | google/auth/_oauth2client.py | convert | def convert(credentials):
"""Convert oauth2client credentials to google-auth credentials.
This class converts:
- :class:`oauth2client.client.OAuth2Credentials` to
:class:`google.oauth2.credentials.Credentials`.
- :class:`oauth2client.client.GoogleCredentials` to
:class:`google.oauth2.credentials.Credentials`.
- :class:`oauth2client.service_account.ServiceAccountCredentials` to
:class:`google.oauth2.service_account.Credentials`.
- :class:`oauth2client.service_account._JWTAccessCredentials` to
:class:`google.oauth2.service_account.Credentials`.
- :class:`oauth2client.contrib.gce.AppAssertionCredentials` to
:class:`google.auth.compute_engine.Credentials`.
- :class:`oauth2client.contrib.appengine.AppAssertionCredentials` to
:class:`google.auth.app_engine.Credentials`.
Returns:
google.auth.credentials.Credentials: The converted credentials.
Raises:
ValueError: If the credentials could not be converted.
"""
credentials_class = type(credentials)
try:
return _CLASS_CONVERSION_MAP[credentials_class](credentials)
except KeyError as caught_exc:
new_exc = ValueError(_CONVERT_ERROR_TMPL.format(credentials_class))
six.raise_from(new_exc, caught_exc) | python | def convert(credentials):
credentials_class = type(credentials)
try:
return _CLASS_CONVERSION_MAP[credentials_class](credentials)
except KeyError as caught_exc:
new_exc = ValueError(_CONVERT_ERROR_TMPL.format(credentials_class))
six.raise_from(new_exc, caught_exc) | [
"def",
"convert",
"(",
"credentials",
")",
":",
"credentials_class",
"=",
"type",
"(",
"credentials",
")",
"try",
":",
"return",
"_CLASS_CONVERSION_MAP",
"[",
"credentials_class",
"]",
"(",
"credentials",
")",
"except",
"KeyError",
"as",
"caught_exc",
":",
"new_... | Convert oauth2client credentials to google-auth credentials.
This class converts:
- :class:`oauth2client.client.OAuth2Credentials` to
:class:`google.oauth2.credentials.Credentials`.
- :class:`oauth2client.client.GoogleCredentials` to
:class:`google.oauth2.credentials.Credentials`.
- :class:`oauth2client.service_account.ServiceAccountCredentials` to
:class:`google.oauth2.service_account.Credentials`.
- :class:`oauth2client.service_account._JWTAccessCredentials` to
:class:`google.oauth2.service_account.Credentials`.
- :class:`oauth2client.contrib.gce.AppAssertionCredentials` to
:class:`google.auth.compute_engine.Credentials`.
- :class:`oauth2client.contrib.appengine.AppAssertionCredentials` to
:class:`google.auth.app_engine.Credentials`.
Returns:
google.auth.credentials.Credentials: The converted credentials.
Raises:
ValueError: If the credentials could not be converted. | [
"Convert",
"oauth2client",
"credentials",
"to",
"google",
"-",
"auth",
"credentials",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/_oauth2client.py#L140-L171 |
228,578 | googleapis/google-auth-library-python | google/auth/impersonated_credentials.py | Credentials._update_token | def _update_token(self, request):
"""Updates credentials with a new access_token representing
the impersonated account.
Args:
request (google.auth.transport.requests.Request): Request object
to use for refreshing credentials.
"""
# Refresh our source credentials.
self._source_credentials.refresh(request)
body = {
"delegates": self._delegates,
"scope": self._target_scopes,
"lifetime": str(self._lifetime) + "s"
}
headers = {
'Content-Type': 'application/json',
}
# Apply the source credentials authentication info.
self._source_credentials.apply(headers)
self.token, self.expiry = _make_iam_token_request(
request=request,
principal=self._target_principal,
headers=headers,
body=body) | python | def _update_token(self, request):
# Refresh our source credentials.
self._source_credentials.refresh(request)
body = {
"delegates": self._delegates,
"scope": self._target_scopes,
"lifetime": str(self._lifetime) + "s"
}
headers = {
'Content-Type': 'application/json',
}
# Apply the source credentials authentication info.
self._source_credentials.apply(headers)
self.token, self.expiry = _make_iam_token_request(
request=request,
principal=self._target_principal,
headers=headers,
body=body) | [
"def",
"_update_token",
"(",
"self",
",",
"request",
")",
":",
"# Refresh our source credentials.",
"self",
".",
"_source_credentials",
".",
"refresh",
"(",
"request",
")",
"body",
"=",
"{",
"\"delegates\"",
":",
"self",
".",
"_delegates",
",",
"\"scope\"",
":",... | Updates credentials with a new access_token representing
the impersonated account.
Args:
request (google.auth.transport.requests.Request): Request object
to use for refreshing credentials. | [
"Updates",
"credentials",
"with",
"a",
"new",
"access_token",
"representing",
"the",
"impersonated",
"account",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/impersonated_credentials.py#L202-L231 |
228,579 | googleapis/google-auth-library-python | google/auth/crypt/__init__.py | verify_signature | def verify_signature(message, signature, certs):
"""Verify an RSA cryptographic signature.
Checks that the provided ``signature`` was generated from ``bytes`` using
the private key associated with the ``cert``.
Args:
message (Union[str, bytes]): The plaintext message.
signature (Union[str, bytes]): The cryptographic signature to check.
certs (Union[Sequence, str, bytes]): The certificate or certificates
to use to check the signature.
Returns:
bool: True if the signature is valid, otherwise False.
"""
if isinstance(certs, (six.text_type, six.binary_type)):
certs = [certs]
for cert in certs:
verifier = rsa.RSAVerifier.from_string(cert)
if verifier.verify(message, signature):
return True
return False | python | def verify_signature(message, signature, certs):
if isinstance(certs, (six.text_type, six.binary_type)):
certs = [certs]
for cert in certs:
verifier = rsa.RSAVerifier.from_string(cert)
if verifier.verify(message, signature):
return True
return False | [
"def",
"verify_signature",
"(",
"message",
",",
"signature",
",",
"certs",
")",
":",
"if",
"isinstance",
"(",
"certs",
",",
"(",
"six",
".",
"text_type",
",",
"six",
".",
"binary_type",
")",
")",
":",
"certs",
"=",
"[",
"certs",
"]",
"for",
"cert",
"... | Verify an RSA cryptographic signature.
Checks that the provided ``signature`` was generated from ``bytes`` using
the private key associated with the ``cert``.
Args:
message (Union[str, bytes]): The plaintext message.
signature (Union[str, bytes]): The cryptographic signature to check.
certs (Union[Sequence, str, bytes]): The certificate or certificates
to use to check the signature.
Returns:
bool: True if the signature is valid, otherwise False. | [
"Verify",
"an",
"RSA",
"cryptographic",
"signature",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/crypt/__init__.py#L57-L79 |
228,580 | googleapis/google-auth-library-python | google/auth/iam.py | Signer._make_signing_request | def _make_signing_request(self, message):
"""Makes a request to the API signBlob API."""
message = _helpers.to_bytes(message)
method = 'POST'
url = _SIGN_BLOB_URI.format(self._service_account_email)
headers = {}
body = json.dumps({
'bytesToSign': base64.b64encode(message).decode('utf-8'),
})
self._credentials.before_request(self._request, method, url, headers)
response = self._request(
url=url, method=method, body=body, headers=headers)
if response.status != http_client.OK:
raise exceptions.TransportError(
'Error calling the IAM signBytes API: {}'.format(
response.data))
return json.loads(response.data.decode('utf-8')) | python | def _make_signing_request(self, message):
message = _helpers.to_bytes(message)
method = 'POST'
url = _SIGN_BLOB_URI.format(self._service_account_email)
headers = {}
body = json.dumps({
'bytesToSign': base64.b64encode(message).decode('utf-8'),
})
self._credentials.before_request(self._request, method, url, headers)
response = self._request(
url=url, method=method, body=body, headers=headers)
if response.status != http_client.OK:
raise exceptions.TransportError(
'Error calling the IAM signBytes API: {}'.format(
response.data))
return json.loads(response.data.decode('utf-8')) | [
"def",
"_make_signing_request",
"(",
"self",
",",
"message",
")",
":",
"message",
"=",
"_helpers",
".",
"to_bytes",
"(",
"message",
")",
"method",
"=",
"'POST'",
"url",
"=",
"_SIGN_BLOB_URI",
".",
"format",
"(",
"self",
".",
"_service_account_email",
")",
"h... | Makes a request to the API signBlob API. | [
"Makes",
"a",
"request",
"to",
"the",
"API",
"signBlob",
"API",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/iam.py#L67-L87 |
228,581 | googleapis/google-auth-library-python | google/oauth2/id_token.py | _fetch_certs | def _fetch_certs(request, certs_url):
"""Fetches certificates.
Google-style cerificate endpoints return JSON in the format of
``{'key id': 'x509 certificate'}``.
Args:
request (google.auth.transport.Request): The object used to make
HTTP requests.
certs_url (str): The certificate endpoint URL.
Returns:
Mapping[str, str]: A mapping of public key ID to x.509 certificate
data.
"""
response = request(certs_url, method='GET')
if response.status != http_client.OK:
raise exceptions.TransportError(
'Could not fetch certificates at {}'.format(certs_url))
return json.loads(response.data.decode('utf-8')) | python | def _fetch_certs(request, certs_url):
response = request(certs_url, method='GET')
if response.status != http_client.OK:
raise exceptions.TransportError(
'Could not fetch certificates at {}'.format(certs_url))
return json.loads(response.data.decode('utf-8')) | [
"def",
"_fetch_certs",
"(",
"request",
",",
"certs_url",
")",
":",
"response",
"=",
"request",
"(",
"certs_url",
",",
"method",
"=",
"'GET'",
")",
"if",
"response",
".",
"status",
"!=",
"http_client",
".",
"OK",
":",
"raise",
"exceptions",
".",
"TransportE... | Fetches certificates.
Google-style cerificate endpoints return JSON in the format of
``{'key id': 'x509 certificate'}``.
Args:
request (google.auth.transport.Request): The object used to make
HTTP requests.
certs_url (str): The certificate endpoint URL.
Returns:
Mapping[str, str]: A mapping of public key ID to x.509 certificate
data. | [
"Fetches",
"certificates",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/oauth2/id_token.py#L79-L100 |
228,582 | googleapis/google-auth-library-python | google/oauth2/id_token.py | verify_token | def verify_token(id_token, request, audience=None,
certs_url=_GOOGLE_OAUTH2_CERTS_URL):
"""Verifies an ID token and returns the decoded token.
Args:
id_token (Union[str, bytes]): The encoded token.
request (google.auth.transport.Request): The object used to make
HTTP requests.
audience (str): The audience that this token is intended for. If None
then the audience is not verified.
certs_url (str): The URL that specifies the certificates to use to
verify the token. This URL should return JSON in the format of
``{'key id': 'x509 certificate'}``.
Returns:
Mapping[str, Any]: The decoded token.
"""
certs = _fetch_certs(request, certs_url)
return jwt.decode(id_token, certs=certs, audience=audience) | python | def verify_token(id_token, request, audience=None,
certs_url=_GOOGLE_OAUTH2_CERTS_URL):
certs = _fetch_certs(request, certs_url)
return jwt.decode(id_token, certs=certs, audience=audience) | [
"def",
"verify_token",
"(",
"id_token",
",",
"request",
",",
"audience",
"=",
"None",
",",
"certs_url",
"=",
"_GOOGLE_OAUTH2_CERTS_URL",
")",
":",
"certs",
"=",
"_fetch_certs",
"(",
"request",
",",
"certs_url",
")",
"return",
"jwt",
".",
"decode",
"(",
"id_t... | Verifies an ID token and returns the decoded token.
Args:
id_token (Union[str, bytes]): The encoded token.
request (google.auth.transport.Request): The object used to make
HTTP requests.
audience (str): The audience that this token is intended for. If None
then the audience is not verified.
certs_url (str): The URL that specifies the certificates to use to
verify the token. This URL should return JSON in the format of
``{'key id': 'x509 certificate'}``.
Returns:
Mapping[str, Any]: The decoded token. | [
"Verifies",
"an",
"ID",
"token",
"and",
"returns",
"the",
"decoded",
"token",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/oauth2/id_token.py#L103-L122 |
228,583 | googleapis/google-auth-library-python | google/oauth2/id_token.py | verify_oauth2_token | def verify_oauth2_token(id_token, request, audience=None):
"""Verifies an ID Token issued by Google's OAuth 2.0 authorization server.
Args:
id_token (Union[str, bytes]): The encoded token.
request (google.auth.transport.Request): The object used to make
HTTP requests.
audience (str): The audience that this token is intended for. This is
typically your application's OAuth 2.0 client ID. If None then the
audience is not verified.
Returns:
Mapping[str, Any]: The decoded token.
"""
return verify_token(
id_token, request, audience=audience,
certs_url=_GOOGLE_OAUTH2_CERTS_URL) | python | def verify_oauth2_token(id_token, request, audience=None):
return verify_token(
id_token, request, audience=audience,
certs_url=_GOOGLE_OAUTH2_CERTS_URL) | [
"def",
"verify_oauth2_token",
"(",
"id_token",
",",
"request",
",",
"audience",
"=",
"None",
")",
":",
"return",
"verify_token",
"(",
"id_token",
",",
"request",
",",
"audience",
"=",
"audience",
",",
"certs_url",
"=",
"_GOOGLE_OAUTH2_CERTS_URL",
")"
] | Verifies an ID Token issued by Google's OAuth 2.0 authorization server.
Args:
id_token (Union[str, bytes]): The encoded token.
request (google.auth.transport.Request): The object used to make
HTTP requests.
audience (str): The audience that this token is intended for. This is
typically your application's OAuth 2.0 client ID. If None then the
audience is not verified.
Returns:
Mapping[str, Any]: The decoded token. | [
"Verifies",
"an",
"ID",
"Token",
"issued",
"by",
"Google",
"s",
"OAuth",
"2",
".",
"0",
"authorization",
"server",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/oauth2/id_token.py#L125-L141 |
228,584 | googleapis/google-auth-library-python | google/oauth2/id_token.py | verify_firebase_token | def verify_firebase_token(id_token, request, audience=None):
"""Verifies an ID Token issued by Firebase Authentication.
Args:
id_token (Union[str, bytes]): The encoded token.
request (google.auth.transport.Request): The object used to make
HTTP requests.
audience (str): The audience that this token is intended for. This is
typically your Firebase application ID. If None then the audience
is not verified.
Returns:
Mapping[str, Any]: The decoded token.
"""
return verify_token(
id_token, request, audience=audience, certs_url=_GOOGLE_APIS_CERTS_URL) | python | def verify_firebase_token(id_token, request, audience=None):
return verify_token(
id_token, request, audience=audience, certs_url=_GOOGLE_APIS_CERTS_URL) | [
"def",
"verify_firebase_token",
"(",
"id_token",
",",
"request",
",",
"audience",
"=",
"None",
")",
":",
"return",
"verify_token",
"(",
"id_token",
",",
"request",
",",
"audience",
"=",
"audience",
",",
"certs_url",
"=",
"_GOOGLE_APIS_CERTS_URL",
")"
] | Verifies an ID Token issued by Firebase Authentication.
Args:
id_token (Union[str, bytes]): The encoded token.
request (google.auth.transport.Request): The object used to make
HTTP requests.
audience (str): The audience that this token is intended for. This is
typically your Firebase application ID. If None then the audience
is not verified.
Returns:
Mapping[str, Any]: The decoded token. | [
"Verifies",
"an",
"ID",
"Token",
"issued",
"by",
"Firebase",
"Authentication",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/oauth2/id_token.py#L144-L159 |
228,585 | googleapis/google-auth-library-python | google/auth/jwt.py | _decode_jwt_segment | def _decode_jwt_segment(encoded_section):
"""Decodes a single JWT segment."""
section_bytes = _helpers.padded_urlsafe_b64decode(encoded_section)
try:
return json.loads(section_bytes.decode('utf-8'))
except ValueError as caught_exc:
new_exc = ValueError('Can\'t parse segment: {0}'.format(section_bytes))
six.raise_from(new_exc, caught_exc) | python | def _decode_jwt_segment(encoded_section):
section_bytes = _helpers.padded_urlsafe_b64decode(encoded_section)
try:
return json.loads(section_bytes.decode('utf-8'))
except ValueError as caught_exc:
new_exc = ValueError('Can\'t parse segment: {0}'.format(section_bytes))
six.raise_from(new_exc, caught_exc) | [
"def",
"_decode_jwt_segment",
"(",
"encoded_section",
")",
":",
"section_bytes",
"=",
"_helpers",
".",
"padded_urlsafe_b64decode",
"(",
"encoded_section",
")",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"section_bytes",
".",
"decode",
"(",
"'utf-8'",
")",
... | Decodes a single JWT segment. | [
"Decodes",
"a",
"single",
"JWT",
"segment",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/jwt.py#L105-L112 |
228,586 | googleapis/google-auth-library-python | google/auth/jwt.py | _unverified_decode | def _unverified_decode(token):
"""Decodes a token and does no verification.
Args:
token (Union[str, bytes]): The encoded JWT.
Returns:
Tuple[str, str, str, str]: header, payload, signed_section, and
signature.
Raises:
ValueError: if there are an incorrect amount of segments in the token.
"""
token = _helpers.to_bytes(token)
if token.count(b'.') != 2:
raise ValueError(
'Wrong number of segments in token: {0}'.format(token))
encoded_header, encoded_payload, signature = token.split(b'.')
signed_section = encoded_header + b'.' + encoded_payload
signature = _helpers.padded_urlsafe_b64decode(signature)
# Parse segments
header = _decode_jwt_segment(encoded_header)
payload = _decode_jwt_segment(encoded_payload)
return header, payload, signed_section, signature | python | def _unverified_decode(token):
token = _helpers.to_bytes(token)
if token.count(b'.') != 2:
raise ValueError(
'Wrong number of segments in token: {0}'.format(token))
encoded_header, encoded_payload, signature = token.split(b'.')
signed_section = encoded_header + b'.' + encoded_payload
signature = _helpers.padded_urlsafe_b64decode(signature)
# Parse segments
header = _decode_jwt_segment(encoded_header)
payload = _decode_jwt_segment(encoded_payload)
return header, payload, signed_section, signature | [
"def",
"_unverified_decode",
"(",
"token",
")",
":",
"token",
"=",
"_helpers",
".",
"to_bytes",
"(",
"token",
")",
"if",
"token",
".",
"count",
"(",
"b'.'",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'Wrong number of segments in token: {0}'",
".",
"fo... | Decodes a token and does no verification.
Args:
token (Union[str, bytes]): The encoded JWT.
Returns:
Tuple[str, str, str, str]: header, payload, signed_section, and
signature.
Raises:
ValueError: if there are an incorrect amount of segments in the token. | [
"Decodes",
"a",
"token",
"and",
"does",
"no",
"verification",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/jwt.py#L115-L142 |
228,587 | googleapis/google-auth-library-python | google/auth/jwt.py | decode | def decode(token, certs=None, verify=True, audience=None):
"""Decode and verify a JWT.
Args:
token (str): The encoded JWT.
certs (Union[str, bytes, Mapping[str, Union[str, bytes]]]): The
certificate used to validate the JWT signature. If bytes or string,
it must the the public key certificate in PEM format. If a mapping,
it must be a mapping of key IDs to public key certificates in PEM
format. The mapping must contain the same key ID that's specified
in the token's header.
verify (bool): Whether to perform signature and claim validation.
Verification is done by default.
audience (str): The audience claim, 'aud', that this JWT should
contain. If None then the JWT's 'aud' parameter is not verified.
Returns:
Mapping[str, str]: The deserialized JSON payload in the JWT.
Raises:
ValueError: if any verification checks failed.
"""
header, payload, signed_section, signature = _unverified_decode(token)
if not verify:
return payload
# If certs is specified as a dictionary of key IDs to certificates, then
# use the certificate identified by the key ID in the token header.
if isinstance(certs, collections.Mapping):
key_id = header.get('kid')
if key_id:
if key_id not in certs:
raise ValueError(
'Certificate for key id {} not found.'.format(key_id))
certs_to_check = [certs[key_id]]
# If there's no key id in the header, check against all of the certs.
else:
certs_to_check = certs.values()
else:
certs_to_check = certs
# Verify that the signature matches the message.
if not crypt.verify_signature(signed_section, signature, certs_to_check):
raise ValueError('Could not verify token signature.')
# Verify the issued at and created times in the payload.
_verify_iat_and_exp(payload)
# Check audience.
if audience is not None:
claim_audience = payload.get('aud')
if audience != claim_audience:
raise ValueError(
'Token has wrong audience {}, expected {}'.format(
claim_audience, audience))
return payload | python | def decode(token, certs=None, verify=True, audience=None):
header, payload, signed_section, signature = _unverified_decode(token)
if not verify:
return payload
# If certs is specified as a dictionary of key IDs to certificates, then
# use the certificate identified by the key ID in the token header.
if isinstance(certs, collections.Mapping):
key_id = header.get('kid')
if key_id:
if key_id not in certs:
raise ValueError(
'Certificate for key id {} not found.'.format(key_id))
certs_to_check = [certs[key_id]]
# If there's no key id in the header, check against all of the certs.
else:
certs_to_check = certs.values()
else:
certs_to_check = certs
# Verify that the signature matches the message.
if not crypt.verify_signature(signed_section, signature, certs_to_check):
raise ValueError('Could not verify token signature.')
# Verify the issued at and created times in the payload.
_verify_iat_and_exp(payload)
# Check audience.
if audience is not None:
claim_audience = payload.get('aud')
if audience != claim_audience:
raise ValueError(
'Token has wrong audience {}, expected {}'.format(
claim_audience, audience))
return payload | [
"def",
"decode",
"(",
"token",
",",
"certs",
"=",
"None",
",",
"verify",
"=",
"True",
",",
"audience",
"=",
"None",
")",
":",
"header",
",",
"payload",
",",
"signed_section",
",",
"signature",
"=",
"_unverified_decode",
"(",
"token",
")",
"if",
"not",
... | Decode and verify a JWT.
Args:
token (str): The encoded JWT.
certs (Union[str, bytes, Mapping[str, Union[str, bytes]]]): The
certificate used to validate the JWT signature. If bytes or string,
it must the the public key certificate in PEM format. If a mapping,
it must be a mapping of key IDs to public key certificates in PEM
format. The mapping must contain the same key ID that's specified
in the token's header.
verify (bool): Whether to perform signature and claim validation.
Verification is done by default.
audience (str): The audience claim, 'aud', that this JWT should
contain. If None then the JWT's 'aud' parameter is not verified.
Returns:
Mapping[str, str]: The deserialized JSON payload in the JWT.
Raises:
ValueError: if any verification checks failed. | [
"Decode",
"and",
"verify",
"a",
"JWT",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/jwt.py#L197-L254 |
228,588 | googleapis/google-auth-library-python | google/auth/jwt.py | OnDemandCredentials._get_jwt_for_audience | def _get_jwt_for_audience(self, audience):
"""Get a JWT For a given audience.
If there is already an existing, non-expired token in the cache for
the audience, that token is used. Otherwise, a new token will be
created.
Args:
audience (str): The intended audience.
Returns:
bytes: The encoded JWT.
"""
token, expiry = self._cache.get(audience, (None, None))
if token is None or expiry < _helpers.utcnow():
token, expiry = self._make_jwt_for_audience(audience)
self._cache[audience] = token, expiry
return token | python | def _get_jwt_for_audience(self, audience):
token, expiry = self._cache.get(audience, (None, None))
if token is None or expiry < _helpers.utcnow():
token, expiry = self._make_jwt_for_audience(audience)
self._cache[audience] = token, expiry
return token | [
"def",
"_get_jwt_for_audience",
"(",
"self",
",",
"audience",
")",
":",
"token",
",",
"expiry",
"=",
"self",
".",
"_cache",
".",
"get",
"(",
"audience",
",",
"(",
"None",
",",
"None",
")",
")",
"if",
"token",
"is",
"None",
"or",
"expiry",
"<",
"_help... | Get a JWT For a given audience.
If there is already an existing, non-expired token in the cache for
the audience, that token is used. Otherwise, a new token will be
created.
Args:
audience (str): The intended audience.
Returns:
bytes: The encoded JWT. | [
"Get",
"a",
"JWT",
"For",
"a",
"given",
"audience",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/jwt.py#L694-L713 |
228,589 | googleapis/google-auth-library-python | google/auth/jwt.py | OnDemandCredentials.before_request | def before_request(self, request, method, url, headers):
"""Performs credential-specific before request logic.
Args:
request (Any): Unused. JWT credentials do not need to make an
HTTP request to refresh.
method (str): The request's HTTP method.
url (str): The request's URI. This is used as the audience claim
when generating the JWT.
headers (Mapping): The request's headers.
"""
# pylint: disable=unused-argument
# (pylint doesn't correctly recognize overridden methods.)
parts = urllib.parse.urlsplit(url)
# Strip query string and fragment
audience = urllib.parse.urlunsplit(
(parts.scheme, parts.netloc, parts.path, "", ""))
token = self._get_jwt_for_audience(audience)
self.apply(headers, token=token) | python | def before_request(self, request, method, url, headers):
# pylint: disable=unused-argument
# (pylint doesn't correctly recognize overridden methods.)
parts = urllib.parse.urlsplit(url)
# Strip query string and fragment
audience = urllib.parse.urlunsplit(
(parts.scheme, parts.netloc, parts.path, "", ""))
token = self._get_jwt_for_audience(audience)
self.apply(headers, token=token) | [
"def",
"before_request",
"(",
"self",
",",
"request",
",",
"method",
",",
"url",
",",
"headers",
")",
":",
"# pylint: disable=unused-argument",
"# (pylint doesn't correctly recognize overridden methods.)",
"parts",
"=",
"urllib",
".",
"parse",
".",
"urlsplit",
"(",
"u... | Performs credential-specific before request logic.
Args:
request (Any): Unused. JWT credentials do not need to make an
HTTP request to refresh.
method (str): The request's HTTP method.
url (str): The request's URI. This is used as the audience claim
when generating the JWT.
headers (Mapping): The request's headers. | [
"Performs",
"credential",
"-",
"specific",
"before",
"request",
"logic",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/jwt.py#L730-L748 |
228,590 | googleapis/google-auth-library-python | google/auth/crypt/_cryptography_rsa.py | RSAVerifier.from_string | def from_string(cls, public_key):
"""Construct an Verifier instance from a public key or public
certificate string.
Args:
public_key (Union[str, bytes]): The public key in PEM format or the
x509 public key certificate.
Returns:
Verifier: The constructed verifier.
Raises:
ValueError: If the public key can't be parsed.
"""
public_key_data = _helpers.to_bytes(public_key)
if _CERTIFICATE_MARKER in public_key_data:
cert = cryptography.x509.load_pem_x509_certificate(
public_key_data, _BACKEND)
pubkey = cert.public_key()
else:
pubkey = serialization.load_pem_public_key(
public_key_data, _BACKEND)
return cls(pubkey) | python | def from_string(cls, public_key):
public_key_data = _helpers.to_bytes(public_key)
if _CERTIFICATE_MARKER in public_key_data:
cert = cryptography.x509.load_pem_x509_certificate(
public_key_data, _BACKEND)
pubkey = cert.public_key()
else:
pubkey = serialization.load_pem_public_key(
public_key_data, _BACKEND)
return cls(pubkey) | [
"def",
"from_string",
"(",
"cls",
",",
"public_key",
")",
":",
"public_key_data",
"=",
"_helpers",
".",
"to_bytes",
"(",
"public_key",
")",
"if",
"_CERTIFICATE_MARKER",
"in",
"public_key_data",
":",
"cert",
"=",
"cryptography",
".",
"x509",
".",
"load_pem_x509_c... | Construct an Verifier instance from a public key or public
certificate string.
Args:
public_key (Union[str, bytes]): The public key in PEM format or the
x509 public key certificate.
Returns:
Verifier: The constructed verifier.
Raises:
ValueError: If the public key can't be parsed. | [
"Construct",
"an",
"Verifier",
"instance",
"from",
"a",
"public",
"key",
"or",
"public",
"certificate",
"string",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/crypt/_cryptography_rsa.py#L73-L98 |
228,591 | googleapis/google-auth-library-python | google/auth/crypt/_cryptography_rsa.py | RSASigner.from_string | def from_string(cls, key, key_id=None):
"""Construct a RSASigner from a private key in PEM format.
Args:
key (Union[bytes, str]): Private key in PEM format.
key_id (str): An optional key id used to identify the private key.
Returns:
google.auth.crypt._cryptography_rsa.RSASigner: The
constructed signer.
Raises:
ValueError: If ``key`` is not ``bytes`` or ``str`` (unicode).
UnicodeDecodeError: If ``key`` is ``bytes`` but cannot be decoded
into a UTF-8 ``str``.
ValueError: If ``cryptography`` "Could not deserialize key data."
"""
key = _helpers.to_bytes(key)
private_key = serialization.load_pem_private_key(
key, password=None, backend=_BACKEND)
return cls(private_key, key_id=key_id) | python | def from_string(cls, key, key_id=None):
key = _helpers.to_bytes(key)
private_key = serialization.load_pem_private_key(
key, password=None, backend=_BACKEND)
return cls(private_key, key_id=key_id) | [
"def",
"from_string",
"(",
"cls",
",",
"key",
",",
"key_id",
"=",
"None",
")",
":",
"key",
"=",
"_helpers",
".",
"to_bytes",
"(",
"key",
")",
"private_key",
"=",
"serialization",
".",
"load_pem_private_key",
"(",
"key",
",",
"password",
"=",
"None",
",",... | Construct a RSASigner from a private key in PEM format.
Args:
key (Union[bytes, str]): Private key in PEM format.
key_id (str): An optional key id used to identify the private key.
Returns:
google.auth.crypt._cryptography_rsa.RSASigner: The
constructed signer.
Raises:
ValueError: If ``key`` is not ``bytes`` or ``str`` (unicode).
UnicodeDecodeError: If ``key`` is ``bytes`` but cannot be decoded
into a UTF-8 ``str``.
ValueError: If ``cryptography`` "Could not deserialize key data." | [
"Construct",
"a",
"RSASigner",
"from",
"a",
"private",
"key",
"in",
"PEM",
"format",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/crypt/_cryptography_rsa.py#L129-L149 |
228,592 | googleapis/google-auth-library-python | google/auth/_default.py | _warn_about_problematic_credentials | def _warn_about_problematic_credentials(credentials):
"""Determines if the credentials are problematic.
Credentials from the Cloud SDK that are associated with Cloud SDK's project
are problematic because they may not have APIs enabled and have limited
quota. If this is the case, warn about it.
"""
from google.auth import _cloud_sdk
if credentials.client_id == _cloud_sdk.CLOUD_SDK_CLIENT_ID:
warnings.warn(_CLOUD_SDK_CREDENTIALS_WARNING) | python | def _warn_about_problematic_credentials(credentials):
from google.auth import _cloud_sdk
if credentials.client_id == _cloud_sdk.CLOUD_SDK_CLIENT_ID:
warnings.warn(_CLOUD_SDK_CREDENTIALS_WARNING) | [
"def",
"_warn_about_problematic_credentials",
"(",
"credentials",
")",
":",
"from",
"google",
".",
"auth",
"import",
"_cloud_sdk",
"if",
"credentials",
".",
"client_id",
"==",
"_cloud_sdk",
".",
"CLOUD_SDK_CLIENT_ID",
":",
"warnings",
".",
"warn",
"(",
"_CLOUD_SDK_C... | Determines if the credentials are problematic.
Credentials from the Cloud SDK that are associated with Cloud SDK's project
are problematic because they may not have APIs enabled and have limited
quota. If this is the case, warn about it. | [
"Determines",
"if",
"the",
"credentials",
"are",
"problematic",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/_default.py#L57-L66 |
228,593 | googleapis/google-auth-library-python | google/auth/_default.py | _load_credentials_from_file | def _load_credentials_from_file(filename):
"""Loads credentials from a file.
The credentials file must be a service account key or stored authorized
user credentials.
Args:
filename (str): The full path to the credentials file.
Returns:
Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded
credentials and the project ID. Authorized user credentials do not
have the project ID information.
Raises:
google.auth.exceptions.DefaultCredentialsError: if the file is in the
wrong format or is missing.
"""
if not os.path.exists(filename):
raise exceptions.DefaultCredentialsError(
'File {} was not found.'.format(filename))
with io.open(filename, 'r') as file_obj:
try:
info = json.load(file_obj)
except ValueError as caught_exc:
new_exc = exceptions.DefaultCredentialsError(
'File {} is not a valid json file.'.format(filename),
caught_exc)
six.raise_from(new_exc, caught_exc)
# The type key should indicate that the file is either a service account
# credentials file or an authorized user credentials file.
credential_type = info.get('type')
if credential_type == _AUTHORIZED_USER_TYPE:
from google.auth import _cloud_sdk
try:
credentials = _cloud_sdk.load_authorized_user_credentials(info)
except ValueError as caught_exc:
msg = 'Failed to load authorized user credentials from {}'.format(
filename)
new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
six.raise_from(new_exc, caught_exc)
# Authorized user credentials do not contain the project ID.
_warn_about_problematic_credentials(credentials)
return credentials, None
elif credential_type == _SERVICE_ACCOUNT_TYPE:
from google.oauth2 import service_account
try:
credentials = (
service_account.Credentials.from_service_account_info(info))
except ValueError as caught_exc:
msg = 'Failed to load service account credentials from {}'.format(
filename)
new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
six.raise_from(new_exc, caught_exc)
return credentials, info.get('project_id')
else:
raise exceptions.DefaultCredentialsError(
'The file {file} does not have a valid type. '
'Type is {type}, expected one of {valid_types}.'.format(
file=filename, type=credential_type, valid_types=_VALID_TYPES)) | python | def _load_credentials_from_file(filename):
if not os.path.exists(filename):
raise exceptions.DefaultCredentialsError(
'File {} was not found.'.format(filename))
with io.open(filename, 'r') as file_obj:
try:
info = json.load(file_obj)
except ValueError as caught_exc:
new_exc = exceptions.DefaultCredentialsError(
'File {} is not a valid json file.'.format(filename),
caught_exc)
six.raise_from(new_exc, caught_exc)
# The type key should indicate that the file is either a service account
# credentials file or an authorized user credentials file.
credential_type = info.get('type')
if credential_type == _AUTHORIZED_USER_TYPE:
from google.auth import _cloud_sdk
try:
credentials = _cloud_sdk.load_authorized_user_credentials(info)
except ValueError as caught_exc:
msg = 'Failed to load authorized user credentials from {}'.format(
filename)
new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
six.raise_from(new_exc, caught_exc)
# Authorized user credentials do not contain the project ID.
_warn_about_problematic_credentials(credentials)
return credentials, None
elif credential_type == _SERVICE_ACCOUNT_TYPE:
from google.oauth2 import service_account
try:
credentials = (
service_account.Credentials.from_service_account_info(info))
except ValueError as caught_exc:
msg = 'Failed to load service account credentials from {}'.format(
filename)
new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
six.raise_from(new_exc, caught_exc)
return credentials, info.get('project_id')
else:
raise exceptions.DefaultCredentialsError(
'The file {file} does not have a valid type. '
'Type is {type}, expected one of {valid_types}.'.format(
file=filename, type=credential_type, valid_types=_VALID_TYPES)) | [
"def",
"_load_credentials_from_file",
"(",
"filename",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"raise",
"exceptions",
".",
"DefaultCredentialsError",
"(",
"'File {} was not found.'",
".",
"format",
"(",
"filename",
")"... | Loads credentials from a file.
The credentials file must be a service account key or stored authorized
user credentials.
Args:
filename (str): The full path to the credentials file.
Returns:
Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded
credentials and the project ID. Authorized user credentials do not
have the project ID information.
Raises:
google.auth.exceptions.DefaultCredentialsError: if the file is in the
wrong format or is missing. | [
"Loads",
"credentials",
"from",
"a",
"file",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/_default.py#L69-L135 |
228,594 | googleapis/google-auth-library-python | google/auth/_default.py | _get_gcloud_sdk_credentials | def _get_gcloud_sdk_credentials():
"""Gets the credentials and project ID from the Cloud SDK."""
from google.auth import _cloud_sdk
# Check if application default credentials exist.
credentials_filename = (
_cloud_sdk.get_application_default_credentials_path())
if not os.path.isfile(credentials_filename):
return None, None
credentials, project_id = _load_credentials_from_file(
credentials_filename)
if not project_id:
project_id = _cloud_sdk.get_project_id()
return credentials, project_id | python | def _get_gcloud_sdk_credentials():
from google.auth import _cloud_sdk
# Check if application default credentials exist.
credentials_filename = (
_cloud_sdk.get_application_default_credentials_path())
if not os.path.isfile(credentials_filename):
return None, None
credentials, project_id = _load_credentials_from_file(
credentials_filename)
if not project_id:
project_id = _cloud_sdk.get_project_id()
return credentials, project_id | [
"def",
"_get_gcloud_sdk_credentials",
"(",
")",
":",
"from",
"google",
".",
"auth",
"import",
"_cloud_sdk",
"# Check if application default credentials exist.",
"credentials_filename",
"=",
"(",
"_cloud_sdk",
".",
"get_application_default_credentials_path",
"(",
")",
")",
"... | Gets the credentials and project ID from the Cloud SDK. | [
"Gets",
"the",
"credentials",
"and",
"project",
"ID",
"from",
"the",
"Cloud",
"SDK",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/_default.py#L138-L155 |
228,595 | googleapis/google-auth-library-python | google/auth/_default.py | _get_explicit_environ_credentials | def _get_explicit_environ_credentials():
"""Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment
variable."""
explicit_file = os.environ.get(environment_vars.CREDENTIALS)
if explicit_file is not None:
credentials, project_id = _load_credentials_from_file(
os.environ[environment_vars.CREDENTIALS])
return credentials, project_id
else:
return None, None | python | def _get_explicit_environ_credentials():
explicit_file = os.environ.get(environment_vars.CREDENTIALS)
if explicit_file is not None:
credentials, project_id = _load_credentials_from_file(
os.environ[environment_vars.CREDENTIALS])
return credentials, project_id
else:
return None, None | [
"def",
"_get_explicit_environ_credentials",
"(",
")",
":",
"explicit_file",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"environment_vars",
".",
"CREDENTIALS",
")",
"if",
"explicit_file",
"is",
"not",
"None",
":",
"credentials",
",",
"project_id",
"=",
"_load_cr... | Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment
variable. | [
"Gets",
"credentials",
"from",
"the",
"GOOGLE_APPLICATION_CREDENTIALS",
"environment",
"variable",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/_default.py#L158-L170 |
228,596 | googleapis/google-auth-library-python | google/auth/_default.py | _get_gae_credentials | def _get_gae_credentials():
"""Gets Google App Engine App Identity credentials and project ID."""
# While this library is normally bundled with app_engine, there are
# some cases where it's not available, so we tolerate ImportError.
try:
import google.auth.app_engine as app_engine
except ImportError:
return None, None
try:
credentials = app_engine.Credentials()
project_id = app_engine.get_project_id()
return credentials, project_id
except EnvironmentError:
return None, None | python | def _get_gae_credentials():
# While this library is normally bundled with app_engine, there are
# some cases where it's not available, so we tolerate ImportError.
try:
import google.auth.app_engine as app_engine
except ImportError:
return None, None
try:
credentials = app_engine.Credentials()
project_id = app_engine.get_project_id()
return credentials, project_id
except EnvironmentError:
return None, None | [
"def",
"_get_gae_credentials",
"(",
")",
":",
"# While this library is normally bundled with app_engine, there are",
"# some cases where it's not available, so we tolerate ImportError.",
"try",
":",
"import",
"google",
".",
"auth",
".",
"app_engine",
"as",
"app_engine",
"except",
... | Gets Google App Engine App Identity credentials and project ID. | [
"Gets",
"Google",
"App",
"Engine",
"App",
"Identity",
"credentials",
"and",
"project",
"ID",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/_default.py#L173-L187 |
228,597 | googleapis/google-auth-library-python | google/auth/_default.py | _get_gce_credentials | def _get_gce_credentials(request=None):
"""Gets credentials and project ID from the GCE Metadata Service."""
# Ping requires a transport, but we want application default credentials
# to require no arguments. So, we'll use the _http_client transport which
# uses http.client. This is only acceptable because the metadata server
# doesn't do SSL and never requires proxies.
# While this library is normally bundled with compute_engine, there are
# some cases where it's not available, so we tolerate ImportError.
try:
from google.auth import compute_engine
from google.auth.compute_engine import _metadata
except ImportError:
return None, None
if request is None:
request = google.auth.transport._http_client.Request()
if _metadata.ping(request=request):
# Get the project ID.
try:
project_id = _metadata.get_project_id(request=request)
except exceptions.TransportError:
project_id = None
return compute_engine.Credentials(), project_id
else:
return None, None | python | def _get_gce_credentials(request=None):
# Ping requires a transport, but we want application default credentials
# to require no arguments. So, we'll use the _http_client transport which
# uses http.client. This is only acceptable because the metadata server
# doesn't do SSL and never requires proxies.
# While this library is normally bundled with compute_engine, there are
# some cases where it's not available, so we tolerate ImportError.
try:
from google.auth import compute_engine
from google.auth.compute_engine import _metadata
except ImportError:
return None, None
if request is None:
request = google.auth.transport._http_client.Request()
if _metadata.ping(request=request):
# Get the project ID.
try:
project_id = _metadata.get_project_id(request=request)
except exceptions.TransportError:
project_id = None
return compute_engine.Credentials(), project_id
else:
return None, None | [
"def",
"_get_gce_credentials",
"(",
"request",
"=",
"None",
")",
":",
"# Ping requires a transport, but we want application default credentials",
"# to require no arguments. So, we'll use the _http_client transport which",
"# uses http.client. This is only acceptable because the metadata server"... | Gets credentials and project ID from the GCE Metadata Service. | [
"Gets",
"credentials",
"and",
"project",
"ID",
"from",
"the",
"GCE",
"Metadata",
"Service",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/_default.py#L190-L217 |
228,598 | googleapis/google-auth-library-python | google/auth/_default.py | default | def default(scopes=None, request=None):
"""Gets the default credentials for the current environment.
`Application Default Credentials`_ provides an easy way to obtain
credentials to call Google APIs for server-to-server or local applications.
This function acquires credentials from the environment in the following
order:
1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set
to the path of a valid service account JSON private key file, then it is
loaded and returned. The project ID returned is the project ID defined
in the service account file if available (some older files do not
contain project ID information).
2. If the `Google Cloud SDK`_ is installed and has application default
credentials set they are loaded and returned.
To enable application default credentials with the Cloud SDK run::
gcloud auth application-default login
If the Cloud SDK has an active project, the project ID is returned. The
active project can be set using::
gcloud config set project
3. If the application is running in the `App Engine standard environment`_
then the credentials and project ID from the `App Identity Service`_
are used.
4. If the application is running in `Compute Engine`_ or the
`App Engine flexible environment`_ then the credentials and project ID
are obtained from the `Metadata Service`_.
5. If no credentials are found,
:class:`~google.auth.exceptions.DefaultCredentialsError` will be raised.
.. _Application Default Credentials: https://developers.google.com\
/identity/protocols/application-default-credentials
.. _Google Cloud SDK: https://cloud.google.com/sdk
.. _App Engine standard environment: https://cloud.google.com/appengine
.. _App Identity Service: https://cloud.google.com/appengine/docs/python\
/appidentity/
.. _Compute Engine: https://cloud.google.com/compute
.. _App Engine flexible environment: https://cloud.google.com\
/appengine/flexible
.. _Metadata Service: https://cloud.google.com/compute/docs\
/storing-retrieving-metadata
Example::
import google.auth
credentials, project_id = google.auth.default()
Args:
scopes (Sequence[str]): The list of scopes for the credentials. If
specified, the credentials will automatically be scoped if
necessary.
request (google.auth.transport.Request): An object used to make
HTTP requests. This is used to detect whether the application
is running on Compute Engine. If not specified, then it will
use the standard library http client to make requests.
Returns:
Tuple[~google.auth.credentials.Credentials, Optional[str]]:
the current environment's credentials and project ID. Project ID
may be None, which indicates that the Project ID could not be
ascertained from the environment.
Raises:
~google.auth.exceptions.DefaultCredentialsError:
If no credentials were found, or if the credentials found were
invalid.
"""
from google.auth.credentials import with_scopes_if_required
explicit_project_id = os.environ.get(
environment_vars.PROJECT,
os.environ.get(environment_vars.LEGACY_PROJECT))
checkers = (
_get_explicit_environ_credentials,
_get_gcloud_sdk_credentials,
_get_gae_credentials,
lambda: _get_gce_credentials(request))
for checker in checkers:
credentials, project_id = checker()
if credentials is not None:
credentials = with_scopes_if_required(credentials, scopes)
effective_project_id = explicit_project_id or project_id
if not effective_project_id:
_LOGGER.warning(
'No project ID could be determined. Consider running '
'`gcloud config set project` or setting the %s '
'environment variable',
environment_vars.PROJECT)
return credentials, effective_project_id
raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) | python | def default(scopes=None, request=None):
from google.auth.credentials import with_scopes_if_required
explicit_project_id = os.environ.get(
environment_vars.PROJECT,
os.environ.get(environment_vars.LEGACY_PROJECT))
checkers = (
_get_explicit_environ_credentials,
_get_gcloud_sdk_credentials,
_get_gae_credentials,
lambda: _get_gce_credentials(request))
for checker in checkers:
credentials, project_id = checker()
if credentials is not None:
credentials = with_scopes_if_required(credentials, scopes)
effective_project_id = explicit_project_id or project_id
if not effective_project_id:
_LOGGER.warning(
'No project ID could be determined. Consider running '
'`gcloud config set project` or setting the %s '
'environment variable',
environment_vars.PROJECT)
return credentials, effective_project_id
raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) | [
"def",
"default",
"(",
"scopes",
"=",
"None",
",",
"request",
"=",
"None",
")",
":",
"from",
"google",
".",
"auth",
".",
"credentials",
"import",
"with_scopes_if_required",
"explicit_project_id",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"environment_vars",
... | Gets the default credentials for the current environment.
`Application Default Credentials`_ provides an easy way to obtain
credentials to call Google APIs for server-to-server or local applications.
This function acquires credentials from the environment in the following
order:
1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set
to the path of a valid service account JSON private key file, then it is
loaded and returned. The project ID returned is the project ID defined
in the service account file if available (some older files do not
contain project ID information).
2. If the `Google Cloud SDK`_ is installed and has application default
credentials set they are loaded and returned.
To enable application default credentials with the Cloud SDK run::
gcloud auth application-default login
If the Cloud SDK has an active project, the project ID is returned. The
active project can be set using::
gcloud config set project
3. If the application is running in the `App Engine standard environment`_
then the credentials and project ID from the `App Identity Service`_
are used.
4. If the application is running in `Compute Engine`_ or the
`App Engine flexible environment`_ then the credentials and project ID
are obtained from the `Metadata Service`_.
5. If no credentials are found,
:class:`~google.auth.exceptions.DefaultCredentialsError` will be raised.
.. _Application Default Credentials: https://developers.google.com\
/identity/protocols/application-default-credentials
.. _Google Cloud SDK: https://cloud.google.com/sdk
.. _App Engine standard environment: https://cloud.google.com/appengine
.. _App Identity Service: https://cloud.google.com/appengine/docs/python\
/appidentity/
.. _Compute Engine: https://cloud.google.com/compute
.. _App Engine flexible environment: https://cloud.google.com\
/appengine/flexible
.. _Metadata Service: https://cloud.google.com/compute/docs\
/storing-retrieving-metadata
Example::
import google.auth
credentials, project_id = google.auth.default()
Args:
scopes (Sequence[str]): The list of scopes for the credentials. If
specified, the credentials will automatically be scoped if
necessary.
request (google.auth.transport.Request): An object used to make
HTTP requests. This is used to detect whether the application
is running on Compute Engine. If not specified, then it will
use the standard library http client to make requests.
Returns:
Tuple[~google.auth.credentials.Credentials, Optional[str]]:
the current environment's credentials and project ID. Project ID
may be None, which indicates that the Project ID could not be
ascertained from the environment.
Raises:
~google.auth.exceptions.DefaultCredentialsError:
If no credentials were found, or if the credentials found were
invalid. | [
"Gets",
"the",
"default",
"credentials",
"for",
"the",
"current",
"environment",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/_default.py#L220-L317 |
228,599 | googleapis/google-auth-library-python | google/auth/transport/grpc.py | AuthMetadataPlugin._get_authorization_headers | def _get_authorization_headers(self, context):
"""Gets the authorization headers for a request.
Returns:
Sequence[Tuple[str, str]]: A list of request headers (key, value)
to add to the request.
"""
headers = {}
self._credentials.before_request(
self._request,
context.method_name,
context.service_url,
headers)
return list(six.iteritems(headers)) | python | def _get_authorization_headers(self, context):
headers = {}
self._credentials.before_request(
self._request,
context.method_name,
context.service_url,
headers)
return list(six.iteritems(headers)) | [
"def",
"_get_authorization_headers",
"(",
"self",
",",
"context",
")",
":",
"headers",
"=",
"{",
"}",
"self",
".",
"_credentials",
".",
"before_request",
"(",
"self",
".",
"_request",
",",
"context",
".",
"method_name",
",",
"context",
".",
"service_url",
",... | Gets the authorization headers for a request.
Returns:
Sequence[Tuple[str, str]]: A list of request headers (key, value)
to add to the request. | [
"Gets",
"the",
"authorization",
"headers",
"for",
"a",
"request",
"."
] | 2c6ad78917e936f38f87c946209c8031166dc96e | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/transport/grpc.py#L53-L67 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.