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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
24,200 | icgood/pymap | pymap/selected.py | SynchronizedMessages.get_all | def get_all(self, seq_set: SequenceSet) \
-> Sequence[Tuple[int, CachedMessage]]:
"""Return the cached messages, and their sequence numbers, for the
given sequence set.
Args:
seq_set: The message sequence set.
"""
if seq_set.uid:
all_uids = seq_set.flatten(self.max_uid) & self._uids
return [(seq, self._cache[uid])
for seq, uid in enumerate(self._sorted, 1)
if uid in all_uids]
else:
all_seqs = seq_set.flatten(self.exists)
return [(seq, self._cache[uid])
for seq, uid in enumerate(self._sorted, 1)
if seq in all_seqs] | python | def get_all(self, seq_set: SequenceSet) \
-> Sequence[Tuple[int, CachedMessage]]:
if seq_set.uid:
all_uids = seq_set.flatten(self.max_uid) & self._uids
return [(seq, self._cache[uid])
for seq, uid in enumerate(self._sorted, 1)
if uid in all_uids]
else:
all_seqs = seq_set.flatten(self.exists)
return [(seq, self._cache[uid])
for seq, uid in enumerate(self._sorted, 1)
if seq in all_seqs] | [
"def",
"get_all",
"(",
"self",
",",
"seq_set",
":",
"SequenceSet",
")",
"->",
"Sequence",
"[",
"Tuple",
"[",
"int",
",",
"CachedMessage",
"]",
"]",
":",
"if",
"seq_set",
".",
"uid",
":",
"all_uids",
"=",
"seq_set",
".",
"flatten",
"(",
"self",
".",
"... | Return the cached messages, and their sequence numbers, for the
given sequence set.
Args:
seq_set: The message sequence set. | [
"Return",
"the",
"cached",
"messages",
"and",
"their",
"sequence",
"numbers",
"for",
"the",
"given",
"sequence",
"set",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/selected.py#L170-L188 |
24,201 | icgood/pymap | pymap/selected.py | SelectedMailbox.add_updates | def add_updates(self, messages: Iterable[CachedMessage],
expunged: Iterable[int]) -> None:
"""Update the messages in the selected mailboxes. The ``messages``
should include non-expunged messages in the mailbox that should be
checked for updates. The ``expunged`` argument is the set of UIDs that
have been expunged from the mailbox.
In an optimized implementation, ``messages`` only includes new messages
or messages with metadata updates. This minimizes the comparison
needed to determine what untagged responses are necessary. The
:attr:`.mod_sequence` attribute may be used to support this
optimization.
If a backend implementation lacks the ability to determine the subset
of messages that have been updated, it should instead use
:meth:`.set_messages`.
Args:
messages: The cached message objects to add.
expunged: The set of message UIDs that have been expunged.
"""
self._messages._update(messages)
self._messages._remove(expunged, self._hide_expunged)
if not self._hide_expunged:
self._session_flags.remove(expunged) | python | def add_updates(self, messages: Iterable[CachedMessage],
expunged: Iterable[int]) -> None:
self._messages._update(messages)
self._messages._remove(expunged, self._hide_expunged)
if not self._hide_expunged:
self._session_flags.remove(expunged) | [
"def",
"add_updates",
"(",
"self",
",",
"messages",
":",
"Iterable",
"[",
"CachedMessage",
"]",
",",
"expunged",
":",
"Iterable",
"[",
"int",
"]",
")",
"->",
"None",
":",
"self",
".",
"_messages",
".",
"_update",
"(",
"messages",
")",
"self",
".",
"_me... | Update the messages in the selected mailboxes. The ``messages``
should include non-expunged messages in the mailbox that should be
checked for updates. The ``expunged`` argument is the set of UIDs that
have been expunged from the mailbox.
In an optimized implementation, ``messages`` only includes new messages
or messages with metadata updates. This minimizes the comparison
needed to determine what untagged responses are necessary. The
:attr:`.mod_sequence` attribute may be used to support this
optimization.
If a backend implementation lacks the ability to determine the subset
of messages that have been updated, it should instead use
:meth:`.set_messages`.
Args:
messages: The cached message objects to add.
expunged: The set of message UIDs that have been expunged. | [
"Update",
"the",
"messages",
"in",
"the",
"selected",
"mailboxes",
".",
"The",
"messages",
"should",
"include",
"non",
"-",
"expunged",
"messages",
"in",
"the",
"mailbox",
"that",
"should",
"be",
"checked",
"for",
"updates",
".",
"The",
"expunged",
"argument",... | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/selected.py#L281-L306 |
24,202 | icgood/pymap | pymap/selected.py | SelectedMailbox.silence | def silence(self, seq_set: SequenceSet, flag_set: AbstractSet[Flag],
flag_op: FlagOp) -> None:
"""Runs the flags update against the cached flags, to prevent untagged
FETCH responses unless other updates have occurred.
For example, if a session adds ``\\Deleted`` and calls this method,
the FETCH response will be silenced. But if another added ``\\Seen``
at the same time, the FETCH response will be sent.
Args:
seq_set: The sequence set of messages.
flag_set: The set of flags for the update operation.
flag_op: The mode to change the flags.
"""
session_flags = self.session_flags
permanent_flag_set = self.permanent_flags & flag_set
session_flag_set = session_flags & flag_set
for seq, msg in self._messages.get_all(seq_set):
msg_flags = msg.permanent_flags
msg_sflags = session_flags.get(msg.uid)
updated_flags = flag_op.apply(msg_flags, permanent_flag_set)
updated_sflags = flag_op.apply(msg_sflags, session_flag_set)
if msg_flags != updated_flags:
self._silenced_flags.add((msg.uid, updated_flags))
if msg_sflags != updated_sflags:
self._silenced_sflags.add((msg.uid, updated_sflags)) | python | def silence(self, seq_set: SequenceSet, flag_set: AbstractSet[Flag],
flag_op: FlagOp) -> None:
session_flags = self.session_flags
permanent_flag_set = self.permanent_flags & flag_set
session_flag_set = session_flags & flag_set
for seq, msg in self._messages.get_all(seq_set):
msg_flags = msg.permanent_flags
msg_sflags = session_flags.get(msg.uid)
updated_flags = flag_op.apply(msg_flags, permanent_flag_set)
updated_sflags = flag_op.apply(msg_sflags, session_flag_set)
if msg_flags != updated_flags:
self._silenced_flags.add((msg.uid, updated_flags))
if msg_sflags != updated_sflags:
self._silenced_sflags.add((msg.uid, updated_sflags)) | [
"def",
"silence",
"(",
"self",
",",
"seq_set",
":",
"SequenceSet",
",",
"flag_set",
":",
"AbstractSet",
"[",
"Flag",
"]",
",",
"flag_op",
":",
"FlagOp",
")",
"->",
"None",
":",
"session_flags",
"=",
"self",
".",
"session_flags",
"permanent_flag_set",
"=",
... | Runs the flags update against the cached flags, to prevent untagged
FETCH responses unless other updates have occurred.
For example, if a session adds ``\\Deleted`` and calls this method,
the FETCH response will be silenced. But if another added ``\\Seen``
at the same time, the FETCH response will be sent.
Args:
seq_set: The sequence set of messages.
flag_set: The set of flags for the update operation.
flag_op: The mode to change the flags. | [
"Runs",
"the",
"flags",
"update",
"against",
"the",
"cached",
"flags",
"to",
"prevent",
"untagged",
"FETCH",
"responses",
"unless",
"other",
"updates",
"have",
"occurred",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/selected.py#L349-L375 |
24,203 | icgood/pymap | pymap/selected.py | SelectedMailbox.fork | def fork(self, command: Command) \
-> Tuple['SelectedMailbox', Iterable[Response]]:
"""Compares the state of the current object to that of the last fork,
returning the untagged responses that reflect any changes. A new copy
of the object is also returned, ready for the next command.
Args:
command: The command that was finished.
"""
frozen = _Frozen(self)
cls = type(self)
copy = cls(self._guid, self._readonly, self._permanent_flags,
self._session_flags, self._selected_set, self._lookup,
_mod_sequence=self._mod_sequence,
_prev=frozen, _messages=self._messages)
if self._prev is not None:
with_uid: bool = getattr(command, 'uid', False)
untagged = self._compare(self._prev, frozen, with_uid)
else:
untagged = []
return copy, untagged | python | def fork(self, command: Command) \
-> Tuple['SelectedMailbox', Iterable[Response]]:
frozen = _Frozen(self)
cls = type(self)
copy = cls(self._guid, self._readonly, self._permanent_flags,
self._session_flags, self._selected_set, self._lookup,
_mod_sequence=self._mod_sequence,
_prev=frozen, _messages=self._messages)
if self._prev is not None:
with_uid: bool = getattr(command, 'uid', False)
untagged = self._compare(self._prev, frozen, with_uid)
else:
untagged = []
return copy, untagged | [
"def",
"fork",
"(",
"self",
",",
"command",
":",
"Command",
")",
"->",
"Tuple",
"[",
"'SelectedMailbox'",
",",
"Iterable",
"[",
"Response",
"]",
"]",
":",
"frozen",
"=",
"_Frozen",
"(",
"self",
")",
"cls",
"=",
"type",
"(",
"self",
")",
"copy",
"=",
... | Compares the state of the current object to that of the last fork,
returning the untagged responses that reflect any changes. A new copy
of the object is also returned, ready for the next command.
Args:
command: The command that was finished. | [
"Compares",
"the",
"state",
"of",
"the",
"current",
"object",
"to",
"that",
"of",
"the",
"last",
"fork",
"returning",
"the",
"untagged",
"responses",
"that",
"reflect",
"any",
"changes",
".",
"A",
"new",
"copy",
"of",
"the",
"object",
"is",
"also",
"return... | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/selected.py#L377-L398 |
24,204 | icgood/pymap | pymap/parsing/command/select.py | IdleCommand.parse_done | def parse_done(self, buf: memoryview) -> Tuple[bool, memoryview]:
"""Parse the continuation line sent by the client to end the ``IDLE``
command.
Args:
buf: The continuation line to parse.
"""
match = self._pattern.match(buf)
if not match:
raise NotParseable(buf)
done = match.group(1).upper() == self.continuation
buf = buf[match.end(0):]
return done, buf | python | def parse_done(self, buf: memoryview) -> Tuple[bool, memoryview]:
match = self._pattern.match(buf)
if not match:
raise NotParseable(buf)
done = match.group(1).upper() == self.continuation
buf = buf[match.end(0):]
return done, buf | [
"def",
"parse_done",
"(",
"self",
",",
"buf",
":",
"memoryview",
")",
"->",
"Tuple",
"[",
"bool",
",",
"memoryview",
"]",
":",
"match",
"=",
"self",
".",
"_pattern",
".",
"match",
"(",
"buf",
")",
"if",
"not",
"match",
":",
"raise",
"NotParseable",
"... | Parse the continuation line sent by the client to end the ``IDLE``
command.
Args:
buf: The continuation line to parse. | [
"Parse",
"the",
"continuation",
"line",
"sent",
"by",
"the",
"client",
"to",
"end",
"the",
"IDLE",
"command",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/command/select.py#L485-L498 |
24,205 | icgood/pymap | pymap/backend/maildir/subscriptions.py | Subscriptions.set | def set(self, folder: str, subscribed: bool) -> None:
"""Set the subscribed status of a folder."""
if subscribed:
self.add(folder)
else:
self.remove(folder) | python | def set(self, folder: str, subscribed: bool) -> None:
if subscribed:
self.add(folder)
else:
self.remove(folder) | [
"def",
"set",
"(",
"self",
",",
"folder",
":",
"str",
",",
"subscribed",
":",
"bool",
")",
"->",
"None",
":",
"if",
"subscribed",
":",
"self",
".",
"add",
"(",
"folder",
")",
"else",
":",
"self",
".",
"remove",
"(",
"folder",
")"
] | Set the subscribed status of a folder. | [
"Set",
"the",
"subscribed",
"status",
"of",
"a",
"folder",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/maildir/subscriptions.py#L41-L46 |
24,206 | icgood/pymap | pymap/mailbox.py | MailboxSnapshot.new_uid_validity | def new_uid_validity(cls) -> int:
"""Generate a new UID validity value for a mailbox, where the first
two bytes are time-based and the second two bytes are random.
"""
time_part = int(time.time()) % 4096
rand_part = random.randint(0, 1048576)
return (time_part << 20) + rand_part | python | def new_uid_validity(cls) -> int:
time_part = int(time.time()) % 4096
rand_part = random.randint(0, 1048576)
return (time_part << 20) + rand_part | [
"def",
"new_uid_validity",
"(",
"cls",
")",
"->",
"int",
":",
"time_part",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"%",
"4096",
"rand_part",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"1048576",
")",
"return",
"(",
"time_part",
"<<",
... | Generate a new UID validity value for a mailbox, where the first
two bytes are time-based and the second two bytes are random. | [
"Generate",
"a",
"new",
"UID",
"validity",
"value",
"for",
"a",
"mailbox",
"where",
"the",
"first",
"two",
"bytes",
"are",
"time",
"-",
"based",
"and",
"the",
"second",
"two",
"bytes",
"are",
"random",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mailbox.py#L56-L63 |
24,207 | icgood/pymap | pymap/backend/maildir/flags.py | MaildirFlags.to_maildir | def to_maildir(self, flags: Iterable[Union[bytes, Flag]]) -> str:
"""Return the string of letter codes that are used to map to defined
IMAP flags and keywords.
Args:
flags: The flags and keywords to map.
"""
codes = []
for flag in flags:
if isinstance(flag, bytes):
flag = Flag(flag)
from_sys = self._from_sys.get(flag)
if from_sys is not None:
codes.append(from_sys)
else:
from_kwd = self._from_kwd.get(flag)
if from_kwd is not None:
codes.append(from_kwd)
return ''.join(codes) | python | def to_maildir(self, flags: Iterable[Union[bytes, Flag]]) -> str:
codes = []
for flag in flags:
if isinstance(flag, bytes):
flag = Flag(flag)
from_sys = self._from_sys.get(flag)
if from_sys is not None:
codes.append(from_sys)
else:
from_kwd = self._from_kwd.get(flag)
if from_kwd is not None:
codes.append(from_kwd)
return ''.join(codes) | [
"def",
"to_maildir",
"(",
"self",
",",
"flags",
":",
"Iterable",
"[",
"Union",
"[",
"bytes",
",",
"Flag",
"]",
"]",
")",
"->",
"str",
":",
"codes",
"=",
"[",
"]",
"for",
"flag",
"in",
"flags",
":",
"if",
"isinstance",
"(",
"flag",
",",
"bytes",
"... | Return the string of letter codes that are used to map to defined
IMAP flags and keywords.
Args:
flags: The flags and keywords to map. | [
"Return",
"the",
"string",
"of",
"letter",
"codes",
"that",
"are",
"used",
"to",
"map",
"to",
"defined",
"IMAP",
"flags",
"and",
"keywords",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/maildir/flags.py#L71-L90 |
24,208 | icgood/pymap | pymap/backend/maildir/flags.py | MaildirFlags.from_maildir | def from_maildir(self, codes: str) -> FrozenSet[Flag]:
"""Return the set of IMAP flags that correspond to the letter codes.
Args:
codes: The letter codes to map.
"""
flags = set()
for code in codes:
if code == ',':
break
to_sys = self._to_sys.get(code)
if to_sys is not None:
flags.add(to_sys)
else:
to_kwd = self._to_kwd.get(code)
if to_kwd is not None:
flags.add(to_kwd)
return frozenset(flags) | python | def from_maildir(self, codes: str) -> FrozenSet[Flag]:
flags = set()
for code in codes:
if code == ',':
break
to_sys = self._to_sys.get(code)
if to_sys is not None:
flags.add(to_sys)
else:
to_kwd = self._to_kwd.get(code)
if to_kwd is not None:
flags.add(to_kwd)
return frozenset(flags) | [
"def",
"from_maildir",
"(",
"self",
",",
"codes",
":",
"str",
")",
"->",
"FrozenSet",
"[",
"Flag",
"]",
":",
"flags",
"=",
"set",
"(",
")",
"for",
"code",
"in",
"codes",
":",
"if",
"code",
"==",
"','",
":",
"break",
"to_sys",
"=",
"self",
".",
"_... | Return the set of IMAP flags that correspond to the letter codes.
Args:
codes: The letter codes to map. | [
"Return",
"the",
"set",
"of",
"IMAP",
"flags",
"that",
"correspond",
"to",
"the",
"letter",
"codes",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/maildir/flags.py#L92-L110 |
24,209 | icgood/pymap | pymap/backend/dict/__init__.py | Session.login | async def login(cls, credentials: AuthenticationCredentials,
config: Config) -> 'Session':
"""Checks the given credentials for a valid login and returns a new
session. The mailbox data is shared between concurrent and future
sessions, but only for the lifetime of the process.
"""
user = credentials.authcid
password = cls._get_password(config, user)
if user != credentials.identity:
raise InvalidAuth()
elif not credentials.check_secret(password):
raise InvalidAuth()
mailbox_set, filter_set = config.set_cache.get(user, (None, None))
if not mailbox_set or not filter_set:
mailbox_set = MailboxSet()
filter_set = FilterSet()
if config.demo_data:
await cls._load_demo(mailbox_set, filter_set)
config.set_cache[user] = (mailbox_set, filter_set)
return cls(credentials.identity, config, mailbox_set, filter_set) | python | async def login(cls, credentials: AuthenticationCredentials,
config: Config) -> 'Session':
user = credentials.authcid
password = cls._get_password(config, user)
if user != credentials.identity:
raise InvalidAuth()
elif not credentials.check_secret(password):
raise InvalidAuth()
mailbox_set, filter_set = config.set_cache.get(user, (None, None))
if not mailbox_set or not filter_set:
mailbox_set = MailboxSet()
filter_set = FilterSet()
if config.demo_data:
await cls._load_demo(mailbox_set, filter_set)
config.set_cache[user] = (mailbox_set, filter_set)
return cls(credentials.identity, config, mailbox_set, filter_set) | [
"async",
"def",
"login",
"(",
"cls",
",",
"credentials",
":",
"AuthenticationCredentials",
",",
"config",
":",
"Config",
")",
"->",
"'Session'",
":",
"user",
"=",
"credentials",
".",
"authcid",
"password",
"=",
"cls",
".",
"_get_password",
"(",
"config",
","... | Checks the given credentials for a valid login and returns a new
session. The mailbox data is shared between concurrent and future
sessions, but only for the lifetime of the process. | [
"Checks",
"the",
"given",
"credentials",
"for",
"a",
"valid",
"login",
"and",
"returns",
"a",
"new",
"session",
".",
"The",
"mailbox",
"data",
"is",
"shared",
"between",
"concurrent",
"and",
"future",
"sessions",
"but",
"only",
"for",
"the",
"lifetime",
"of"... | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/dict/__init__.py#L125-L145 |
24,210 | icgood/pymap | pymap/mime/cte.py | MessageDecoder.of | def of(cls, msg_header: MessageHeader) -> 'MessageDecoder':
"""Return a decoder from the message header object.
See Also:
:meth:`.of_cte`
Args:
msg_header: The message header object.
"""
cte_hdr = msg_header.parsed.content_transfer_encoding
return cls.of_cte(cte_hdr) | python | def of(cls, msg_header: MessageHeader) -> 'MessageDecoder':
cte_hdr = msg_header.parsed.content_transfer_encoding
return cls.of_cte(cte_hdr) | [
"def",
"of",
"(",
"cls",
",",
"msg_header",
":",
"MessageHeader",
")",
"->",
"'MessageDecoder'",
":",
"cte_hdr",
"=",
"msg_header",
".",
"parsed",
".",
"content_transfer_encoding",
"return",
"cls",
".",
"of_cte",
"(",
"cte_hdr",
")"
] | Return a decoder from the message header object.
See Also:
:meth:`.of_cte`
Args:
msg_header: The message header object. | [
"Return",
"a",
"decoder",
"from",
"the",
"message",
"header",
"object",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/cte.py#L27-L38 |
24,211 | icgood/pymap | pymap/mime/cte.py | MessageDecoder.of_cte | def of_cte(cls, header: Optional[ContentTransferEncodingHeader]) \
-> 'MessageDecoder':
"""Return a decoder from the CTE header value.
There is built-in support for ``7bit``, ``8bit``, ``quoted-printable``,
and ``base64`` CTE header values. Decoders can be added or overridden
with the :attr:`.registry` dictionary.
Args:
header: The CTE header value.
"""
if header is None:
return _NoopDecoder()
hdr_str = str(header).lower()
custom = cls.registry.get(hdr_str)
if custom is not None:
return custom
elif hdr_str in ('7bit', '8bit'):
return _NoopDecoder()
elif hdr_str == 'quoted-printable':
return _QuotedPrintableDecoder()
elif hdr_str == 'base64':
return _Base64Decoder()
else:
raise NotImplementedError(hdr_str) | python | def of_cte(cls, header: Optional[ContentTransferEncodingHeader]) \
-> 'MessageDecoder':
if header is None:
return _NoopDecoder()
hdr_str = str(header).lower()
custom = cls.registry.get(hdr_str)
if custom is not None:
return custom
elif hdr_str in ('7bit', '8bit'):
return _NoopDecoder()
elif hdr_str == 'quoted-printable':
return _QuotedPrintableDecoder()
elif hdr_str == 'base64':
return _Base64Decoder()
else:
raise NotImplementedError(hdr_str) | [
"def",
"of_cte",
"(",
"cls",
",",
"header",
":",
"Optional",
"[",
"ContentTransferEncodingHeader",
"]",
")",
"->",
"'MessageDecoder'",
":",
"if",
"header",
"is",
"None",
":",
"return",
"_NoopDecoder",
"(",
")",
"hdr_str",
"=",
"str",
"(",
"header",
")",
".... | Return a decoder from the CTE header value.
There is built-in support for ``7bit``, ``8bit``, ``quoted-printable``,
and ``base64`` CTE header values. Decoders can be added or overridden
with the :attr:`.registry` dictionary.
Args:
header: The CTE header value. | [
"Return",
"a",
"decoder",
"from",
"the",
"CTE",
"header",
"value",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/cte.py#L41-L66 |
24,212 | icgood/pymap | pymap/backend/maildir/__init__.py | Session.find_user | async def find_user(cls, config: Config, user: str) \
-> Tuple[str, str]:
"""If the given user ID exists, return its expected password and
mailbox path. Override this method to implement custom login logic.
Args:
config: The maildir config object.
user: The expected user ID.
Raises:
InvalidAuth: The user ID was not valid.
"""
with open(config.users_file, 'r') as users_file:
for line in users_file:
this_user, user_dir, password = line.split(':', 2)
if user == this_user:
return password.rstrip('\r\n'), user_dir or user
raise InvalidAuth() | python | async def find_user(cls, config: Config, user: str) \
-> Tuple[str, str]:
with open(config.users_file, 'r') as users_file:
for line in users_file:
this_user, user_dir, password = line.split(':', 2)
if user == this_user:
return password.rstrip('\r\n'), user_dir or user
raise InvalidAuth() | [
"async",
"def",
"find_user",
"(",
"cls",
",",
"config",
":",
"Config",
",",
"user",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"with",
"open",
"(",
"config",
".",
"users_file",
",",
"'r'",
")",
"as",
"users_file",
":",
"for",... | If the given user ID exists, return its expected password and
mailbox path. Override this method to implement custom login logic.
Args:
config: The maildir config object.
user: The expected user ID.
Raises:
InvalidAuth: The user ID was not valid. | [
"If",
"the",
"given",
"user",
"ID",
"exists",
"return",
"its",
"expected",
"password",
"and",
"mailbox",
"path",
".",
"Override",
"this",
"method",
"to",
"implement",
"custom",
"login",
"logic",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/maildir/__init__.py#L208-L226 |
24,213 | icgood/pymap | pymap/parsing/modutf7.py | modutf7_encode | def modutf7_encode(data: str) -> bytes:
"""Encode the string using modified UTF-7.
Args:
data: The input string to encode.
"""
ret = bytearray()
is_usascii = True
encode_start = None
for i, symbol in enumerate(data):
charpoint = ord(symbol)
if is_usascii:
if charpoint == 0x26:
ret.extend(b'&-')
elif 0x20 <= charpoint <= 0x7e:
ret.append(charpoint)
else:
encode_start = i
is_usascii = False
else:
if 0x20 <= charpoint <= 0x7e:
to_encode = data[encode_start:i]
encoded = _modified_b64encode(to_encode)
ret.append(0x26)
ret.extend(encoded)
ret.extend((0x2d, charpoint))
is_usascii = True
if not is_usascii:
to_encode = data[encode_start:]
encoded = _modified_b64encode(to_encode)
ret.append(0x26)
ret.extend(encoded)
ret.append(0x2d)
return bytes(ret) | python | def modutf7_encode(data: str) -> bytes:
ret = bytearray()
is_usascii = True
encode_start = None
for i, symbol in enumerate(data):
charpoint = ord(symbol)
if is_usascii:
if charpoint == 0x26:
ret.extend(b'&-')
elif 0x20 <= charpoint <= 0x7e:
ret.append(charpoint)
else:
encode_start = i
is_usascii = False
else:
if 0x20 <= charpoint <= 0x7e:
to_encode = data[encode_start:i]
encoded = _modified_b64encode(to_encode)
ret.append(0x26)
ret.extend(encoded)
ret.extend((0x2d, charpoint))
is_usascii = True
if not is_usascii:
to_encode = data[encode_start:]
encoded = _modified_b64encode(to_encode)
ret.append(0x26)
ret.extend(encoded)
ret.append(0x2d)
return bytes(ret) | [
"def",
"modutf7_encode",
"(",
"data",
":",
"str",
")",
"->",
"bytes",
":",
"ret",
"=",
"bytearray",
"(",
")",
"is_usascii",
"=",
"True",
"encode_start",
"=",
"None",
"for",
"i",
",",
"symbol",
"in",
"enumerate",
"(",
"data",
")",
":",
"charpoint",
"=",... | Encode the string using modified UTF-7.
Args:
data: The input string to encode. | [
"Encode",
"the",
"string",
"using",
"modified",
"UTF",
"-",
"7",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/modutf7.py#L26-L60 |
24,214 | icgood/pymap | pymap/parsing/modutf7.py | modutf7_decode | def modutf7_decode(data: bytes) -> str:
"""Decode the bytestring using modified UTF-7.
Args:
data: The encoded bytestring to decode.
"""
parts = []
is_usascii = True
buf = memoryview(data)
while buf:
byte = buf[0]
if is_usascii:
if buf[0:2] == b'&-':
parts.append('&')
buf = buf[2:]
elif byte == 0x26:
is_usascii = False
buf = buf[1:]
else:
parts.append(chr(byte))
buf = buf[1:]
else:
for i, byte in enumerate(buf):
if byte == 0x2d:
to_decode = buf[:i].tobytes()
decoded = _modified_b64decode(to_decode)
parts.append(decoded)
buf = buf[i + 1:]
is_usascii = True
break
if not is_usascii:
to_decode = buf.tobytes()
decoded = _modified_b64decode(to_decode)
parts.append(decoded)
return ''.join(parts) | python | def modutf7_decode(data: bytes) -> str:
parts = []
is_usascii = True
buf = memoryview(data)
while buf:
byte = buf[0]
if is_usascii:
if buf[0:2] == b'&-':
parts.append('&')
buf = buf[2:]
elif byte == 0x26:
is_usascii = False
buf = buf[1:]
else:
parts.append(chr(byte))
buf = buf[1:]
else:
for i, byte in enumerate(buf):
if byte == 0x2d:
to_decode = buf[:i].tobytes()
decoded = _modified_b64decode(to_decode)
parts.append(decoded)
buf = buf[i + 1:]
is_usascii = True
break
if not is_usascii:
to_decode = buf.tobytes()
decoded = _modified_b64decode(to_decode)
parts.append(decoded)
return ''.join(parts) | [
"def",
"modutf7_decode",
"(",
"data",
":",
"bytes",
")",
"->",
"str",
":",
"parts",
"=",
"[",
"]",
"is_usascii",
"=",
"True",
"buf",
"=",
"memoryview",
"(",
"data",
")",
"while",
"buf",
":",
"byte",
"=",
"buf",
"[",
"0",
"]",
"if",
"is_usascii",
":... | Decode the bytestring using modified UTF-7.
Args:
data: The encoded bytestring to decode. | [
"Decode",
"the",
"bytestring",
"using",
"modified",
"UTF",
"-",
"7",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/modutf7.py#L63-L98 |
24,215 | icgood/pymap | pymap/bytes.py | BytesFormat.format | def format(self, data: Iterable[_FormatArg]) -> bytes:
"""String interpolation into the format string.
Args:
data: The data interpolated into the format string.
Examples:
::
BytesFormat(b'Hello, %b!') % b'World'
BytesFormat(b'%b, %b!') % (b'Hello', b'World')
"""
fix_arg = self._fix_format_arg
return self.how % tuple(fix_arg(item) for item in data) | python | def format(self, data: Iterable[_FormatArg]) -> bytes:
fix_arg = self._fix_format_arg
return self.how % tuple(fix_arg(item) for item in data) | [
"def",
"format",
"(",
"self",
",",
"data",
":",
"Iterable",
"[",
"_FormatArg",
"]",
")",
"->",
"bytes",
":",
"fix_arg",
"=",
"self",
".",
"_fix_format_arg",
"return",
"self",
".",
"how",
"%",
"tuple",
"(",
"fix_arg",
"(",
"item",
")",
"for",
"item",
... | String interpolation into the format string.
Args:
data: The data interpolated into the format string.
Examples:
::
BytesFormat(b'Hello, %b!') % b'World'
BytesFormat(b'%b, %b!') % (b'Hello', b'World') | [
"String",
"interpolation",
"into",
"the",
"format",
"string",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/bytes.py#L179-L193 |
24,216 | icgood/pymap | pymap/bytes.py | BytesFormat.join | def join(self, *data: Iterable[MaybeBytes]) -> bytes:
"""Iterable join on a delimiter.
Args:
data: Iterable of items to join.
Examples:
::
BytesFormat(b' ').join([b'one', b'two', b'three'])
"""
return self.how.join([bytes(item) for item in chain(*data)]) | python | def join(self, *data: Iterable[MaybeBytes]) -> bytes:
return self.how.join([bytes(item) for item in chain(*data)]) | [
"def",
"join",
"(",
"self",
",",
"*",
"data",
":",
"Iterable",
"[",
"MaybeBytes",
"]",
")",
"->",
"bytes",
":",
"return",
"self",
".",
"how",
".",
"join",
"(",
"[",
"bytes",
"(",
"item",
")",
"for",
"item",
"in",
"chain",
"(",
"*",
"data",
")",
... | Iterable join on a delimiter.
Args:
data: Iterable of items to join.
Examples:
::
BytesFormat(b' ').join([b'one', b'two', b'three']) | [
"Iterable",
"join",
"on",
"a",
"delimiter",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/bytes.py#L195-L207 |
24,217 | icgood/pymap | pymap/interfaces/filter.py | FilterInterface.apply | async def apply(self, sender: str, recipient: str, mailbox: str,
append_msg: AppendMessage) \
-> Tuple[Optional[str], AppendMessage]:
"""Run the filter and return the mailbox where it should be appended,
or None to discard, and the message to be appended, which is usually
the same as ``append_msg``.
Args:
sender: The envelope sender of the message.
recipient: The envelope recipient of the message.
mailbox: The intended mailbox to append the message.
append_msg: The message to be appended.
raises:
:exc:`~pymap.exceptions.AppendFailure`
"""
... | python | async def apply(self, sender: str, recipient: str, mailbox: str,
append_msg: AppendMessage) \
-> Tuple[Optional[str], AppendMessage]:
... | [
"async",
"def",
"apply",
"(",
"self",
",",
"sender",
":",
"str",
",",
"recipient",
":",
"str",
",",
"mailbox",
":",
"str",
",",
"append_msg",
":",
"AppendMessage",
")",
"->",
"Tuple",
"[",
"Optional",
"[",
"str",
"]",
",",
"AppendMessage",
"]",
":",
... | Run the filter and return the mailbox where it should be appended,
or None to discard, and the message to be appended, which is usually
the same as ``append_msg``.
Args:
sender: The envelope sender of the message.
recipient: The envelope recipient of the message.
mailbox: The intended mailbox to append the message.
append_msg: The message to be appended.
raises:
:exc:`~pymap.exceptions.AppendFailure` | [
"Run",
"the",
"filter",
"and",
"return",
"the",
"mailbox",
"where",
"it",
"should",
"be",
"appended",
"or",
"None",
"to",
"discard",
"and",
"the",
"message",
"to",
"be",
"appended",
"which",
"is",
"usually",
"the",
"same",
"as",
"append_msg",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/filter.py#L23-L40 |
24,218 | icgood/pymap | pymap/interfaces/session.py | SessionInterface.list_mailboxes | async def list_mailboxes(self, ref_name: str, filter_: str,
subscribed: bool = False,
selected: SelectedMailbox = None) \
-> Tuple[Iterable[Tuple[str, Optional[str], Sequence[bytes]]],
Optional[SelectedMailbox]]:
"""List the mailboxes owned by the user.
See Also:
`RFC 3501 6.3.8.
<https://tools.ietf.org/html/rfc3501#section-6.3.8>`_,
`RFC 3501 6.3.9.
<https://tools.ietf.org/html/rfc3501#section-6.3.9>`_
Args:
ref_name: Mailbox reference name.
filter_: Mailbox name with possible wildcards.
subscribed: If True, only list the subscribed mailboxes.
selected: If applicable, the currently selected mailbox name.
"""
... | python | async def list_mailboxes(self, ref_name: str, filter_: str,
subscribed: bool = False,
selected: SelectedMailbox = None) \
-> Tuple[Iterable[Tuple[str, Optional[str], Sequence[bytes]]],
Optional[SelectedMailbox]]:
... | [
"async",
"def",
"list_mailboxes",
"(",
"self",
",",
"ref_name",
":",
"str",
",",
"filter_",
":",
"str",
",",
"subscribed",
":",
"bool",
"=",
"False",
",",
"selected",
":",
"SelectedMailbox",
"=",
"None",
")",
"->",
"Tuple",
"[",
"Iterable",
"[",
"Tuple",... | List the mailboxes owned by the user.
See Also:
`RFC 3501 6.3.8.
<https://tools.ietf.org/html/rfc3501#section-6.3.8>`_,
`RFC 3501 6.3.9.
<https://tools.ietf.org/html/rfc3501#section-6.3.9>`_
Args:
ref_name: Mailbox reference name.
filter_: Mailbox name with possible wildcards.
subscribed: If True, only list the subscribed mailboxes.
selected: If applicable, the currently selected mailbox name. | [
"List",
"the",
"mailboxes",
"owned",
"by",
"the",
"user",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L70-L90 |
24,219 | icgood/pymap | pymap/interfaces/session.py | SessionInterface.rename_mailbox | async def rename_mailbox(self, before_name: str, after_name: str,
selected: SelectedMailbox = None) \
-> Optional[SelectedMailbox]:
"""Renames the mailbox owned by the user.
See Also:
`RFC 3501 6.3.5.
<https://tools.ietf.org/html/rfc3501#section-6.3.5>`_
Args:
before_name: The name of the mailbox before the rename.
after_name: The name of the mailbox after the rename.
selected: If applicable, the currently selected mailbox name.
Raises:
:class:`~pymap.exceptions.MailboxNotFound`
:class:`~pymap.exceptions.MailboxConflict`
"""
... | python | async def rename_mailbox(self, before_name: str, after_name: str,
selected: SelectedMailbox = None) \
-> Optional[SelectedMailbox]:
... | [
"async",
"def",
"rename_mailbox",
"(",
"self",
",",
"before_name",
":",
"str",
",",
"after_name",
":",
"str",
",",
"selected",
":",
"SelectedMailbox",
"=",
"None",
")",
"->",
"Optional",
"[",
"SelectedMailbox",
"]",
":",
"..."
] | Renames the mailbox owned by the user.
See Also:
`RFC 3501 6.3.5.
<https://tools.ietf.org/html/rfc3501#section-6.3.5>`_
Args:
before_name: The name of the mailbox before the rename.
after_name: The name of the mailbox after the rename.
selected: If applicable, the currently selected mailbox name.
Raises:
:class:`~pymap.exceptions.MailboxNotFound`
:class:`~pymap.exceptions.MailboxConflict` | [
"Renames",
"the",
"mailbox",
"owned",
"by",
"the",
"user",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L151-L170 |
24,220 | icgood/pymap | pymap/interfaces/session.py | SessionInterface.append_messages | async def append_messages(self, name: str,
messages: Sequence[AppendMessage],
selected: SelectedMailbox = None) \
-> Tuple[AppendUid, Optional[SelectedMailbox]]:
"""Appends a message to the end of the mailbox.
See Also:
`RFC 3502 6.3.11.
<https://tools.ietf.org/html/rfc3502#section-6.3.11>`_
Args:
name: The name of the mailbox.
messages: The messages to append.
selected: If applicable, the currently selected mailbox name.
Raises:
:class:`~pymap.exceptions.MailboxNotFound`
:class:`~pymap.exceptions.AppendFailure`
"""
... | python | async def append_messages(self, name: str,
messages: Sequence[AppendMessage],
selected: SelectedMailbox = None) \
-> Tuple[AppendUid, Optional[SelectedMailbox]]:
... | [
"async",
"def",
"append_messages",
"(",
"self",
",",
"name",
":",
"str",
",",
"messages",
":",
"Sequence",
"[",
"AppendMessage",
"]",
",",
"selected",
":",
"SelectedMailbox",
"=",
"None",
")",
"->",
"Tuple",
"[",
"AppendUid",
",",
"Optional",
"[",
"Selecte... | Appends a message to the end of the mailbox.
See Also:
`RFC 3502 6.3.11.
<https://tools.ietf.org/html/rfc3502#section-6.3.11>`_
Args:
name: The name of the mailbox.
messages: The messages to append.
selected: If applicable, the currently selected mailbox name.
Raises:
:class:`~pymap.exceptions.MailboxNotFound`
:class:`~pymap.exceptions.AppendFailure` | [
"Appends",
"a",
"message",
"to",
"the",
"end",
"of",
"the",
"mailbox",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L213-L233 |
24,221 | icgood/pymap | pymap/interfaces/session.py | SessionInterface.select_mailbox | async def select_mailbox(self, name: str, readonly: bool = False) \
-> Tuple[MailboxInterface, SelectedMailbox]:
"""Selects an existing mailbox owned by the user. The returned session
is then used as the ``selected`` argument to other methods to fetch
mailbox updates.
See Also:
`RFC 3501 6.3.1.
<https://tools.ietf.org/html/rfc3501#section-6.3.1>`_,
`RFC 3501 6.3.2.
<https://tools.ietf.org/html/rfc3501#section-6.3.2>`_
Args:
name: The name of the mailbox.
readonly: True if the mailbox is read-only.
Raises:
:class:`~pymap.exceptions.MailboxNotFound`
"""
... | python | async def select_mailbox(self, name: str, readonly: bool = False) \
-> Tuple[MailboxInterface, SelectedMailbox]:
... | [
"async",
"def",
"select_mailbox",
"(",
"self",
",",
"name",
":",
"str",
",",
"readonly",
":",
"bool",
"=",
"False",
")",
"->",
"Tuple",
"[",
"MailboxInterface",
",",
"SelectedMailbox",
"]",
":",
"..."
] | Selects an existing mailbox owned by the user. The returned session
is then used as the ``selected`` argument to other methods to fetch
mailbox updates.
See Also:
`RFC 3501 6.3.1.
<https://tools.ietf.org/html/rfc3501#section-6.3.1>`_,
`RFC 3501 6.3.2.
<https://tools.ietf.org/html/rfc3501#section-6.3.2>`_
Args:
name: The name of the mailbox.
readonly: True if the mailbox is read-only.
Raises:
:class:`~pymap.exceptions.MailboxNotFound` | [
"Selects",
"an",
"existing",
"mailbox",
"owned",
"by",
"the",
"user",
".",
"The",
"returned",
"session",
"is",
"then",
"used",
"as",
"the",
"selected",
"argument",
"to",
"other",
"methods",
"to",
"fetch",
"mailbox",
"updates",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L236-L256 |
24,222 | icgood/pymap | pymap/interfaces/session.py | SessionInterface.check_mailbox | async def check_mailbox(self, selected: SelectedMailbox, *,
wait_on: Event = None,
housekeeping: bool = False) -> SelectedMailbox:
"""Checks for any updates in the mailbox.
If ``wait_on`` is given, this method should block until either this
event is signalled or the mailbox has detected updates. This method may
be called continuously as long as ``wait_on`` is not signalled.
If ``housekeeping`` is True, perform any house-keeping necessary by the
mailbox backend, which may be a slower operation.
See Also:
`RFC 3501 6.1.2.
<https://tools.ietf.org/html/rfc3501#section-6.1.2>`_,
`RFC 3501 6.4.1.
<https://tools.ietf.org/html/rfc3501#section-6.4.1>`_
`RFC 2177 <https://tools.ietf.org/html/rfc2177>`_
Args:
selected: The selected mailbox session.
wait_on: If given, block until this event signals.
housekeeping: If True, the backend may perform additional
housekeeping operations if necessary.
Raises:
:class:`~pymap.exceptions.MailboxNotFound`
"""
... | python | async def check_mailbox(self, selected: SelectedMailbox, *,
wait_on: Event = None,
housekeeping: bool = False) -> SelectedMailbox:
... | [
"async",
"def",
"check_mailbox",
"(",
"self",
",",
"selected",
":",
"SelectedMailbox",
",",
"*",
",",
"wait_on",
":",
"Event",
"=",
"None",
",",
"housekeeping",
":",
"bool",
"=",
"False",
")",
"->",
"SelectedMailbox",
":",
"..."
] | Checks for any updates in the mailbox.
If ``wait_on`` is given, this method should block until either this
event is signalled or the mailbox has detected updates. This method may
be called continuously as long as ``wait_on`` is not signalled.
If ``housekeeping`` is True, perform any house-keeping necessary by the
mailbox backend, which may be a slower operation.
See Also:
`RFC 3501 6.1.2.
<https://tools.ietf.org/html/rfc3501#section-6.1.2>`_,
`RFC 3501 6.4.1.
<https://tools.ietf.org/html/rfc3501#section-6.4.1>`_
`RFC 2177 <https://tools.ietf.org/html/rfc2177>`_
Args:
selected: The selected mailbox session.
wait_on: If given, block until this event signals.
housekeeping: If True, the backend may perform additional
housekeeping operations if necessary.
Raises:
:class:`~pymap.exceptions.MailboxNotFound` | [
"Checks",
"for",
"any",
"updates",
"in",
"the",
"mailbox",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L259-L288 |
24,223 | icgood/pymap | pymap/interfaces/session.py | SessionInterface.fetch_messages | async def fetch_messages(self, selected: SelectedMailbox,
sequence_set: SequenceSet,
attributes: FrozenSet[FetchAttribute]) \
-> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]:
"""Get a list of loaded message objects corresponding to given sequence
set.
Args:
selected: The selected mailbox session.
sequence_set: Sequence set of message sequences or UIDs.
attributes: Fetch attributes for the messages.
Raises:
:class:`~pymap.exceptions.MailboxNotFound`
"""
... | python | async def fetch_messages(self, selected: SelectedMailbox,
sequence_set: SequenceSet,
attributes: FrozenSet[FetchAttribute]) \
-> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]:
... | [
"async",
"def",
"fetch_messages",
"(",
"self",
",",
"selected",
":",
"SelectedMailbox",
",",
"sequence_set",
":",
"SequenceSet",
",",
"attributes",
":",
"FrozenSet",
"[",
"FetchAttribute",
"]",
")",
"->",
"Tuple",
"[",
"Iterable",
"[",
"Tuple",
"[",
"int",
"... | Get a list of loaded message objects corresponding to given sequence
set.
Args:
selected: The selected mailbox session.
sequence_set: Sequence set of message sequences or UIDs.
attributes: Fetch attributes for the messages.
Raises:
:class:`~pymap.exceptions.MailboxNotFound` | [
"Get",
"a",
"list",
"of",
"loaded",
"message",
"objects",
"corresponding",
"to",
"given",
"sequence",
"set",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L291-L307 |
24,224 | icgood/pymap | pymap/interfaces/session.py | SessionInterface.search_mailbox | async def search_mailbox(self, selected: SelectedMailbox,
keys: FrozenSet[SearchKey]) \
-> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]:
"""Get the messages in the current mailbox that meet all of the
given search criteria.
See Also:
`RFC 3501 7.2.5.
<https://tools.ietf.org/html/rfc3501#section-7.2.5>`_
Args:
selected: The selected mailbox session.
keys: Search keys specifying the message criteria.
Raises:
:class:`~pymap.exceptions.MailboxNotFound`
"""
... | python | async def search_mailbox(self, selected: SelectedMailbox,
keys: FrozenSet[SearchKey]) \
-> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]:
... | [
"async",
"def",
"search_mailbox",
"(",
"self",
",",
"selected",
":",
"SelectedMailbox",
",",
"keys",
":",
"FrozenSet",
"[",
"SearchKey",
"]",
")",
"->",
"Tuple",
"[",
"Iterable",
"[",
"Tuple",
"[",
"int",
",",
"MessageInterface",
"]",
"]",
",",
"SelectedMa... | Get the messages in the current mailbox that meet all of the
given search criteria.
See Also:
`RFC 3501 7.2.5.
<https://tools.ietf.org/html/rfc3501#section-7.2.5>`_
Args:
selected: The selected mailbox session.
keys: Search keys specifying the message criteria.
Raises:
:class:`~pymap.exceptions.MailboxNotFound` | [
"Get",
"the",
"messages",
"in",
"the",
"current",
"mailbox",
"that",
"meet",
"all",
"of",
"the",
"given",
"search",
"criteria",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L310-L328 |
24,225 | icgood/pymap | pymap/interfaces/session.py | SessionInterface.copy_messages | async def copy_messages(self, selected: SelectedMailbox,
sequence_set: SequenceSet,
mailbox: str) \
-> Tuple[Optional[CopyUid], SelectedMailbox]:
"""Copy a set of messages into the given mailbox.
See Also:
`RFC 3501 6.4.7.
<https://tools.ietf.org/html/rfc3501#section-6.4.7>`_
Args:
selected: The selected mailbox session.
sequence_set: Sequence set of message sequences or UIDs.
mailbox: Name of the mailbox to copy messages into.
Raises:
:class:`~pymap.exceptions.MailboxNotFound`
:class:`~pymap.exceptions.MailboxReadOnly`
"""
... | python | async def copy_messages(self, selected: SelectedMailbox,
sequence_set: SequenceSet,
mailbox: str) \
-> Tuple[Optional[CopyUid], SelectedMailbox]:
... | [
"async",
"def",
"copy_messages",
"(",
"self",
",",
"selected",
":",
"SelectedMailbox",
",",
"sequence_set",
":",
"SequenceSet",
",",
"mailbox",
":",
"str",
")",
"->",
"Tuple",
"[",
"Optional",
"[",
"CopyUid",
"]",
",",
"SelectedMailbox",
"]",
":",
"..."
] | Copy a set of messages into the given mailbox.
See Also:
`RFC 3501 6.4.7.
<https://tools.ietf.org/html/rfc3501#section-6.4.7>`_
Args:
selected: The selected mailbox session.
sequence_set: Sequence set of message sequences or UIDs.
mailbox: Name of the mailbox to copy messages into.
Raises:
:class:`~pymap.exceptions.MailboxNotFound`
:class:`~pymap.exceptions.MailboxReadOnly` | [
"Copy",
"a",
"set",
"of",
"messages",
"into",
"the",
"given",
"mailbox",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L353-L373 |
24,226 | icgood/pymap | pymap/interfaces/session.py | SessionInterface.update_flags | async def update_flags(self, selected: SelectedMailbox,
sequence_set: SequenceSet,
flag_set: FrozenSet[Flag],
mode: FlagOp = FlagOp.REPLACE) \
-> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]:
"""Update the flags for the given set of messages.
See Also:
`RFC 3501 6.4.6.
<https://tools.ietf.org/html/rfc3501#section-6.4.6>`_
Args:
selected: The selected mailbox session.
sequence_set: Sequence set of message sequences or UIDs.
flag_set: Set of flags to update.
mode: Update mode for the flag set.
Raises:
:class:`~pymap.exceptions.MailboxNotFound`
:class:`~pymap.exceptions.MailboxReadOnly`
"""
... | python | async def update_flags(self, selected: SelectedMailbox,
sequence_set: SequenceSet,
flag_set: FrozenSet[Flag],
mode: FlagOp = FlagOp.REPLACE) \
-> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]:
... | [
"async",
"def",
"update_flags",
"(",
"self",
",",
"selected",
":",
"SelectedMailbox",
",",
"sequence_set",
":",
"SequenceSet",
",",
"flag_set",
":",
"FrozenSet",
"[",
"Flag",
"]",
",",
"mode",
":",
"FlagOp",
"=",
"FlagOp",
".",
"REPLACE",
")",
"->",
"Tuple... | Update the flags for the given set of messages.
See Also:
`RFC 3501 6.4.6.
<https://tools.ietf.org/html/rfc3501#section-6.4.6>`_
Args:
selected: The selected mailbox session.
sequence_set: Sequence set of message sequences or UIDs.
flag_set: Set of flags to update.
mode: Update mode for the flag set.
Raises:
:class:`~pymap.exceptions.MailboxNotFound`
:class:`~pymap.exceptions.MailboxReadOnly` | [
"Update",
"the",
"flags",
"for",
"the",
"given",
"set",
"of",
"messages",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/interfaces/session.py#L376-L398 |
24,227 | icgood/pymap | pymap/parsing/specials/fetchattr.py | FetchRequirement.reduce | def reduce(cls, requirements: Iterable['FetchRequirement']) \
-> 'FetchRequirement':
"""Reduce a set of fetch requirements into a single requirement.
Args:
requirements: The set of fetch requirements.
"""
return reduce(lambda x, y: x | y, requirements, cls.NONE) | python | def reduce(cls, requirements: Iterable['FetchRequirement']) \
-> 'FetchRequirement':
return reduce(lambda x, y: x | y, requirements, cls.NONE) | [
"def",
"reduce",
"(",
"cls",
",",
"requirements",
":",
"Iterable",
"[",
"'FetchRequirement'",
"]",
")",
"->",
"'FetchRequirement'",
":",
"return",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"|",
"y",
",",
"requirements",
",",
"cls",
".",
"NONE",
... | Reduce a set of fetch requirements into a single requirement.
Args:
requirements: The set of fetch requirements. | [
"Reduce",
"a",
"set",
"of",
"fetch",
"requirements",
"into",
"a",
"single",
"requirement",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/specials/fetchattr.py#L31-L39 |
24,228 | icgood/pymap | pymap/parsing/specials/searchkey.py | SearchKey.requirement | def requirement(self) -> FetchRequirement:
"""Indicates the data required to fulfill this search key."""
key_name = self.key
if key_name == b'ALL':
return FetchRequirement.NONE
elif key_name == b'KEYSET':
keyset_reqs = {key.requirement for key in self.filter_key_set}
return FetchRequirement.reduce(keyset_reqs)
elif key_name == b'OR':
left, right = self.filter_key_or
key_or_reqs = {left.requirement, right.requirement}
return FetchRequirement.reduce(key_or_reqs)
elif key_name in (b'SENTBEFORE', b'SENTON', b'SENTSINCE', b'BCC',
b'CC', b'FROM', b'SUBJECT', b'TO', b'HEADER'):
return FetchRequirement.HEADERS
elif key_name in (b'BODY', b'TEXT', b'LARGER', b'SMALLER'):
return FetchRequirement.BODY
else:
return FetchRequirement.METADATA | python | def requirement(self) -> FetchRequirement:
key_name = self.key
if key_name == b'ALL':
return FetchRequirement.NONE
elif key_name == b'KEYSET':
keyset_reqs = {key.requirement for key in self.filter_key_set}
return FetchRequirement.reduce(keyset_reqs)
elif key_name == b'OR':
left, right = self.filter_key_or
key_or_reqs = {left.requirement, right.requirement}
return FetchRequirement.reduce(key_or_reqs)
elif key_name in (b'SENTBEFORE', b'SENTON', b'SENTSINCE', b'BCC',
b'CC', b'FROM', b'SUBJECT', b'TO', b'HEADER'):
return FetchRequirement.HEADERS
elif key_name in (b'BODY', b'TEXT', b'LARGER', b'SMALLER'):
return FetchRequirement.BODY
else:
return FetchRequirement.METADATA | [
"def",
"requirement",
"(",
"self",
")",
"->",
"FetchRequirement",
":",
"key_name",
"=",
"self",
".",
"key",
"if",
"key_name",
"==",
"b'ALL'",
":",
"return",
"FetchRequirement",
".",
"NONE",
"elif",
"key_name",
"==",
"b'KEYSET'",
":",
"keyset_reqs",
"=",
"{",... | Indicates the data required to fulfill this search key. | [
"Indicates",
"the",
"data",
"required",
"to",
"fulfill",
"this",
"search",
"key",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/specials/searchkey.py#L53-L71 |
24,229 | icgood/pymap | pymap/backend/maildir/mailbox.py | Maildir.claim_new | def claim_new(self) -> Iterable[str]:
"""Checks for messages in the ``new`` subdirectory, moving them to
``cur`` and returning their keys.
"""
new_subdir = self._paths['new']
cur_subdir = self._paths['cur']
for name in os.listdir(new_subdir):
new_path = os.path.join(new_subdir, name)
cur_path = os.path.join(cur_subdir, name)
try:
os.rename(new_path, cur_path)
except FileNotFoundError:
pass
else:
yield name.rsplit(self.colon, 1)[0] | python | def claim_new(self) -> Iterable[str]:
new_subdir = self._paths['new']
cur_subdir = self._paths['cur']
for name in os.listdir(new_subdir):
new_path = os.path.join(new_subdir, name)
cur_path = os.path.join(cur_subdir, name)
try:
os.rename(new_path, cur_path)
except FileNotFoundError:
pass
else:
yield name.rsplit(self.colon, 1)[0] | [
"def",
"claim_new",
"(",
"self",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"new_subdir",
"=",
"self",
".",
"_paths",
"[",
"'new'",
"]",
"cur_subdir",
"=",
"self",
".",
"_paths",
"[",
"'cur'",
"]",
"for",
"name",
"in",
"os",
".",
"listdir",
"(",
... | Checks for messages in the ``new`` subdirectory, moving them to
``cur`` and returning their keys. | [
"Checks",
"for",
"messages",
"in",
"the",
"new",
"subdirectory",
"moving",
"them",
"to",
"cur",
"and",
"returning",
"their",
"keys",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/maildir/mailbox.py#L34-L49 |
24,230 | icgood/pymap | pymap/admin/handlers.py | AdminHandlers.Append | async def Append(self, stream) -> None:
"""Append a message directly to a user's mailbox.
If the backend session defines a
:attr:`~pymap.interfaces.session.SessionInterface.filter_set`, the
active filter implementation will be applied to the appended message,
such that the message may be discarded, modified, or placed into a
specific mailbox.
For example, using the CLI client::
$ cat message.txt | pymap-admin append user@example.com
See ``pymap-admin append --help`` for more options.
Args:
stream (:class:`~grpclib.server.Stream`): The stream for the
request and response.
"""
from .grpc.admin_pb2 import AppendRequest, AppendResponse, \
ERROR_RESPONSE
request: AppendRequest = await stream.recv_message()
mailbox = request.mailbox or 'INBOX'
flag_set = frozenset(Flag(flag) for flag in request.flags)
when = datetime.fromtimestamp(request.when, timezone.utc)
append_msg = AppendMessage(request.data, flag_set, when,
ExtensionOptions.empty())
try:
session = await self._login_as(request.user)
if self._with_filter and session.filter_set is not None:
filter_value = await session.filter_set.get_active()
if filter_value is not None:
filter_ = await session.filter_set.compile(filter_value)
new_mailbox, append_msg = await filter_.apply(
request.sender, request.recipient, mailbox, append_msg)
if new_mailbox is None:
await stream.send_message(AppendResponse())
return
else:
mailbox = new_mailbox
append_uid, _ = await session.append_messages(
mailbox, [append_msg])
except ResponseError as exc:
resp = AppendResponse(result=ERROR_RESPONSE,
error_type=type(exc).__name__,
error_response=bytes(exc.get_response(b'.')),
mailbox=mailbox)
await stream.send_message(resp)
else:
validity = append_uid.validity
uid = next(iter(append_uid.uids))
resp = AppendResponse(mailbox=mailbox, validity=validity, uid=uid)
await stream.send_message(resp) | python | async def Append(self, stream) -> None:
from .grpc.admin_pb2 import AppendRequest, AppendResponse, \
ERROR_RESPONSE
request: AppendRequest = await stream.recv_message()
mailbox = request.mailbox or 'INBOX'
flag_set = frozenset(Flag(flag) for flag in request.flags)
when = datetime.fromtimestamp(request.when, timezone.utc)
append_msg = AppendMessage(request.data, flag_set, when,
ExtensionOptions.empty())
try:
session = await self._login_as(request.user)
if self._with_filter and session.filter_set is not None:
filter_value = await session.filter_set.get_active()
if filter_value is not None:
filter_ = await session.filter_set.compile(filter_value)
new_mailbox, append_msg = await filter_.apply(
request.sender, request.recipient, mailbox, append_msg)
if new_mailbox is None:
await stream.send_message(AppendResponse())
return
else:
mailbox = new_mailbox
append_uid, _ = await session.append_messages(
mailbox, [append_msg])
except ResponseError as exc:
resp = AppendResponse(result=ERROR_RESPONSE,
error_type=type(exc).__name__,
error_response=bytes(exc.get_response(b'.')),
mailbox=mailbox)
await stream.send_message(resp)
else:
validity = append_uid.validity
uid = next(iter(append_uid.uids))
resp = AppendResponse(mailbox=mailbox, validity=validity, uid=uid)
await stream.send_message(resp) | [
"async",
"def",
"Append",
"(",
"self",
",",
"stream",
")",
"->",
"None",
":",
"from",
".",
"grpc",
".",
"admin_pb2",
"import",
"AppendRequest",
",",
"AppendResponse",
",",
"ERROR_RESPONSE",
"request",
":",
"AppendRequest",
"=",
"await",
"stream",
".",
"recv_... | Append a message directly to a user's mailbox.
If the backend session defines a
:attr:`~pymap.interfaces.session.SessionInterface.filter_set`, the
active filter implementation will be applied to the appended message,
such that the message may be discarded, modified, or placed into a
specific mailbox.
For example, using the CLI client::
$ cat message.txt | pymap-admin append user@example.com
See ``pymap-admin append --help`` for more options.
Args:
stream (:class:`~grpclib.server.Stream`): The stream for the
request and response. | [
"Append",
"a",
"message",
"directly",
"to",
"a",
"user",
"s",
"mailbox",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/admin/handlers.py#L39-L92 |
24,231 | icgood/pymap | pymap/flags.py | FlagOp.apply | def apply(self, flag_set: AbstractSet[Flag], operand: AbstractSet[Flag]) \
-> FrozenSet[Flag]:
"""Apply the flag operation on the two sets, returning the result.
Args:
flag_set: The flag set being operated on.
operand: The flags to use as the operand.
"""
if self == FlagOp.ADD:
return frozenset(flag_set | operand)
elif self == FlagOp.DELETE:
return frozenset(flag_set - operand)
else: # op == FlagOp.REPLACE
return frozenset(operand) | python | def apply(self, flag_set: AbstractSet[Flag], operand: AbstractSet[Flag]) \
-> FrozenSet[Flag]:
if self == FlagOp.ADD:
return frozenset(flag_set | operand)
elif self == FlagOp.DELETE:
return frozenset(flag_set - operand)
else: # op == FlagOp.REPLACE
return frozenset(operand) | [
"def",
"apply",
"(",
"self",
",",
"flag_set",
":",
"AbstractSet",
"[",
"Flag",
"]",
",",
"operand",
":",
"AbstractSet",
"[",
"Flag",
"]",
")",
"->",
"FrozenSet",
"[",
"Flag",
"]",
":",
"if",
"self",
"==",
"FlagOp",
".",
"ADD",
":",
"return",
"frozens... | Apply the flag operation on the two sets, returning the result.
Args:
flag_set: The flag set being operated on.
operand: The flags to use as the operand. | [
"Apply",
"the",
"flag",
"operation",
"on",
"the",
"two",
"sets",
"returning",
"the",
"result",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/flags.py#L30-L44 |
24,232 | icgood/pymap | pymap/flags.py | SessionFlags.get | def get(self, uid: int) -> FrozenSet[Flag]:
"""Return the session flags for the mailbox session.
Args:
uid: The message UID value.
"""
recent = _recent_set if uid in self._recent else frozenset()
flags = self._flags.get(uid)
return recent if flags is None else (flags | recent) | python | def get(self, uid: int) -> FrozenSet[Flag]:
recent = _recent_set if uid in self._recent else frozenset()
flags = self._flags.get(uid)
return recent if flags is None else (flags | recent) | [
"def",
"get",
"(",
"self",
",",
"uid",
":",
"int",
")",
"->",
"FrozenSet",
"[",
"Flag",
"]",
":",
"recent",
"=",
"_recent_set",
"if",
"uid",
"in",
"self",
".",
"_recent",
"else",
"frozenset",
"(",
")",
"flags",
"=",
"self",
".",
"_flags",
".",
"get... | Return the session flags for the mailbox session.
Args:
uid: The message UID value. | [
"Return",
"the",
"session",
"flags",
"for",
"the",
"mailbox",
"session",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/flags.py#L138-L147 |
24,233 | icgood/pymap | pymap/flags.py | SessionFlags.remove | def remove(self, uids: Iterable[int]) -> None:
"""Remove any session flags for the given message.
Args:
uids: The message UID values.
"""
for uid in uids:
self._recent.discard(uid)
self._flags.pop(uid, None) | python | def remove(self, uids: Iterable[int]) -> None:
for uid in uids:
self._recent.discard(uid)
self._flags.pop(uid, None) | [
"def",
"remove",
"(",
"self",
",",
"uids",
":",
"Iterable",
"[",
"int",
"]",
")",
"->",
"None",
":",
"for",
"uid",
"in",
"uids",
":",
"self",
".",
"_recent",
".",
"discard",
"(",
"uid",
")",
"self",
".",
"_flags",
".",
"pop",
"(",
"uid",
",",
"... | Remove any session flags for the given message.
Args:
uids: The message UID values. | [
"Remove",
"any",
"session",
"flags",
"for",
"the",
"given",
"message",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/flags.py#L149-L158 |
24,234 | icgood/pymap | pymap/flags.py | SessionFlags.update | def update(self, uid: int, flag_set: Iterable[Flag],
op: FlagOp = FlagOp.REPLACE) -> FrozenSet[Flag]:
"""Update the flags for the session, returning the resulting flags.
Args:
uid: The message UID value.
flag_set: The set of flags for the update operation.
op: The type of update.
"""
orig_set = self._flags.get(uid, frozenset())
new_flags = op.apply(orig_set, self & flag_set)
if new_flags:
self._flags[uid] = new_flags
else:
self._flags.pop(uid, None)
return new_flags | python | def update(self, uid: int, flag_set: Iterable[Flag],
op: FlagOp = FlagOp.REPLACE) -> FrozenSet[Flag]:
orig_set = self._flags.get(uid, frozenset())
new_flags = op.apply(orig_set, self & flag_set)
if new_flags:
self._flags[uid] = new_flags
else:
self._flags.pop(uid, None)
return new_flags | [
"def",
"update",
"(",
"self",
",",
"uid",
":",
"int",
",",
"flag_set",
":",
"Iterable",
"[",
"Flag",
"]",
",",
"op",
":",
"FlagOp",
"=",
"FlagOp",
".",
"REPLACE",
")",
"->",
"FrozenSet",
"[",
"Flag",
"]",
":",
"orig_set",
"=",
"self",
".",
"_flags"... | Update the flags for the session, returning the resulting flags.
Args:
uid: The message UID value.
flag_set: The set of flags for the update operation.
op: The type of update. | [
"Update",
"the",
"flags",
"for",
"the",
"session",
"returning",
"the",
"resulting",
"flags",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/flags.py#L160-L176 |
24,235 | icgood/pymap | pymap/parsing/specials/flag.py | get_system_flags | def get_system_flags() -> FrozenSet[Flag]:
"""Return the set of implemented system flags."""
return frozenset({Seen, Recent, Deleted, Flagged, Answered, Draft}) | python | def get_system_flags() -> FrozenSet[Flag]:
return frozenset({Seen, Recent, Deleted, Flagged, Answered, Draft}) | [
"def",
"get_system_flags",
"(",
")",
"->",
"FrozenSet",
"[",
"Flag",
"]",
":",
"return",
"frozenset",
"(",
"{",
"Seen",
",",
"Recent",
",",
"Deleted",
",",
"Flagged",
",",
"Answered",
",",
"Draft",
"}",
")"
] | Return the set of implemented system flags. | [
"Return",
"the",
"set",
"of",
"implemented",
"system",
"flags",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/specials/flag.py#L93-L95 |
24,236 | icgood/pymap | pymap/parsing/commands.py | Commands.register | def register(self, cmd: Type[Command]) -> None:
"""Register a new IMAP command.
Args:
cmd: The new command type.
"""
self.commands[cmd.command] = cmd | python | def register(self, cmd: Type[Command]) -> None:
self.commands[cmd.command] = cmd | [
"def",
"register",
"(",
"self",
",",
"cmd",
":",
"Type",
"[",
"Command",
"]",
")",
"->",
"None",
":",
"self",
".",
"commands",
"[",
"cmd",
".",
"command",
"]",
"=",
"cmd"
] | Register a new IMAP command.
Args:
cmd: The new command type. | [
"Register",
"a",
"new",
"IMAP",
"command",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/commands.py#L95-L102 |
24,237 | icgood/pymap | pymap/parsing/primitives.py | ListP.get_as | def get_as(self, cls: Type[MaybeBytesT]) -> Sequence[MaybeBytesT]:
"""Return the list of parsed objects."""
_ = cls # noqa
return cast(Sequence[MaybeBytesT], self.items) | python | def get_as(self, cls: Type[MaybeBytesT]) -> Sequence[MaybeBytesT]:
_ = cls # noqa
return cast(Sequence[MaybeBytesT], self.items) | [
"def",
"get_as",
"(",
"self",
",",
"cls",
":",
"Type",
"[",
"MaybeBytesT",
"]",
")",
"->",
"Sequence",
"[",
"MaybeBytesT",
"]",
":",
"_",
"=",
"cls",
"# noqa",
"return",
"cast",
"(",
"Sequence",
"[",
"MaybeBytesT",
"]",
",",
"self",
".",
"items",
")"... | Return the list of parsed objects. | [
"Return",
"the",
"list",
"of",
"parsed",
"objects",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/primitives.py#L430-L433 |
24,238 | icgood/pymap | pymap/fetch.py | MessageAttributes.get_all | def get_all(self, attrs: Iterable[FetchAttribute]) \
-> Sequence[Tuple[FetchAttribute, MaybeBytes]]:
"""Return a list of tuples containing the attribute iself and the bytes
representation of that attribute from the message.
Args:
attrs: The fetch attributes.
"""
ret: List[Tuple[FetchAttribute, MaybeBytes]] = []
for attr in attrs:
try:
ret.append((attr.for_response, self.get(attr)))
except NotFetchable:
pass
return ret | python | def get_all(self, attrs: Iterable[FetchAttribute]) \
-> Sequence[Tuple[FetchAttribute, MaybeBytes]]:
ret: List[Tuple[FetchAttribute, MaybeBytes]] = []
for attr in attrs:
try:
ret.append((attr.for_response, self.get(attr)))
except NotFetchable:
pass
return ret | [
"def",
"get_all",
"(",
"self",
",",
"attrs",
":",
"Iterable",
"[",
"FetchAttribute",
"]",
")",
"->",
"Sequence",
"[",
"Tuple",
"[",
"FetchAttribute",
",",
"MaybeBytes",
"]",
"]",
":",
"ret",
":",
"List",
"[",
"Tuple",
"[",
"FetchAttribute",
",",
"MaybeBy... | Return a list of tuples containing the attribute iself and the bytes
representation of that attribute from the message.
Args:
attrs: The fetch attributes. | [
"Return",
"a",
"list",
"of",
"tuples",
"containing",
"the",
"attribute",
"iself",
"and",
"the",
"bytes",
"representation",
"of",
"that",
"attribute",
"from",
"the",
"message",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/fetch.py#L60-L75 |
24,239 | icgood/pymap | pymap/fetch.py | MessageAttributes.get | def get(self, attr: FetchAttribute) -> MaybeBytes:
"""Return the bytes representation of the given message attribue.
Args:
attr: The fetch attribute.
Raises:
:class:`NotFetchable`
"""
attr_name = attr.value.decode('ascii')
method = getattr(self, '_get_' + attr_name.replace('.', '_'))
return method(attr) | python | def get(self, attr: FetchAttribute) -> MaybeBytes:
attr_name = attr.value.decode('ascii')
method = getattr(self, '_get_' + attr_name.replace('.', '_'))
return method(attr) | [
"def",
"get",
"(",
"self",
",",
"attr",
":",
"FetchAttribute",
")",
"->",
"MaybeBytes",
":",
"attr_name",
"=",
"attr",
".",
"value",
".",
"decode",
"(",
"'ascii'",
")",
"method",
"=",
"getattr",
"(",
"self",
",",
"'_get_'",
"+",
"attr_name",
".",
"repl... | Return the bytes representation of the given message attribue.
Args:
attr: The fetch attribute.
Raises:
:class:`NotFetchable` | [
"Return",
"the",
"bytes",
"representation",
"of",
"the",
"given",
"message",
"attribue",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/fetch.py#L77-L89 |
24,240 | icgood/pymap | pymap/search.py | SearchCriteriaSet.sequence_set | def sequence_set(self) -> SequenceSet:
"""The sequence set to use when finding the messages to match against.
This will default to all messages unless the search criteria set
contains a sequence set.
"""
try:
seqset_crit = next(crit for crit in self.all_criteria
if isinstance(crit, SequenceSetSearchCriteria))
except StopIteration:
return SequenceSet.all()
else:
return seqset_crit.seq_set | python | def sequence_set(self) -> SequenceSet:
try:
seqset_crit = next(crit for crit in self.all_criteria
if isinstance(crit, SequenceSetSearchCriteria))
except StopIteration:
return SequenceSet.all()
else:
return seqset_crit.seq_set | [
"def",
"sequence_set",
"(",
"self",
")",
"->",
"SequenceSet",
":",
"try",
":",
"seqset_crit",
"=",
"next",
"(",
"crit",
"for",
"crit",
"in",
"self",
".",
"all_criteria",
"if",
"isinstance",
"(",
"crit",
",",
"SequenceSetSearchCriteria",
")",
")",
"except",
... | The sequence set to use when finding the messages to match against.
This will default to all messages unless the search criteria set
contains a sequence set. | [
"The",
"sequence",
"set",
"to",
"use",
"when",
"finding",
"the",
"messages",
"to",
"match",
"against",
".",
"This",
"will",
"default",
"to",
"all",
"messages",
"unless",
"the",
"search",
"criteria",
"set",
"contains",
"a",
"sequence",
"set",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/search.py#L167-L179 |
24,241 | icgood/pymap | pymap/search.py | SearchCriteriaSet.matches | def matches(self, msg_seq: int, msg: MessageInterface) -> bool:
"""The message matches if all the defined search key criteria match.
Args:
msg_seq: The message sequence ID.
msg: The message object.
"""
return all(crit.matches(msg_seq, msg) for crit in self.all_criteria) | python | def matches(self, msg_seq: int, msg: MessageInterface) -> bool:
return all(crit.matches(msg_seq, msg) for crit in self.all_criteria) | [
"def",
"matches",
"(",
"self",
",",
"msg_seq",
":",
"int",
",",
"msg",
":",
"MessageInterface",
")",
"->",
"bool",
":",
"return",
"all",
"(",
"crit",
".",
"matches",
"(",
"msg_seq",
",",
"msg",
")",
"for",
"crit",
"in",
"self",
".",
"all_criteria",
"... | The message matches if all the defined search key criteria match.
Args:
msg_seq: The message sequence ID.
msg: The message object. | [
"The",
"message",
"matches",
"if",
"all",
"the",
"defined",
"search",
"key",
"criteria",
"match",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/search.py#L181-L189 |
24,242 | icgood/pymap | pymap/mime/__init__.py | MessageContent.walk | def walk(self) -> Iterable['MessageContent']:
"""Iterate through the message and all its nested sub-parts in the
order they occur.
"""
if self.body.has_nested:
return chain([self], *(part.walk() for part in self.body.nested))
else:
return [self] | python | def walk(self) -> Iterable['MessageContent']:
if self.body.has_nested:
return chain([self], *(part.walk() for part in self.body.nested))
else:
return [self] | [
"def",
"walk",
"(",
"self",
")",
"->",
"Iterable",
"[",
"'MessageContent'",
"]",
":",
"if",
"self",
".",
"body",
".",
"has_nested",
":",
"return",
"chain",
"(",
"[",
"self",
"]",
",",
"*",
"(",
"part",
".",
"walk",
"(",
")",
"for",
"part",
"in",
... | Iterate through the message and all its nested sub-parts in the
order they occur. | [
"Iterate",
"through",
"the",
"message",
"and",
"all",
"its",
"nested",
"sub",
"-",
"parts",
"in",
"the",
"order",
"they",
"occur",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/__init__.py#L44-L52 |
24,243 | icgood/pymap | pymap/mime/__init__.py | MessageContent.parse | def parse(cls, data: bytes) -> 'MessageContent':
"""Parse the bytestring into message content.
Args:
data: The bytestring to parse.
"""
lines = cls._find_lines(data)
view = memoryview(data)
return cls._parse(data, view, lines) | python | def parse(cls, data: bytes) -> 'MessageContent':
lines = cls._find_lines(data)
view = memoryview(data)
return cls._parse(data, view, lines) | [
"def",
"parse",
"(",
"cls",
",",
"data",
":",
"bytes",
")",
"->",
"'MessageContent'",
":",
"lines",
"=",
"cls",
".",
"_find_lines",
"(",
"data",
")",
"view",
"=",
"memoryview",
"(",
"data",
")",
"return",
"cls",
".",
"_parse",
"(",
"data",
",",
"view... | Parse the bytestring into message content.
Args:
data: The bytestring to parse. | [
"Parse",
"the",
"bytestring",
"into",
"message",
"content",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/__init__.py#L64-L73 |
24,244 | icgood/pymap | pymap/mime/__init__.py | MessageContent.parse_split | def parse_split(cls, header: bytes, body: bytes) -> 'MessageContent':
"""Parse the header and body bytestrings into message content.
Args:
header: The header bytestring to parse.
body: The body bytestring to parse.
"""
header_lines = cls._find_lines(header)
body_lines = cls._find_lines(body)
header_view = memoryview(header)
body_view = memoryview(body)
return cls._parse_split([header_view, body_view], header, body,
header_view, body_view,
header_lines, body_lines) | python | def parse_split(cls, header: bytes, body: bytes) -> 'MessageContent':
header_lines = cls._find_lines(header)
body_lines = cls._find_lines(body)
header_view = memoryview(header)
body_view = memoryview(body)
return cls._parse_split([header_view, body_view], header, body,
header_view, body_view,
header_lines, body_lines) | [
"def",
"parse_split",
"(",
"cls",
",",
"header",
":",
"bytes",
",",
"body",
":",
"bytes",
")",
"->",
"'MessageContent'",
":",
"header_lines",
"=",
"cls",
".",
"_find_lines",
"(",
"header",
")",
"body_lines",
"=",
"cls",
".",
"_find_lines",
"(",
"body",
"... | Parse the header and body bytestrings into message content.
Args:
header: The header bytestring to parse.
body: The body bytestring to parse. | [
"Parse",
"the",
"header",
"and",
"body",
"bytestrings",
"into",
"message",
"content",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/__init__.py#L76-L90 |
24,245 | icgood/pymap | pymap/backend/maildir/uidlist.py | UidList.get_all | def get_all(self, uids: Iterable[int]) -> Mapping[int, Record]:
"""Get records by a set of UIDs.
Args:
uids: The message UIDs.
"""
return {uid: self._records[uid] for uid in uids
if uid in self._records} | python | def get_all(self, uids: Iterable[int]) -> Mapping[int, Record]:
return {uid: self._records[uid] for uid in uids
if uid in self._records} | [
"def",
"get_all",
"(",
"self",
",",
"uids",
":",
"Iterable",
"[",
"int",
"]",
")",
"->",
"Mapping",
"[",
"int",
",",
"Record",
"]",
":",
"return",
"{",
"uid",
":",
"self",
".",
"_records",
"[",
"uid",
"]",
"for",
"uid",
"in",
"uids",
"if",
"uid",... | Get records by a set of UIDs.
Args:
uids: The message UIDs. | [
"Get",
"records",
"by",
"a",
"set",
"of",
"UIDs",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/maildir/uidlist.py#L79-L87 |
24,246 | phatpiglet/autocorrect | autocorrect/__init__.py | spell | def spell(word):
"""most likely correction for everything up to a double typo"""
w = Word(word)
candidates = (common([word]) or exact([word]) or known([word]) or
known(w.typos()) or common(w.double_typos()) or
[word])
correction = max(candidates, key=NLP_COUNTS.get)
return get_case(word, correction) | python | def spell(word):
w = Word(word)
candidates = (common([word]) or exact([word]) or known([word]) or
known(w.typos()) or common(w.double_typos()) or
[word])
correction = max(candidates, key=NLP_COUNTS.get)
return get_case(word, correction) | [
"def",
"spell",
"(",
"word",
")",
":",
"w",
"=",
"Word",
"(",
"word",
")",
"candidates",
"=",
"(",
"common",
"(",
"[",
"word",
"]",
")",
"or",
"exact",
"(",
"[",
"word",
"]",
")",
"or",
"known",
"(",
"[",
"word",
"]",
")",
"or",
"known",
"(",... | most likely correction for everything up to a double typo | [
"most",
"likely",
"correction",
"for",
"everything",
"up",
"to",
"a",
"double",
"typo"
] | ae90c886aa5e3e261813fd0f4c91188f0d14c35c | https://github.com/phatpiglet/autocorrect/blob/ae90c886aa5e3e261813fd0f4c91188f0d14c35c/autocorrect/__init__.py#L19-L26 |
24,247 | phatpiglet/autocorrect | autocorrect/utils.py | words_from_archive | def words_from_archive(filename, include_dups=False, map_case=False):
"""extract words from a text file in the archive"""
bz2 = os.path.join(PATH, BZ2)
tar_path = '{}/{}'.format('words', filename)
with closing(tarfile.open(bz2, 'r:bz2')) as t:
with closing(t.extractfile(tar_path)) as f:
words = re.findall(RE, f.read().decode(encoding='utf-8'))
if include_dups:
return words
elif map_case:
return {w.lower():w for w in words}
else:
return set(words) | python | def words_from_archive(filename, include_dups=False, map_case=False):
bz2 = os.path.join(PATH, BZ2)
tar_path = '{}/{}'.format('words', filename)
with closing(tarfile.open(bz2, 'r:bz2')) as t:
with closing(t.extractfile(tar_path)) as f:
words = re.findall(RE, f.read().decode(encoding='utf-8'))
if include_dups:
return words
elif map_case:
return {w.lower():w for w in words}
else:
return set(words) | [
"def",
"words_from_archive",
"(",
"filename",
",",
"include_dups",
"=",
"False",
",",
"map_case",
"=",
"False",
")",
":",
"bz2",
"=",
"os",
".",
"path",
".",
"join",
"(",
"PATH",
",",
"BZ2",
")",
"tar_path",
"=",
"'{}/{}'",
".",
"format",
"(",
"'words'... | extract words from a text file in the archive | [
"extract",
"words",
"from",
"a",
"text",
"file",
"in",
"the",
"archive"
] | ae90c886aa5e3e261813fd0f4c91188f0d14c35c | https://github.com/phatpiglet/autocorrect/blob/ae90c886aa5e3e261813fd0f4c91188f0d14c35c/autocorrect/utils.py#L24-L36 |
24,248 | phatpiglet/autocorrect | autocorrect/nlp_parser.py | parse | def parse(lang_sample):
"""tally word popularity using novel extracts, etc"""
words = words_from_archive(lang_sample, include_dups=True)
counts = zero_default_dict()
for word in words:
counts[word] += 1
return set(words), counts | python | def parse(lang_sample):
words = words_from_archive(lang_sample, include_dups=True)
counts = zero_default_dict()
for word in words:
counts[word] += 1
return set(words), counts | [
"def",
"parse",
"(",
"lang_sample",
")",
":",
"words",
"=",
"words_from_archive",
"(",
"lang_sample",
",",
"include_dups",
"=",
"True",
")",
"counts",
"=",
"zero_default_dict",
"(",
")",
"for",
"word",
"in",
"words",
":",
"counts",
"[",
"word",
"]",
"+=",
... | tally word popularity using novel extracts, etc | [
"tally",
"word",
"popularity",
"using",
"novel",
"extracts",
"etc"
] | ae90c886aa5e3e261813fd0f4c91188f0d14c35c | https://github.com/phatpiglet/autocorrect/blob/ae90c886aa5e3e261813fd0f4c91188f0d14c35c/autocorrect/nlp_parser.py#L18-L24 |
24,249 | phatpiglet/autocorrect | autocorrect/word.py | get_case | def get_case(word, correction):
"""
Best guess of intended case.
manchester => manchester
chilton => Chilton
AAvTech => AAvTech
THe => The
imho => IMHO
"""
if word.istitle():
return correction.title()
if word.isupper():
return correction.upper()
if correction == word and not word.islower():
return word
if len(word) > 2 and word[:2].isupper():
return correction.title()
if not known_as_lower([correction]): #expensive
try:
return CASE_MAPPED[correction]
except KeyError:
pass
return correction | python | def get_case(word, correction):
if word.istitle():
return correction.title()
if word.isupper():
return correction.upper()
if correction == word and not word.islower():
return word
if len(word) > 2 and word[:2].isupper():
return correction.title()
if not known_as_lower([correction]): #expensive
try:
return CASE_MAPPED[correction]
except KeyError:
pass
return correction | [
"def",
"get_case",
"(",
"word",
",",
"correction",
")",
":",
"if",
"word",
".",
"istitle",
"(",
")",
":",
"return",
"correction",
".",
"title",
"(",
")",
"if",
"word",
".",
"isupper",
"(",
")",
":",
"return",
"correction",
".",
"upper",
"(",
")",
"... | Best guess of intended case.
manchester => manchester
chilton => Chilton
AAvTech => AAvTech
THe => The
imho => IMHO | [
"Best",
"guess",
"of",
"intended",
"case",
"."
] | ae90c886aa5e3e261813fd0f4c91188f0d14c35c | https://github.com/phatpiglet/autocorrect/blob/ae90c886aa5e3e261813fd0f4c91188f0d14c35c/autocorrect/word.py#L91-L115 |
24,250 | phatpiglet/autocorrect | autocorrect/word.py | Word.typos | def typos(self):
"""letter combinations one typo away from word"""
return (self._deletes() | self._transposes() |
self._replaces() | self._inserts()) | python | def typos(self):
return (self._deletes() | self._transposes() |
self._replaces() | self._inserts()) | [
"def",
"typos",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_deletes",
"(",
")",
"|",
"self",
".",
"_transposes",
"(",
")",
"|",
"self",
".",
"_replaces",
"(",
")",
"|",
"self",
".",
"_inserts",
"(",
")",
")"
] | letter combinations one typo away from word | [
"letter",
"combinations",
"one",
"typo",
"away",
"from",
"word"
] | ae90c886aa5e3e261813fd0f4c91188f0d14c35c | https://github.com/phatpiglet/autocorrect/blob/ae90c886aa5e3e261813fd0f4c91188f0d14c35c/autocorrect/word.py#L64-L67 |
24,251 | phatpiglet/autocorrect | autocorrect/word.py | Word.double_typos | def double_typos(self):
"""letter combinations two typos away from word"""
return {e2 for e1 in self.typos()
for e2 in Word(e1).typos()} | python | def double_typos(self):
return {e2 for e1 in self.typos()
for e2 in Word(e1).typos()} | [
"def",
"double_typos",
"(",
"self",
")",
":",
"return",
"{",
"e2",
"for",
"e1",
"in",
"self",
".",
"typos",
"(",
")",
"for",
"e2",
"in",
"Word",
"(",
"e1",
")",
".",
"typos",
"(",
")",
"}"
] | letter combinations two typos away from word | [
"letter",
"combinations",
"two",
"typos",
"away",
"from",
"word"
] | ae90c886aa5e3e261813fd0f4c91188f0d14c35c | https://github.com/phatpiglet/autocorrect/blob/ae90c886aa5e3e261813fd0f4c91188f0d14c35c/autocorrect/word.py#L69-L72 |
24,252 | theelous3/multio | multio/__init__.py | register | def register(lib_name: str, cbl: Callable[[_AsyncLib], None]):
'''
Registers a new library function with the current manager.
'''
return manager.register(lib_name, cbl) | python | def register(lib_name: str, cbl: Callable[[_AsyncLib], None]):
'''
Registers a new library function with the current manager.
'''
return manager.register(lib_name, cbl) | [
"def",
"register",
"(",
"lib_name",
":",
"str",
",",
"cbl",
":",
"Callable",
"[",
"[",
"_AsyncLib",
"]",
",",
"None",
"]",
")",
":",
"return",
"manager",
".",
"register",
"(",
"lib_name",
",",
"cbl",
")"
] | Registers a new library function with the current manager. | [
"Registers",
"a",
"new",
"library",
"function",
"with",
"the",
"current",
"manager",
"."
] | 018e4a9f78d5f4e78608a1a1537000b5fd778bbe | https://github.com/theelous3/multio/blob/018e4a9f78d5f4e78608a1a1537000b5fd778bbe/multio/__init__.py#L480-L484 |
24,253 | theelous3/multio | multio/__init__.py | init | def init(library: typing.Union[str, types.ModuleType]) -> None:
'''
Must be called at some point after import and before your event loop
is run.
Populates the asynclib instance of _AsyncLib with methods relevant to the
async library you are using.
The supported libraries at the moment are:
- curio
- trio
Args:
library (str or module): Either the module name as a string or the
imported module itself. E.g. ``multio.init(curio)``.
'''
if isinstance(library, types.ModuleType):
library = library.__name__
if library not in manager._handlers:
raise ValueError("Possible values are <{}>, not <{}>".format(manager._handlers.keys(),
library))
manager.init(library, asynclib)
asynclib.lib_name = library
asynclib._init = True | python | def init(library: typing.Union[str, types.ModuleType]) -> None:
'''
Must be called at some point after import and before your event loop
is run.
Populates the asynclib instance of _AsyncLib with methods relevant to the
async library you are using.
The supported libraries at the moment are:
- curio
- trio
Args:
library (str or module): Either the module name as a string or the
imported module itself. E.g. ``multio.init(curio)``.
'''
if isinstance(library, types.ModuleType):
library = library.__name__
if library not in manager._handlers:
raise ValueError("Possible values are <{}>, not <{}>".format(manager._handlers.keys(),
library))
manager.init(library, asynclib)
asynclib.lib_name = library
asynclib._init = True | [
"def",
"init",
"(",
"library",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"types",
".",
"ModuleType",
"]",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"library",
",",
"types",
".",
"ModuleType",
")",
":",
"library",
"=",
"library",
".",
"__na... | Must be called at some point after import and before your event loop
is run.
Populates the asynclib instance of _AsyncLib with methods relevant to the
async library you are using.
The supported libraries at the moment are:
- curio
- trio
Args:
library (str or module): Either the module name as a string or the
imported module itself. E.g. ``multio.init(curio)``. | [
"Must",
"be",
"called",
"at",
"some",
"point",
"after",
"import",
"and",
"before",
"your",
"event",
"loop",
"is",
"run",
"."
] | 018e4a9f78d5f4e78608a1a1537000b5fd778bbe | https://github.com/theelous3/multio/blob/018e4a9f78d5f4e78608a1a1537000b5fd778bbe/multio/__init__.py#L487-L512 |
24,254 | theelous3/multio | multio/__init__.py | run | def run(*args, **kwargs):
'''
Runs the appropriate library run function.
'''
lib = sys.modules[asynclib.lib_name]
lib.run(*args, **kwargs) | python | def run(*args, **kwargs):
'''
Runs the appropriate library run function.
'''
lib = sys.modules[asynclib.lib_name]
lib.run(*args, **kwargs) | [
"def",
"run",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lib",
"=",
"sys",
".",
"modules",
"[",
"asynclib",
".",
"lib_name",
"]",
"lib",
".",
"run",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Runs the appropriate library run function. | [
"Runs",
"the",
"appropriate",
"library",
"run",
"function",
"."
] | 018e4a9f78d5f4e78608a1a1537000b5fd778bbe | https://github.com/theelous3/multio/blob/018e4a9f78d5f4e78608a1a1537000b5fd778bbe/multio/__init__.py#L515-L520 |
24,255 | theelous3/multio | multio/__init__.py | SocketWrapper.recv | async def recv(self, nbytes: int = -1, **kwargs) -> bytes:
'''
Receives some data on the socket.
'''
return await asynclib.recv(self.sock, nbytes, **kwargs) | python | async def recv(self, nbytes: int = -1, **kwargs) -> bytes:
'''
Receives some data on the socket.
'''
return await asynclib.recv(self.sock, nbytes, **kwargs) | [
"async",
"def",
"recv",
"(",
"self",
",",
"nbytes",
":",
"int",
"=",
"-",
"1",
",",
"*",
"*",
"kwargs",
")",
"->",
"bytes",
":",
"return",
"await",
"asynclib",
".",
"recv",
"(",
"self",
".",
"sock",
",",
"nbytes",
",",
"*",
"*",
"kwargs",
")"
] | Receives some data on the socket. | [
"Receives",
"some",
"data",
"on",
"the",
"socket",
"."
] | 018e4a9f78d5f4e78608a1a1537000b5fd778bbe | https://github.com/theelous3/multio/blob/018e4a9f78d5f4e78608a1a1537000b5fd778bbe/multio/__init__.py#L91-L95 |
24,256 | theelous3/multio | multio/__init__.py | SocketWrapper.sendall | async def sendall(self, data: bytes, *args, **kwargs):
'''
Sends some data on the socket.
'''
return await asynclib.sendall(self.sock, data, *args, **kwargs) | python | async def sendall(self, data: bytes, *args, **kwargs):
'''
Sends some data on the socket.
'''
return await asynclib.sendall(self.sock, data, *args, **kwargs) | [
"async",
"def",
"sendall",
"(",
"self",
",",
"data",
":",
"bytes",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"asynclib",
".",
"sendall",
"(",
"self",
".",
"sock",
",",
"data",
",",
"*",
"args",
",",
"*",
"*",
"kwargs... | Sends some data on the socket. | [
"Sends",
"some",
"data",
"on",
"the",
"socket",
"."
] | 018e4a9f78d5f4e78608a1a1537000b5fd778bbe | https://github.com/theelous3/multio/blob/018e4a9f78d5f4e78608a1a1537000b5fd778bbe/multio/__init__.py#L97-L101 |
24,257 | theelous3/multio | multio/__init__.py | SocketWrapper.wrap | def wrap(cls, meth):
'''
Wraps a connection opening method in this class.
'''
async def inner(*args, **kwargs):
sock = await meth(*args, **kwargs)
return cls(sock)
return inner | python | def wrap(cls, meth):
'''
Wraps a connection opening method in this class.
'''
async def inner(*args, **kwargs):
sock = await meth(*args, **kwargs)
return cls(sock)
return inner | [
"def",
"wrap",
"(",
"cls",
",",
"meth",
")",
":",
"async",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"sock",
"=",
"await",
"meth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"cls",
"(",
"sock",
")",
"... | Wraps a connection opening method in this class. | [
"Wraps",
"a",
"connection",
"opening",
"method",
"in",
"this",
"class",
"."
] | 018e4a9f78d5f4e78608a1a1537000b5fd778bbe | https://github.com/theelous3/multio/blob/018e4a9f78d5f4e78608a1a1537000b5fd778bbe/multio/__init__.py#L112-L121 |
24,258 | theelous3/multio | multio/__init__.py | Event.set | async def set(self, *args, **kwargs):
'''
Sets the value of the event.
'''
return await _maybe_await(self.event.set(*args, **kwargs)) | python | async def set(self, *args, **kwargs):
'''
Sets the value of the event.
'''
return await _maybe_await(self.event.set(*args, **kwargs)) | [
"async",
"def",
"set",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"_maybe_await",
"(",
"self",
".",
"event",
".",
"set",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | Sets the value of the event. | [
"Sets",
"the",
"value",
"of",
"the",
"event",
"."
] | 018e4a9f78d5f4e78608a1a1537000b5fd778bbe | https://github.com/theelous3/multio/blob/018e4a9f78d5f4e78608a1a1537000b5fd778bbe/multio/__init__.py#L168-L172 |
24,259 | theelous3/multio | multio/__init__.py | _AsyncLibManager.register | def register(self, library: str, cbl: Callable[['_AsyncLib'], None]):
'''
Registers a callable to set up a library.
'''
self._handlers[library] = cbl | python | def register(self, library: str, cbl: Callable[['_AsyncLib'], None]):
'''
Registers a callable to set up a library.
'''
self._handlers[library] = cbl | [
"def",
"register",
"(",
"self",
",",
"library",
":",
"str",
",",
"cbl",
":",
"Callable",
"[",
"[",
"'_AsyncLib'",
"]",
",",
"None",
"]",
")",
":",
"self",
".",
"_handlers",
"[",
"library",
"]",
"=",
"cbl"
] | Registers a callable to set up a library. | [
"Registers",
"a",
"callable",
"to",
"set",
"up",
"a",
"library",
"."
] | 018e4a9f78d5f4e78608a1a1537000b5fd778bbe | https://github.com/theelous3/multio/blob/018e4a9f78d5f4e78608a1a1537000b5fd778bbe/multio/__init__.py#L253-L257 |
24,260 | theelous3/multio | multio/_event_loop_wrappers.py | trio_open_connection | async def trio_open_connection(host, port, *, ssl=False, **kwargs):
'''
Allows connections to be made that may or may not require ssl.
Somewhat surprisingly trio doesn't have an abstraction for this like
curio even though it's fairly trivial to write. Down the line hopefully.
Args:
host (str): Network location, either by domain or IP.
port (int): The requested port.
ssl (bool or SSLContext): If False or None, SSL is not required. If
True, the context returned by trio.ssl.create_default_context will
be used. Otherwise, this may be an SSLContext object.
kwargs: A catch all to soak up curio's additional kwargs and
ignore them.
'''
import trio
if not ssl:
sock = await trio.open_tcp_stream(host, port)
else:
if isinstance(ssl, bool):
ssl_context = None
else:
ssl_context = ssl
sock = await trio.open_ssl_over_tcp_stream(host, port, ssl_context=ssl_context)
await sock.do_handshake()
sock.close = sock.aclose
return sock | python | async def trio_open_connection(host, port, *, ssl=False, **kwargs):
'''
Allows connections to be made that may or may not require ssl.
Somewhat surprisingly trio doesn't have an abstraction for this like
curio even though it's fairly trivial to write. Down the line hopefully.
Args:
host (str): Network location, either by domain or IP.
port (int): The requested port.
ssl (bool or SSLContext): If False or None, SSL is not required. If
True, the context returned by trio.ssl.create_default_context will
be used. Otherwise, this may be an SSLContext object.
kwargs: A catch all to soak up curio's additional kwargs and
ignore them.
'''
import trio
if not ssl:
sock = await trio.open_tcp_stream(host, port)
else:
if isinstance(ssl, bool):
ssl_context = None
else:
ssl_context = ssl
sock = await trio.open_ssl_over_tcp_stream(host, port, ssl_context=ssl_context)
await sock.do_handshake()
sock.close = sock.aclose
return sock | [
"async",
"def",
"trio_open_connection",
"(",
"host",
",",
"port",
",",
"*",
",",
"ssl",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"trio",
"if",
"not",
"ssl",
":",
"sock",
"=",
"await",
"trio",
".",
"open_tcp_stream",
"(",
"host",
","... | Allows connections to be made that may or may not require ssl.
Somewhat surprisingly trio doesn't have an abstraction for this like
curio even though it's fairly trivial to write. Down the line hopefully.
Args:
host (str): Network location, either by domain or IP.
port (int): The requested port.
ssl (bool or SSLContext): If False or None, SSL is not required. If
True, the context returned by trio.ssl.create_default_context will
be used. Otherwise, this may be an SSLContext object.
kwargs: A catch all to soak up curio's additional kwargs and
ignore them. | [
"Allows",
"connections",
"to",
"be",
"made",
"that",
"may",
"or",
"may",
"not",
"require",
"ssl",
".",
"Somewhat",
"surprisingly",
"trio",
"doesn",
"t",
"have",
"an",
"abstraction",
"for",
"this",
"like",
"curio",
"even",
"though",
"it",
"s",
"fairly",
"tr... | 018e4a9f78d5f4e78608a1a1537000b5fd778bbe | https://github.com/theelous3/multio/blob/018e4a9f78d5f4e78608a1a1537000b5fd778bbe/multio/_event_loop_wrappers.py#L12-L39 |
24,261 | Fizzadar/pyinfra | pyinfra/modules/puppet.py | agent | def agent(state, host, server=None, port=None):
"""
Run puppet agent
+ server: master server URL
+ port: puppet master port
"""
args = []
if server:
args.append('--server=%s' % server)
if port:
args.append('--masterport=%s' % port)
yield 'puppet agent -t %s' % ' '.join(args) | python | def agent(state, host, server=None, port=None):
args = []
if server:
args.append('--server=%s' % server)
if port:
args.append('--masterport=%s' % port)
yield 'puppet agent -t %s' % ' '.join(args) | [
"def",
"agent",
"(",
"state",
",",
"host",
",",
"server",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"args",
"=",
"[",
"]",
"if",
"server",
":",
"args",
".",
"append",
"(",
"'--server=%s'",
"%",
"server",
")",
"if",
"port",
":",
"args",
"."... | Run puppet agent
+ server: master server URL
+ port: puppet master port | [
"Run",
"puppet",
"agent"
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/puppet.py#L5-L20 |
24,262 | Fizzadar/pyinfra | pyinfra_cli/config.py | load_config | def load_config(deploy_dir):
'''
Loads any local config.py file.
'''
config = Config()
config_filename = path.join(deploy_dir, 'config.py')
if path.exists(config_filename):
extract_file_config(config_filename, config)
# Now execute the file to trigger loading of any hooks
exec_file(config_filename)
return config | python | def load_config(deploy_dir):
'''
Loads any local config.py file.
'''
config = Config()
config_filename = path.join(deploy_dir, 'config.py')
if path.exists(config_filename):
extract_file_config(config_filename, config)
# Now execute the file to trigger loading of any hooks
exec_file(config_filename)
return config | [
"def",
"load_config",
"(",
"deploy_dir",
")",
":",
"config",
"=",
"Config",
"(",
")",
"config_filename",
"=",
"path",
".",
"join",
"(",
"deploy_dir",
",",
"'config.py'",
")",
"if",
"path",
".",
"exists",
"(",
"config_filename",
")",
":",
"extract_file_config... | Loads any local config.py file. | [
"Loads",
"any",
"local",
"config",
".",
"py",
"file",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra_cli/config.py#L67-L81 |
24,263 | Fizzadar/pyinfra | pyinfra_cli/config.py | load_deploy_config | def load_deploy_config(deploy_filename, config=None):
'''
Loads any local config overrides in the deploy file.
'''
if not config:
config = Config()
if not deploy_filename:
return
if path.exists(deploy_filename):
extract_file_config(deploy_filename, config)
return config | python | def load_deploy_config(deploy_filename, config=None):
'''
Loads any local config overrides in the deploy file.
'''
if not config:
config = Config()
if not deploy_filename:
return
if path.exists(deploy_filename):
extract_file_config(deploy_filename, config)
return config | [
"def",
"load_deploy_config",
"(",
"deploy_filename",
",",
"config",
"=",
"None",
")",
":",
"if",
"not",
"config",
":",
"config",
"=",
"Config",
"(",
")",
"if",
"not",
"deploy_filename",
":",
"return",
"if",
"path",
".",
"exists",
"(",
"deploy_filename",
")... | Loads any local config overrides in the deploy file. | [
"Loads",
"any",
"local",
"config",
"overrides",
"in",
"the",
"deploy",
"file",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra_cli/config.py#L84-L98 |
24,264 | Fizzadar/pyinfra | pyinfra/facts/iptables.py | parse_iptables_rule | def parse_iptables_rule(line):
'''
Parse one iptables rule. Returns a dict where each iptables code argument
is mapped to a name using IPTABLES_ARGS.
'''
bits = line.split()
definition = {}
key = None
args = []
not_arg = False
def add_args():
arg_string = ' '.join(args)
if key in IPTABLES_ARGS:
definition_key = (
'not_{0}'.format(IPTABLES_ARGS[key])
if not_arg
else IPTABLES_ARGS[key]
)
definition[definition_key] = arg_string
else:
definition.setdefault('extras', []).extend((key, arg_string))
for bit in bits:
if bit == '!':
if key:
add_args()
args = []
key = None
not_arg = True
elif bit.startswith('-'):
if key:
add_args()
args = []
not_arg = False
key = bit
else:
args.append(bit)
if key:
add_args()
if 'extras' in definition:
definition['extras'] = set(definition['extras'])
return definition | python | def parse_iptables_rule(line):
'''
Parse one iptables rule. Returns a dict where each iptables code argument
is mapped to a name using IPTABLES_ARGS.
'''
bits = line.split()
definition = {}
key = None
args = []
not_arg = False
def add_args():
arg_string = ' '.join(args)
if key in IPTABLES_ARGS:
definition_key = (
'not_{0}'.format(IPTABLES_ARGS[key])
if not_arg
else IPTABLES_ARGS[key]
)
definition[definition_key] = arg_string
else:
definition.setdefault('extras', []).extend((key, arg_string))
for bit in bits:
if bit == '!':
if key:
add_args()
args = []
key = None
not_arg = True
elif bit.startswith('-'):
if key:
add_args()
args = []
not_arg = False
key = bit
else:
args.append(bit)
if key:
add_args()
if 'extras' in definition:
definition['extras'] = set(definition['extras'])
return definition | [
"def",
"parse_iptables_rule",
"(",
"line",
")",
":",
"bits",
"=",
"line",
".",
"split",
"(",
")",
"definition",
"=",
"{",
"}",
"key",
"=",
"None",
"args",
"=",
"[",
"]",
"not_arg",
"=",
"False",
"def",
"add_args",
"(",
")",
":",
"arg_string",
"=",
... | Parse one iptables rule. Returns a dict where each iptables code argument
is mapped to a name using IPTABLES_ARGS. | [
"Parse",
"one",
"iptables",
"rule",
".",
"Returns",
"a",
"dict",
"where",
"each",
"iptables",
"code",
"argument",
"is",
"mapped",
"to",
"a",
"name",
"using",
"IPTABLES_ARGS",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/facts/iptables.py#L31-L84 |
24,265 | Fizzadar/pyinfra | pyinfra/api/operation.py | add_op | def add_op(state, op_func, *args, **kwargs):
'''
Prepare & add an operation to ``pyinfra.state`` by executing it on all hosts.
Args:
state (``pyinfra.api.State`` obj): the deploy state to add the operation
to op_func (function): the operation function from one of the modules,
ie ``server.user``
args/kwargs: passed to the operation function
'''
frameinfo = get_caller_frameinfo()
kwargs['frameinfo'] = frameinfo
for host in state.inventory:
op_func(state, host, *args, **kwargs) | python | def add_op(state, op_func, *args, **kwargs):
'''
Prepare & add an operation to ``pyinfra.state`` by executing it on all hosts.
Args:
state (``pyinfra.api.State`` obj): the deploy state to add the operation
to op_func (function): the operation function from one of the modules,
ie ``server.user``
args/kwargs: passed to the operation function
'''
frameinfo = get_caller_frameinfo()
kwargs['frameinfo'] = frameinfo
for host in state.inventory:
op_func(state, host, *args, **kwargs) | [
"def",
"add_op",
"(",
"state",
",",
"op_func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"frameinfo",
"=",
"get_caller_frameinfo",
"(",
")",
"kwargs",
"[",
"'frameinfo'",
"]",
"=",
"frameinfo",
"for",
"host",
"in",
"state",
".",
"inventory",
... | Prepare & add an operation to ``pyinfra.state`` by executing it on all hosts.
Args:
state (``pyinfra.api.State`` obj): the deploy state to add the operation
to op_func (function): the operation function from one of the modules,
ie ``server.user``
args/kwargs: passed to the operation function | [
"Prepare",
"&",
"add",
"an",
"operation",
"to",
"pyinfra",
".",
"state",
"by",
"executing",
"it",
"on",
"all",
"hosts",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/operation.py#L59-L74 |
24,266 | Fizzadar/pyinfra | pyinfra/api/deploy.py | add_deploy | def add_deploy(state, deploy_func, *args, **kwargs):
'''
Prepare & add an deploy to pyinfra.state by executing it on all hosts.
Args:
state (``pyinfra.api.State`` obj): the deploy state to add the operation
deploy_func (function): the operation function from one of the modules,
ie ``server.user``
args/kwargs: passed to the operation function
'''
frameinfo = get_caller_frameinfo()
kwargs['frameinfo'] = frameinfo
for host in state.inventory:
deploy_func(state, host, *args, **kwargs) | python | def add_deploy(state, deploy_func, *args, **kwargs):
'''
Prepare & add an deploy to pyinfra.state by executing it on all hosts.
Args:
state (``pyinfra.api.State`` obj): the deploy state to add the operation
deploy_func (function): the operation function from one of the modules,
ie ``server.user``
args/kwargs: passed to the operation function
'''
frameinfo = get_caller_frameinfo()
kwargs['frameinfo'] = frameinfo
for host in state.inventory:
deploy_func(state, host, *args, **kwargs) | [
"def",
"add_deploy",
"(",
"state",
",",
"deploy_func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"frameinfo",
"=",
"get_caller_frameinfo",
"(",
")",
"kwargs",
"[",
"'frameinfo'",
"]",
"=",
"frameinfo",
"for",
"host",
"in",
"state",
".",
"inven... | Prepare & add an deploy to pyinfra.state by executing it on all hosts.
Args:
state (``pyinfra.api.State`` obj): the deploy state to add the operation
deploy_func (function): the operation function from one of the modules,
ie ``server.user``
args/kwargs: passed to the operation function | [
"Prepare",
"&",
"add",
"an",
"deploy",
"to",
"pyinfra",
".",
"state",
"by",
"executing",
"it",
"on",
"all",
"hosts",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/deploy.py#L24-L39 |
24,267 | Fizzadar/pyinfra | pyinfra_cli/legacy.py | setup_arguments | def setup_arguments(arguments):
'''
Prepares argumnents output by docopt.
'''
# Ensure parallel/port are numbers
for key in ('--parallel', '--port', '--fail-percent'):
if arguments[key]:
try:
arguments[key] = int(arguments[key])
except ValueError:
raise CliError('{0} is not a valid integer for {1}'.format(
arguments[key], key,
))
# Prep --run OP ARGS
if arguments['--run']:
op, args = setup_op_and_args(arguments['--run'], arguments['ARGS'])
else:
op = args = None
# Check deploy file exists
if arguments['DEPLOY']:
if not path.exists(arguments['DEPLOY']):
raise CliError('Deploy file not found: {0}'.format(arguments['DEPLOY']))
# Check our key file exists
if arguments['--key']:
if not path.exists(arguments['--key']):
raise CliError('Private key file not found: {0}'.format(arguments['--key']))
# Setup the rest
return {
# Deploy options
'inventory': arguments['-i'],
'deploy': arguments['DEPLOY'],
'verbose': arguments['-v'],
'dry': arguments['--dry'],
'serial': arguments['--serial'],
'no_wait': arguments['--no-wait'],
'debug': arguments['--debug'],
'debug_data': arguments['--debug-data'],
'debug_state': arguments['--debug-state'],
'fact': arguments['--fact'],
'limit': arguments['--limit'],
'op': op,
'op_args': args,
# Config options
'user': arguments['--user'],
'key': arguments['--key'],
'key_password': arguments['--key-password'],
'password': arguments['--password'],
'port': arguments['--port'],
'sudo': arguments['--sudo'],
'sudo_user': arguments['--sudo-user'],
'su_user': arguments['--su-user'],
'parallel': arguments['--parallel'],
'fail_percent': arguments['--fail-percent'],
} | python | def setup_arguments(arguments):
'''
Prepares argumnents output by docopt.
'''
# Ensure parallel/port are numbers
for key in ('--parallel', '--port', '--fail-percent'):
if arguments[key]:
try:
arguments[key] = int(arguments[key])
except ValueError:
raise CliError('{0} is not a valid integer for {1}'.format(
arguments[key], key,
))
# Prep --run OP ARGS
if arguments['--run']:
op, args = setup_op_and_args(arguments['--run'], arguments['ARGS'])
else:
op = args = None
# Check deploy file exists
if arguments['DEPLOY']:
if not path.exists(arguments['DEPLOY']):
raise CliError('Deploy file not found: {0}'.format(arguments['DEPLOY']))
# Check our key file exists
if arguments['--key']:
if not path.exists(arguments['--key']):
raise CliError('Private key file not found: {0}'.format(arguments['--key']))
# Setup the rest
return {
# Deploy options
'inventory': arguments['-i'],
'deploy': arguments['DEPLOY'],
'verbose': arguments['-v'],
'dry': arguments['--dry'],
'serial': arguments['--serial'],
'no_wait': arguments['--no-wait'],
'debug': arguments['--debug'],
'debug_data': arguments['--debug-data'],
'debug_state': arguments['--debug-state'],
'fact': arguments['--fact'],
'limit': arguments['--limit'],
'op': op,
'op_args': args,
# Config options
'user': arguments['--user'],
'key': arguments['--key'],
'key_password': arguments['--key-password'],
'password': arguments['--password'],
'port': arguments['--port'],
'sudo': arguments['--sudo'],
'sudo_user': arguments['--sudo-user'],
'su_user': arguments['--su-user'],
'parallel': arguments['--parallel'],
'fail_percent': arguments['--fail-percent'],
} | [
"def",
"setup_arguments",
"(",
"arguments",
")",
":",
"# Ensure parallel/port are numbers",
"for",
"key",
"in",
"(",
"'--parallel'",
",",
"'--port'",
",",
"'--fail-percent'",
")",
":",
"if",
"arguments",
"[",
"key",
"]",
":",
"try",
":",
"arguments",
"[",
"key... | Prepares argumnents output by docopt. | [
"Prepares",
"argumnents",
"output",
"by",
"docopt",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra_cli/legacy.py#L210-L272 |
24,268 | Fizzadar/pyinfra | pyinfra/modules/mysql.py | sql | def sql(
state, host, sql,
database=None,
# Details for speaking to MySQL via `mysql` CLI
mysql_user=None, mysql_password=None,
mysql_host=None, mysql_port=None,
):
'''
Execute arbitrary SQL against MySQL.
+ sql: SQL command(s) to execute
+ database: optional database to open the connection with
+ mysql_*: global module arguments, see above
'''
yield make_execute_mysql_command(
sql,
database=database,
user=mysql_user,
password=mysql_password,
host=mysql_host,
port=mysql_port,
) | python | def sql(
state, host, sql,
database=None,
# Details for speaking to MySQL via `mysql` CLI
mysql_user=None, mysql_password=None,
mysql_host=None, mysql_port=None,
):
'''
Execute arbitrary SQL against MySQL.
+ sql: SQL command(s) to execute
+ database: optional database to open the connection with
+ mysql_*: global module arguments, see above
'''
yield make_execute_mysql_command(
sql,
database=database,
user=mysql_user,
password=mysql_password,
host=mysql_host,
port=mysql_port,
) | [
"def",
"sql",
"(",
"state",
",",
"host",
",",
"sql",
",",
"database",
"=",
"None",
",",
"# Details for speaking to MySQL via `mysql` CLI",
"mysql_user",
"=",
"None",
",",
"mysql_password",
"=",
"None",
",",
"mysql_host",
"=",
"None",
",",
"mysql_port",
"=",
"N... | Execute arbitrary SQL against MySQL.
+ sql: SQL command(s) to execute
+ database: optional database to open the connection with
+ mysql_*: global module arguments, see above | [
"Execute",
"arbitrary",
"SQL",
"against",
"MySQL",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/mysql.py#L24-L46 |
24,269 | Fizzadar/pyinfra | pyinfra/modules/mysql.py | dump | def dump(
state, host,
remote_filename, database=None,
# Details for speaking to MySQL via `mysql` CLI
mysql_user=None, mysql_password=None,
mysql_host=None, mysql_port=None,
):
'''
Dump a MySQL database into a ``.sql`` file. Requires ``mysqldump``.
+ database: name of the database to dump
+ remote_filename: name of the file to dump the SQL to
+ mysql_*: global module arguments, see above
'''
yield '{0} > {1}'.format(make_mysql_command(
executable='mysqldump',
database=database,
user=mysql_user,
password=mysql_password,
host=mysql_host,
port=mysql_port,
), remote_filename) | python | def dump(
state, host,
remote_filename, database=None,
# Details for speaking to MySQL via `mysql` CLI
mysql_user=None, mysql_password=None,
mysql_host=None, mysql_port=None,
):
'''
Dump a MySQL database into a ``.sql`` file. Requires ``mysqldump``.
+ database: name of the database to dump
+ remote_filename: name of the file to dump the SQL to
+ mysql_*: global module arguments, see above
'''
yield '{0} > {1}'.format(make_mysql_command(
executable='mysqldump',
database=database,
user=mysql_user,
password=mysql_password,
host=mysql_host,
port=mysql_port,
), remote_filename) | [
"def",
"dump",
"(",
"state",
",",
"host",
",",
"remote_filename",
",",
"database",
"=",
"None",
",",
"# Details for speaking to MySQL via `mysql` CLI",
"mysql_user",
"=",
"None",
",",
"mysql_password",
"=",
"None",
",",
"mysql_host",
"=",
"None",
",",
"mysql_port"... | Dump a MySQL database into a ``.sql`` file. Requires ``mysqldump``.
+ database: name of the database to dump
+ remote_filename: name of the file to dump the SQL to
+ mysql_*: global module arguments, see above | [
"Dump",
"a",
"MySQL",
"database",
"into",
"a",
".",
"sql",
"file",
".",
"Requires",
"mysqldump",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/mysql.py#L306-L328 |
24,270 | Fizzadar/pyinfra | pyinfra/api/inventory.py | Inventory.get_host | def get_host(self, name, default=NoHostError):
'''
Get a single host by name.
'''
if name in self.hosts:
return self.hosts[name]
if default is NoHostError:
raise NoHostError('No such host: {0}'.format(name))
return default | python | def get_host(self, name, default=NoHostError):
'''
Get a single host by name.
'''
if name in self.hosts:
return self.hosts[name]
if default is NoHostError:
raise NoHostError('No such host: {0}'.format(name))
return default | [
"def",
"get_host",
"(",
"self",
",",
"name",
",",
"default",
"=",
"NoHostError",
")",
":",
"if",
"name",
"in",
"self",
".",
"hosts",
":",
"return",
"self",
".",
"hosts",
"[",
"name",
"]",
"if",
"default",
"is",
"NoHostError",
":",
"raise",
"NoHostError... | Get a single host by name. | [
"Get",
"a",
"single",
"host",
"by",
"name",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/inventory.py#L258-L269 |
24,271 | Fizzadar/pyinfra | pyinfra/api/inventory.py | Inventory.get_group | def get_group(self, name, default=NoGroupError):
'''
Get a list of hosts belonging to a group.
'''
if name in self.groups:
return self.groups[name]
if default is NoGroupError:
raise NoGroupError('No such group: {0}'.format(name))
return default | python | def get_group(self, name, default=NoGroupError):
'''
Get a list of hosts belonging to a group.
'''
if name in self.groups:
return self.groups[name]
if default is NoGroupError:
raise NoGroupError('No such group: {0}'.format(name))
return default | [
"def",
"get_group",
"(",
"self",
",",
"name",
",",
"default",
"=",
"NoGroupError",
")",
":",
"if",
"name",
"in",
"self",
".",
"groups",
":",
"return",
"self",
".",
"groups",
"[",
"name",
"]",
"if",
"default",
"is",
"NoGroupError",
":",
"raise",
"NoGrou... | Get a list of hosts belonging to a group. | [
"Get",
"a",
"list",
"of",
"hosts",
"belonging",
"to",
"a",
"group",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/inventory.py#L271-L282 |
24,272 | Fizzadar/pyinfra | pyinfra/api/inventory.py | Inventory.get_groups_data | def get_groups_data(self, groups):
'''
Gets aggregated data from a list of groups. Vars are collected in order so, for
any groups which define the same var twice, the last group's value will hold.
'''
data = {}
for group in groups:
data.update(self.get_group_data(group))
return data | python | def get_groups_data(self, groups):
'''
Gets aggregated data from a list of groups. Vars are collected in order so, for
any groups which define the same var twice, the last group's value will hold.
'''
data = {}
for group in groups:
data.update(self.get_group_data(group))
return data | [
"def",
"get_groups_data",
"(",
"self",
",",
"groups",
")",
":",
"data",
"=",
"{",
"}",
"for",
"group",
"in",
"groups",
":",
"data",
".",
"update",
"(",
"self",
".",
"get_group_data",
"(",
"group",
")",
")",
"return",
"data"
] | Gets aggregated data from a list of groups. Vars are collected in order so, for
any groups which define the same var twice, the last group's value will hold. | [
"Gets",
"aggregated",
"data",
"from",
"a",
"list",
"of",
"groups",
".",
"Vars",
"are",
"collected",
"in",
"order",
"so",
"for",
"any",
"groups",
"which",
"define",
"the",
"same",
"var",
"twice",
"the",
"last",
"group",
"s",
"value",
"will",
"hold",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/inventory.py#L312-L323 |
24,273 | Fizzadar/pyinfra | pyinfra/api/inventory.py | Inventory.get_deploy_data | def get_deploy_data(self):
'''
Gets any default data attached to the current deploy, if any.
'''
if self.state and self.state.deploy_data:
return self.state.deploy_data
return {} | python | def get_deploy_data(self):
'''
Gets any default data attached to the current deploy, if any.
'''
if self.state and self.state.deploy_data:
return self.state.deploy_data
return {} | [
"def",
"get_deploy_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"and",
"self",
".",
"state",
".",
"deploy_data",
":",
"return",
"self",
".",
"state",
".",
"deploy_data",
"return",
"{",
"}"
] | Gets any default data attached to the current deploy, if any. | [
"Gets",
"any",
"default",
"data",
"attached",
"to",
"the",
"current",
"deploy",
"if",
"any",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/inventory.py#L325-L333 |
24,274 | Fizzadar/pyinfra | pyinfra/modules/git.py | config | def config(
state, host, key, value,
repo=None,
):
'''
Manage git config for a repository or globally.
+ key: the key of the config to ensure
+ value: the value this key should have
+ repo: specify the git repo path to edit local config (defaults to global)
'''
existing_config = host.fact.git_config(repo)
if key not in existing_config or existing_config[key] != value:
if repo is None:
yield 'git config --global {0} "{1}"'.format(key, value)
else:
yield 'cd {0} && git config --local {1} "{2}"'.format(repo, key, value) | python | def config(
state, host, key, value,
repo=None,
):
'''
Manage git config for a repository or globally.
+ key: the key of the config to ensure
+ value: the value this key should have
+ repo: specify the git repo path to edit local config (defaults to global)
'''
existing_config = host.fact.git_config(repo)
if key not in existing_config or existing_config[key] != value:
if repo is None:
yield 'git config --global {0} "{1}"'.format(key, value)
else:
yield 'cd {0} && git config --local {1} "{2}"'.format(repo, key, value) | [
"def",
"config",
"(",
"state",
",",
"host",
",",
"key",
",",
"value",
",",
"repo",
"=",
"None",
",",
")",
":",
"existing_config",
"=",
"host",
".",
"fact",
".",
"git_config",
"(",
"repo",
")",
"if",
"key",
"not",
"in",
"existing_config",
"or",
"exist... | Manage git config for a repository or globally.
+ key: the key of the config to ensure
+ value: the value this key should have
+ repo: specify the git repo path to edit local config (defaults to global) | [
"Manage",
"git",
"config",
"for",
"a",
"repository",
"or",
"globally",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/git.py#L23-L41 |
24,275 | Fizzadar/pyinfra | pyinfra/local.py | include | def include(filename, hosts=False, when=True):
'''
Executes a local python file within the ``pyinfra.pseudo_state.deploy_dir``
directory.
Args:
hosts (string, list): group name or list of hosts to limit this include to
when (bool): indicate whether to trigger operations in this include
'''
if not pyinfra.is_cli:
raise PyinfraError('local.include is only available in CLI mode.')
if not when:
return
if hosts is not False:
hosts = ensure_host_list(hosts, inventory=pseudo_state.inventory)
if pseudo_host not in hosts:
return
if pseudo_state.deploy_dir:
filename = path.join(pseudo_state.deploy_dir, filename)
frameinfo = get_caller_frameinfo()
logger.debug('Including local file: {0}'.format(filename))
try:
# Fixes a circular import because `pyinfra.local` is really a CLI
# only thing (so should be `pyinfra_cli.local`). It is kept here
# to maintain backwards compatability and the nicer public import
# (ideally users never need to import from `pyinfra_cli`).
from pyinfra_cli.config import extract_file_config
from pyinfra_cli.util import exec_file
# Load any config defined in the file and setup like a @deploy
config_data = extract_file_config(filename)
kwargs = {
key.lower(): value
for key, value in six.iteritems(config_data)
if key in [
'SUDO', 'SUDO_USER', 'SU_USER',
'PRESERVE_SUDO_ENV', 'IGNORE_ERRORS',
]
}
with pseudo_state.deploy(
filename, kwargs, None, frameinfo.lineno,
in_deploy=False,
):
exec_file(filename)
# One potential solution to the above is to add local as an actual
# module, ie `pyinfra.modules.local`.
except IOError as e:
raise PyinfraError(
'Could not include local file: {0}\n{1}'.format(filename, e),
) | python | def include(filename, hosts=False, when=True):
'''
Executes a local python file within the ``pyinfra.pseudo_state.deploy_dir``
directory.
Args:
hosts (string, list): group name or list of hosts to limit this include to
when (bool): indicate whether to trigger operations in this include
'''
if not pyinfra.is_cli:
raise PyinfraError('local.include is only available in CLI mode.')
if not when:
return
if hosts is not False:
hosts = ensure_host_list(hosts, inventory=pseudo_state.inventory)
if pseudo_host not in hosts:
return
if pseudo_state.deploy_dir:
filename = path.join(pseudo_state.deploy_dir, filename)
frameinfo = get_caller_frameinfo()
logger.debug('Including local file: {0}'.format(filename))
try:
# Fixes a circular import because `pyinfra.local` is really a CLI
# only thing (so should be `pyinfra_cli.local`). It is kept here
# to maintain backwards compatability and the nicer public import
# (ideally users never need to import from `pyinfra_cli`).
from pyinfra_cli.config import extract_file_config
from pyinfra_cli.util import exec_file
# Load any config defined in the file and setup like a @deploy
config_data = extract_file_config(filename)
kwargs = {
key.lower(): value
for key, value in six.iteritems(config_data)
if key in [
'SUDO', 'SUDO_USER', 'SU_USER',
'PRESERVE_SUDO_ENV', 'IGNORE_ERRORS',
]
}
with pseudo_state.deploy(
filename, kwargs, None, frameinfo.lineno,
in_deploy=False,
):
exec_file(filename)
# One potential solution to the above is to add local as an actual
# module, ie `pyinfra.modules.local`.
except IOError as e:
raise PyinfraError(
'Could not include local file: {0}\n{1}'.format(filename, e),
) | [
"def",
"include",
"(",
"filename",
",",
"hosts",
"=",
"False",
",",
"when",
"=",
"True",
")",
":",
"if",
"not",
"pyinfra",
".",
"is_cli",
":",
"raise",
"PyinfraError",
"(",
"'local.include is only available in CLI mode.'",
")",
"if",
"not",
"when",
":",
"ret... | Executes a local python file within the ``pyinfra.pseudo_state.deploy_dir``
directory.
Args:
hosts (string, list): group name or list of hosts to limit this include to
when (bool): indicate whether to trigger operations in this include | [
"Executes",
"a",
"local",
"python",
"file",
"within",
"the",
"pyinfra",
".",
"pseudo_state",
".",
"deploy_dir",
"directory",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/local.py#L19-L78 |
24,276 | jdowner/gist | gist/gist.py | GistAPI.send | def send(self, request, stem=None):
"""Prepare and send a request
Arguments:
request: a Request object that is not yet prepared
stem: a path to append to the root URL
Returns:
The response to the request
"""
if stem is not None:
request.url = request.url + "/" + stem.lstrip("/")
prepped = self.session.prepare_request(request)
settings = self.session.merge_environment_settings(url=prepped.url,
proxies={},
stream=None,
verify=None,
cert=None)
return self.session.send(prepped, **settings) | python | def send(self, request, stem=None):
if stem is not None:
request.url = request.url + "/" + stem.lstrip("/")
prepped = self.session.prepare_request(request)
settings = self.session.merge_environment_settings(url=prepped.url,
proxies={},
stream=None,
verify=None,
cert=None)
return self.session.send(prepped, **settings) | [
"def",
"send",
"(",
"self",
",",
"request",
",",
"stem",
"=",
"None",
")",
":",
"if",
"stem",
"is",
"not",
"None",
":",
"request",
".",
"url",
"=",
"request",
".",
"url",
"+",
"\"/\"",
"+",
"stem",
".",
"lstrip",
"(",
"\"/\"",
")",
"prepped",
"="... | Prepare and send a request
Arguments:
request: a Request object that is not yet prepared
stem: a path to append to the root URL
Returns:
The response to the request | [
"Prepare",
"and",
"send",
"a",
"request"
] | 0f2941434f63c5aed69218edad454de8c73819a0 | https://github.com/jdowner/gist/blob/0f2941434f63c5aed69218edad454de8c73819a0/gist/gist.py#L143-L164 |
24,277 | jdowner/gist | gist/gist.py | GistAPI.list | def list(self):
"""Returns a list of the users gists as GistInfo objects
Returns:
a list of GistInfo objects
"""
# Define the basic request. The per_page parameter is set to 100, which
# is the maximum github allows. If the user has more than one page of
# gists, this request object will be modified to retrieve each
# successive page of gists.
request = requests.Request(
'GET',
'https://api.github.com/gists',
headers={
'Accept-Encoding': 'identity, deflate, compress, gzip',
'User-Agent': 'python-requests/1.2.0',
'Accept': 'application/vnd.github.v3.base64',
},
params={
'access_token': self.token,
'per_page': 100,
},
)
# Github provides a 'link' header that contains information to
# navigate through a users page of gists. This regex is used to
# extract the URLs contained in this header, and to find the next page
# of gists.
pattern = re.compile(r'<([^>]*)>; rel="([^"]*)"')
gists = []
while True:
# Retrieve the next page of gists
try:
response = self.send(request).json()
except Exception:
break
# Extract the list of gists
for gist in response:
try:
gists.append(
GistInfo(
gist['id'],
gist['public'],
gist['description'],
)
)
except KeyError:
continue
try:
link = response.headers['link']
# Search for the next page of gist. If a 'next' page is found,
# the URL is set to this new page and the iteration continues.
# If there is no next page, return the list of gists.
for result in pattern.finditer(link):
url = result.group(1)
rel = result.group(2)
if rel == 'next':
request.url = url
break
else:
return gists
except Exception:
break
return gists | python | def list(self):
# Define the basic request. The per_page parameter is set to 100, which
# is the maximum github allows. If the user has more than one page of
# gists, this request object will be modified to retrieve each
# successive page of gists.
request = requests.Request(
'GET',
'https://api.github.com/gists',
headers={
'Accept-Encoding': 'identity, deflate, compress, gzip',
'User-Agent': 'python-requests/1.2.0',
'Accept': 'application/vnd.github.v3.base64',
},
params={
'access_token': self.token,
'per_page': 100,
},
)
# Github provides a 'link' header that contains information to
# navigate through a users page of gists. This regex is used to
# extract the URLs contained in this header, and to find the next page
# of gists.
pattern = re.compile(r'<([^>]*)>; rel="([^"]*)"')
gists = []
while True:
# Retrieve the next page of gists
try:
response = self.send(request).json()
except Exception:
break
# Extract the list of gists
for gist in response:
try:
gists.append(
GistInfo(
gist['id'],
gist['public'],
gist['description'],
)
)
except KeyError:
continue
try:
link = response.headers['link']
# Search for the next page of gist. If a 'next' page is found,
# the URL is set to this new page and the iteration continues.
# If there is no next page, return the list of gists.
for result in pattern.finditer(link):
url = result.group(1)
rel = result.group(2)
if rel == 'next':
request.url = url
break
else:
return gists
except Exception:
break
return gists | [
"def",
"list",
"(",
"self",
")",
":",
"# Define the basic request. The per_page parameter is set to 100, which",
"# is the maximum github allows. If the user has more than one page of",
"# gists, this request object will be modified to retrieve each",
"# successive page of gists.",
"request",
... | Returns a list of the users gists as GistInfo objects
Returns:
a list of GistInfo objects | [
"Returns",
"a",
"list",
"of",
"the",
"users",
"gists",
"as",
"GistInfo",
"objects"
] | 0f2941434f63c5aed69218edad454de8c73819a0 | https://github.com/jdowner/gist/blob/0f2941434f63c5aed69218edad454de8c73819a0/gist/gist.py#L166-L239 |
24,278 | jdowner/gist | gist/gist.py | GistAPI.create | def create(self, request, desc, files, public=False):
"""Creates a gist
Arguments:
request: an initial request object
desc: the gist description
files: a list of files to add to the gist
public: a flag to indicate whether the gist is public or not
Returns:
The URL to the newly created gist.
"""
request.data = json.dumps({
"description": desc,
"public": public,
"files": files,
})
return self.send(request).json()['html_url'] | python | def create(self, request, desc, files, public=False):
request.data = json.dumps({
"description": desc,
"public": public,
"files": files,
})
return self.send(request).json()['html_url'] | [
"def",
"create",
"(",
"self",
",",
"request",
",",
"desc",
",",
"files",
",",
"public",
"=",
"False",
")",
":",
"request",
".",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"\"description\"",
":",
"desc",
",",
"\"public\"",
":",
"public",
",",
"\"fil... | Creates a gist
Arguments:
request: an initial request object
desc: the gist description
files: a list of files to add to the gist
public: a flag to indicate whether the gist is public or not
Returns:
The URL to the newly created gist. | [
"Creates",
"a",
"gist"
] | 0f2941434f63c5aed69218edad454de8c73819a0 | https://github.com/jdowner/gist/blob/0f2941434f63c5aed69218edad454de8c73819a0/gist/gist.py#L242-L260 |
24,279 | jdowner/gist | gist/gist.py | GistAPI.files | def files(self, request, id):
"""Returns a list of files in the gist
Arguments:
request: an initial request object
id: the gist identifier
Returns:
A list of the files
"""
gist = self.send(request, id).json()
return gist['files'] | python | def files(self, request, id):
gist = self.send(request, id).json()
return gist['files'] | [
"def",
"files",
"(",
"self",
",",
"request",
",",
"id",
")",
":",
"gist",
"=",
"self",
".",
"send",
"(",
"request",
",",
"id",
")",
".",
"json",
"(",
")",
"return",
"gist",
"[",
"'files'",
"]"
] | Returns a list of files in the gist
Arguments:
request: an initial request object
id: the gist identifier
Returns:
A list of the files | [
"Returns",
"a",
"list",
"of",
"files",
"in",
"the",
"gist"
] | 0f2941434f63c5aed69218edad454de8c73819a0 | https://github.com/jdowner/gist/blob/0f2941434f63c5aed69218edad454de8c73819a0/gist/gist.py#L288-L300 |
24,280 | jdowner/gist | gist/gist.py | GistAPI.content | def content(self, request, id):
"""Returns the content of the gist
Arguments:
request: an initial request object
id: the gist identifier
Returns:
A dict containing the contents of each file in the gist
"""
gist = self.send(request, id).json()
def convert(data):
return base64.b64decode(data).decode('utf-8')
content = {}
for name, data in gist['files'].items():
content[name] = convert(data['content'])
return content | python | def content(self, request, id):
gist = self.send(request, id).json()
def convert(data):
return base64.b64decode(data).decode('utf-8')
content = {}
for name, data in gist['files'].items():
content[name] = convert(data['content'])
return content | [
"def",
"content",
"(",
"self",
",",
"request",
",",
"id",
")",
":",
"gist",
"=",
"self",
".",
"send",
"(",
"request",
",",
"id",
")",
".",
"json",
"(",
")",
"def",
"convert",
"(",
"data",
")",
":",
"return",
"base64",
".",
"b64decode",
"(",
"data... | Returns the content of the gist
Arguments:
request: an initial request object
id: the gist identifier
Returns:
A dict containing the contents of each file in the gist | [
"Returns",
"the",
"content",
"of",
"the",
"gist"
] | 0f2941434f63c5aed69218edad454de8c73819a0 | https://github.com/jdowner/gist/blob/0f2941434f63c5aed69218edad454de8c73819a0/gist/gist.py#L303-L323 |
24,281 | jdowner/gist | gist/gist.py | GistAPI.archive | def archive(self, request, id):
"""Create an archive of a gist
The files in the gist are downloaded and added to a compressed archive
(tarball). If the ID of the gist was c78d925546e964b4b1df, the
resulting archive would be,
c78d925546e964b4b1df.tar.gz
The archive is created in the directory where the command is invoked.
Arguments:
request: an initial request object
id: the gist identifier
"""
gist = self.send(request, id).json()
with tarfile.open('{}.tar.gz'.format(id), mode='w:gz') as archive:
for name, data in gist['files'].items():
with tempfile.NamedTemporaryFile('w+') as fp:
fp.write(data['content'])
fp.flush()
archive.add(fp.name, arcname=name) | python | def archive(self, request, id):
gist = self.send(request, id).json()
with tarfile.open('{}.tar.gz'.format(id), mode='w:gz') as archive:
for name, data in gist['files'].items():
with tempfile.NamedTemporaryFile('w+') as fp:
fp.write(data['content'])
fp.flush()
archive.add(fp.name, arcname=name) | [
"def",
"archive",
"(",
"self",
",",
"request",
",",
"id",
")",
":",
"gist",
"=",
"self",
".",
"send",
"(",
"request",
",",
"id",
")",
".",
"json",
"(",
")",
"with",
"tarfile",
".",
"open",
"(",
"'{}.tar.gz'",
".",
"format",
"(",
"id",
")",
",",
... | Create an archive of a gist
The files in the gist are downloaded and added to a compressed archive
(tarball). If the ID of the gist was c78d925546e964b4b1df, the
resulting archive would be,
c78d925546e964b4b1df.tar.gz
The archive is created in the directory where the command is invoked.
Arguments:
request: an initial request object
id: the gist identifier | [
"Create",
"an",
"archive",
"of",
"a",
"gist"
] | 0f2941434f63c5aed69218edad454de8c73819a0 | https://github.com/jdowner/gist/blob/0f2941434f63c5aed69218edad454de8c73819a0/gist/gist.py#L326-L349 |
24,282 | jdowner/gist | gist/gist.py | GistAPI.edit | def edit(self, request, id):
"""Edit a gist
The files in the gist a cloned to a temporary directory and passed to
the default editor (defined by the EDITOR environmental variable). When
the user exits the editor, they will be provided with a prompt to
commit the changes, which will then be pushed to the remote.
Arguments:
request: an initial request object
id: the gist identifier
"""
with pushd(tempfile.gettempdir()):
try:
self.clone(id)
with pushd(id):
files = [f for f in os.listdir('.') if os.path.isfile(f)]
quoted = ['"{}"'.format(f) for f in files]
os.system("{} {}".format(self.editor, ' '.join(quoted)))
os.system('git commit -av && git push')
finally:
shutil.rmtree(id) | python | def edit(self, request, id):
with pushd(tempfile.gettempdir()):
try:
self.clone(id)
with pushd(id):
files = [f for f in os.listdir('.') if os.path.isfile(f)]
quoted = ['"{}"'.format(f) for f in files]
os.system("{} {}".format(self.editor, ' '.join(quoted)))
os.system('git commit -av && git push')
finally:
shutil.rmtree(id) | [
"def",
"edit",
"(",
"self",
",",
"request",
",",
"id",
")",
":",
"with",
"pushd",
"(",
"tempfile",
".",
"gettempdir",
"(",
")",
")",
":",
"try",
":",
"self",
".",
"clone",
"(",
"id",
")",
"with",
"pushd",
"(",
"id",
")",
":",
"files",
"=",
"[",... | Edit a gist
The files in the gist a cloned to a temporary directory and passed to
the default editor (defined by the EDITOR environmental variable). When
the user exits the editor, they will be provided with a prompt to
commit the changes, which will then be pushed to the remote.
Arguments:
request: an initial request object
id: the gist identifier | [
"Edit",
"a",
"gist"
] | 0f2941434f63c5aed69218edad454de8c73819a0 | https://github.com/jdowner/gist/blob/0f2941434f63c5aed69218edad454de8c73819a0/gist/gist.py#L352-L375 |
24,283 | jdowner/gist | gist/gist.py | GistAPI.description | def description(self, request, id, description):
"""Updates the description of a gist
Arguments:
request: an initial request object
id: the id of the gist we want to edit the description for
description: the new description
"""
request.data = json.dumps({
"description": description
})
return self.send(request, id).json()['html_url'] | python | def description(self, request, id, description):
request.data = json.dumps({
"description": description
})
return self.send(request, id).json()['html_url'] | [
"def",
"description",
"(",
"self",
",",
"request",
",",
"id",
",",
"description",
")",
":",
"request",
".",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"\"description\"",
":",
"description",
"}",
")",
"return",
"self",
".",
"send",
"(",
"request",
","... | Updates the description of a gist
Arguments:
request: an initial request object
id: the id of the gist we want to edit the description for
description: the new description | [
"Updates",
"the",
"description",
"of",
"a",
"gist"
] | 0f2941434f63c5aed69218edad454de8c73819a0 | https://github.com/jdowner/gist/blob/0f2941434f63c5aed69218edad454de8c73819a0/gist/gist.py#L391-L403 |
24,284 | jdowner/gist | gist/gist.py | GistAPI.clone | def clone(self, id, name=None):
"""Clone a gist
Arguments:
id: the gist identifier
name: the name to give the cloned repo
"""
url = 'git@gist.github.com:/{}'.format(id)
if name is None:
os.system('git clone {}'.format(url))
else:
os.system('git clone {} {}'.format(url, name)) | python | def clone(self, id, name=None):
url = 'git@gist.github.com:/{}'.format(id)
if name is None:
os.system('git clone {}'.format(url))
else:
os.system('git clone {} {}'.format(url, name)) | [
"def",
"clone",
"(",
"self",
",",
"id",
",",
"name",
"=",
"None",
")",
":",
"url",
"=",
"'git@gist.github.com:/{}'",
".",
"format",
"(",
"id",
")",
"if",
"name",
"is",
"None",
":",
"os",
".",
"system",
"(",
"'git clone {}'",
".",
"format",
"(",
"url"... | Clone a gist
Arguments:
id: the gist identifier
name: the name to give the cloned repo | [
"Clone",
"a",
"gist"
] | 0f2941434f63c5aed69218edad454de8c73819a0 | https://github.com/jdowner/gist/blob/0f2941434f63c5aed69218edad454de8c73819a0/gist/gist.py#L405-L418 |
24,285 | Fizzadar/pyinfra | pyinfra/modules/ssh.py | command | def command(state, host, hostname, command, ssh_user=None):
'''
Execute commands on other servers over SSH.
+ hostname: the hostname to connect to
+ command: the command to execute
+ ssh_user: connect with this user
'''
connection_target = hostname
if ssh_user:
connection_target = '@'.join((ssh_user, hostname))
yield 'ssh {0} "{1}"'.format(connection_target, command) | python | def command(state, host, hostname, command, ssh_user=None):
'''
Execute commands on other servers over SSH.
+ hostname: the hostname to connect to
+ command: the command to execute
+ ssh_user: connect with this user
'''
connection_target = hostname
if ssh_user:
connection_target = '@'.join((ssh_user, hostname))
yield 'ssh {0} "{1}"'.format(connection_target, command) | [
"def",
"command",
"(",
"state",
",",
"host",
",",
"hostname",
",",
"command",
",",
"ssh_user",
"=",
"None",
")",
":",
"connection_target",
"=",
"hostname",
"if",
"ssh_user",
":",
"connection_target",
"=",
"'@'",
".",
"join",
"(",
"(",
"ssh_user",
",",
"h... | Execute commands on other servers over SSH.
+ hostname: the hostname to connect to
+ command: the command to execute
+ ssh_user: connect with this user | [
"Execute",
"commands",
"on",
"other",
"servers",
"over",
"SSH",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/ssh.py#L47-L60 |
24,286 | Fizzadar/pyinfra | pyinfra/modules/ssh.py | upload | def upload(
state, host, hostname, filename,
remote_filename=None, use_remote_sudo=False,
ssh_keyscan=False, ssh_user=None,
):
'''
Upload files to other servers using ``scp``.
+ hostname: hostname to upload to
+ filename: file to upload
+ remote_filename: where to upload the file to (defaults to ``filename``)
+ use_remote_sudo: upload to a temporary location and move using sudo
+ ssh_keyscan: execute ``ssh.keyscan`` before uploading the file
+ ssh_user: connect with this user
'''
remote_filename = remote_filename or filename
# Figure out where we're connecting (host or user@host)
connection_target = hostname
if ssh_user:
connection_target = '@'.join((ssh_user, hostname))
if ssh_keyscan:
yield keyscan(state, host, hostname)
# If we're not using sudo on the remote side, just scp the file over
if not use_remote_sudo:
yield 'scp {0} {1}:{2}'.format(filename, connection_target, remote_filename)
else:
# Otherwise - we need a temporary location for the file
temp_remote_filename = state.get_temp_filename()
# scp it to the temporary location
upload_cmd = 'scp {0} {1}:{2}'.format(
filename, connection_target, temp_remote_filename,
)
yield upload_cmd
# And sudo sudo to move it
yield command(state, host, connection_target, 'sudo mv {0} {1}'.format(
temp_remote_filename, remote_filename,
)) | python | def upload(
state, host, hostname, filename,
remote_filename=None, use_remote_sudo=False,
ssh_keyscan=False, ssh_user=None,
):
'''
Upload files to other servers using ``scp``.
+ hostname: hostname to upload to
+ filename: file to upload
+ remote_filename: where to upload the file to (defaults to ``filename``)
+ use_remote_sudo: upload to a temporary location and move using sudo
+ ssh_keyscan: execute ``ssh.keyscan`` before uploading the file
+ ssh_user: connect with this user
'''
remote_filename = remote_filename or filename
# Figure out where we're connecting (host or user@host)
connection_target = hostname
if ssh_user:
connection_target = '@'.join((ssh_user, hostname))
if ssh_keyscan:
yield keyscan(state, host, hostname)
# If we're not using sudo on the remote side, just scp the file over
if not use_remote_sudo:
yield 'scp {0} {1}:{2}'.format(filename, connection_target, remote_filename)
else:
# Otherwise - we need a temporary location for the file
temp_remote_filename = state.get_temp_filename()
# scp it to the temporary location
upload_cmd = 'scp {0} {1}:{2}'.format(
filename, connection_target, temp_remote_filename,
)
yield upload_cmd
# And sudo sudo to move it
yield command(state, host, connection_target, 'sudo mv {0} {1}'.format(
temp_remote_filename, remote_filename,
)) | [
"def",
"upload",
"(",
"state",
",",
"host",
",",
"hostname",
",",
"filename",
",",
"remote_filename",
"=",
"None",
",",
"use_remote_sudo",
"=",
"False",
",",
"ssh_keyscan",
"=",
"False",
",",
"ssh_user",
"=",
"None",
",",
")",
":",
"remote_filename",
"=",
... | Upload files to other servers using ``scp``.
+ hostname: hostname to upload to
+ filename: file to upload
+ remote_filename: where to upload the file to (defaults to ``filename``)
+ use_remote_sudo: upload to a temporary location and move using sudo
+ ssh_keyscan: execute ``ssh.keyscan`` before uploading the file
+ ssh_user: connect with this user | [
"Upload",
"files",
"to",
"other",
"servers",
"using",
"scp",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/ssh.py#L64-L108 |
24,287 | Fizzadar/pyinfra | pyinfra/modules/ssh.py | download | def download(
state, host, hostname, filename,
local_filename=None, force=False,
ssh_keyscan=False, ssh_user=None,
):
'''
Download files from other servers using ``scp``.
+ hostname: hostname to upload to
+ filename: file to download
+ local_filename: where to download the file to (defaults to ``filename``)
+ force: always download the file, even if present locally
+ ssh_keyscan: execute ``ssh.keyscan`` before uploading the file
+ ssh_user: connect with this user
'''
local_filename = local_filename or filename
# Get local file info
local_file_info = host.fact.file(local_filename)
# Local file exists but isn't a file?
if local_file_info is False:
raise OperationError(
'Local destination {0} already exists and is not a file'.format(
local_filename,
),
)
# If the local file exists and we're not forcing a re-download, no-op
if local_file_info and not force:
return
# Figure out where we're connecting (host or user@host)
connection_target = hostname
if ssh_user:
connection_target = '@'.join((ssh_user, hostname))
if ssh_keyscan:
yield keyscan(state, host, hostname)
# Download the file with scp
yield 'scp {0}:{1} {2}'.format(connection_target, filename, local_filename) | python | def download(
state, host, hostname, filename,
local_filename=None, force=False,
ssh_keyscan=False, ssh_user=None,
):
'''
Download files from other servers using ``scp``.
+ hostname: hostname to upload to
+ filename: file to download
+ local_filename: where to download the file to (defaults to ``filename``)
+ force: always download the file, even if present locally
+ ssh_keyscan: execute ``ssh.keyscan`` before uploading the file
+ ssh_user: connect with this user
'''
local_filename = local_filename or filename
# Get local file info
local_file_info = host.fact.file(local_filename)
# Local file exists but isn't a file?
if local_file_info is False:
raise OperationError(
'Local destination {0} already exists and is not a file'.format(
local_filename,
),
)
# If the local file exists and we're not forcing a re-download, no-op
if local_file_info and not force:
return
# Figure out where we're connecting (host or user@host)
connection_target = hostname
if ssh_user:
connection_target = '@'.join((ssh_user, hostname))
if ssh_keyscan:
yield keyscan(state, host, hostname)
# Download the file with scp
yield 'scp {0}:{1} {2}'.format(connection_target, filename, local_filename) | [
"def",
"download",
"(",
"state",
",",
"host",
",",
"hostname",
",",
"filename",
",",
"local_filename",
"=",
"None",
",",
"force",
"=",
"False",
",",
"ssh_keyscan",
"=",
"False",
",",
"ssh_user",
"=",
"None",
",",
")",
":",
"local_filename",
"=",
"local_f... | Download files from other servers using ``scp``.
+ hostname: hostname to upload to
+ filename: file to download
+ local_filename: where to download the file to (defaults to ``filename``)
+ force: always download the file, even if present locally
+ ssh_keyscan: execute ``ssh.keyscan`` before uploading the file
+ ssh_user: connect with this user | [
"Download",
"files",
"from",
"other",
"servers",
"using",
"scp",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/ssh.py#L112-L154 |
24,288 | Fizzadar/pyinfra | pyinfra/api/util.py | pop_op_kwargs | def pop_op_kwargs(state, kwargs):
'''
Pop and return operation global keyword arguments.
'''
meta_kwargs = state.deploy_kwargs or {}
def get_kwarg(key, default=None):
return kwargs.pop(key, meta_kwargs.get(key, default))
# Get the env for this host: config env followed by command-level env
env = state.config.ENV.copy()
env.update(get_kwarg('env', {}))
hosts = get_kwarg('hosts')
hosts = ensure_host_list(hosts, inventory=state.inventory)
# Filter out any hosts not in the meta kwargs (nested support)
if meta_kwargs.get('hosts') is not None:
hosts = [
host for host in hosts
if host in meta_kwargs['hosts']
]
return {
# ENVars for commands in this operation
'env': env,
# Hosts to limit the op to
'hosts': hosts,
# When to limit the op (default always)
'when': get_kwarg('when', True),
# Locally & globally configurable
'sudo': get_kwarg('sudo', state.config.SUDO),
'sudo_user': get_kwarg('sudo_user', state.config.SUDO_USER),
'su_user': get_kwarg('su_user', state.config.SU_USER),
# Whether to preserve ENVars when sudoing (eg SSH forward agent socket)
'preserve_sudo_env': get_kwarg(
'preserve_sudo_env', state.config.PRESERVE_SUDO_ENV,
),
# Ignore any errors during this operation
'ignore_errors': get_kwarg(
'ignore_errors', state.config.IGNORE_ERRORS,
),
# Timeout on running the command
'timeout': get_kwarg('timeout'),
# Get a PTY before executing commands
'get_pty': get_kwarg('get_pty', False),
# Forces serial mode for this operation (--serial for one op)
'serial': get_kwarg('serial', False),
# Only runs this operation once
'run_once': get_kwarg('run_once', False),
# Execute in batches of X hosts rather than all at once
'parallel': get_kwarg('parallel'),
# Callbacks
'on_success': get_kwarg('on_success'),
'on_error': get_kwarg('on_error'),
# Operation hash
'op': get_kwarg('op'),
} | python | def pop_op_kwargs(state, kwargs):
'''
Pop and return operation global keyword arguments.
'''
meta_kwargs = state.deploy_kwargs or {}
def get_kwarg(key, default=None):
return kwargs.pop(key, meta_kwargs.get(key, default))
# Get the env for this host: config env followed by command-level env
env = state.config.ENV.copy()
env.update(get_kwarg('env', {}))
hosts = get_kwarg('hosts')
hosts = ensure_host_list(hosts, inventory=state.inventory)
# Filter out any hosts not in the meta kwargs (nested support)
if meta_kwargs.get('hosts') is not None:
hosts = [
host for host in hosts
if host in meta_kwargs['hosts']
]
return {
# ENVars for commands in this operation
'env': env,
# Hosts to limit the op to
'hosts': hosts,
# When to limit the op (default always)
'when': get_kwarg('when', True),
# Locally & globally configurable
'sudo': get_kwarg('sudo', state.config.SUDO),
'sudo_user': get_kwarg('sudo_user', state.config.SUDO_USER),
'su_user': get_kwarg('su_user', state.config.SU_USER),
# Whether to preserve ENVars when sudoing (eg SSH forward agent socket)
'preserve_sudo_env': get_kwarg(
'preserve_sudo_env', state.config.PRESERVE_SUDO_ENV,
),
# Ignore any errors during this operation
'ignore_errors': get_kwarg(
'ignore_errors', state.config.IGNORE_ERRORS,
),
# Timeout on running the command
'timeout': get_kwarg('timeout'),
# Get a PTY before executing commands
'get_pty': get_kwarg('get_pty', False),
# Forces serial mode for this operation (--serial for one op)
'serial': get_kwarg('serial', False),
# Only runs this operation once
'run_once': get_kwarg('run_once', False),
# Execute in batches of X hosts rather than all at once
'parallel': get_kwarg('parallel'),
# Callbacks
'on_success': get_kwarg('on_success'),
'on_error': get_kwarg('on_error'),
# Operation hash
'op': get_kwarg('op'),
} | [
"def",
"pop_op_kwargs",
"(",
"state",
",",
"kwargs",
")",
":",
"meta_kwargs",
"=",
"state",
".",
"deploy_kwargs",
"or",
"{",
"}",
"def",
"get_kwarg",
"(",
"key",
",",
"default",
"=",
"None",
")",
":",
"return",
"kwargs",
".",
"pop",
"(",
"key",
",",
... | Pop and return operation global keyword arguments. | [
"Pop",
"and",
"return",
"operation",
"global",
"keyword",
"arguments",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/util.py#L119-L177 |
24,289 | Fizzadar/pyinfra | pyinfra/api/util.py | get_template | def get_template(filename_or_string, is_string=False):
'''
Gets a jinja2 ``Template`` object for the input filename or string, with caching
based on the filename of the template, or the SHA1 of the input string.
'''
# Cache against string sha or just the filename
cache_key = sha1_hash(filename_or_string) if is_string else filename_or_string
if cache_key in TEMPLATES:
return TEMPLATES[cache_key]
if is_string:
# Set the input string as our template
template_string = filename_or_string
else:
# Load template data into memory
with open(filename_or_string, 'r') as file_io:
template_string = file_io.read()
TEMPLATES[cache_key] = Template(template_string, keep_trailing_newline=True)
return TEMPLATES[cache_key] | python | def get_template(filename_or_string, is_string=False):
'''
Gets a jinja2 ``Template`` object for the input filename or string, with caching
based on the filename of the template, or the SHA1 of the input string.
'''
# Cache against string sha or just the filename
cache_key = sha1_hash(filename_or_string) if is_string else filename_or_string
if cache_key in TEMPLATES:
return TEMPLATES[cache_key]
if is_string:
# Set the input string as our template
template_string = filename_or_string
else:
# Load template data into memory
with open(filename_or_string, 'r') as file_io:
template_string = file_io.read()
TEMPLATES[cache_key] = Template(template_string, keep_trailing_newline=True)
return TEMPLATES[cache_key] | [
"def",
"get_template",
"(",
"filename_or_string",
",",
"is_string",
"=",
"False",
")",
":",
"# Cache against string sha or just the filename",
"cache_key",
"=",
"sha1_hash",
"(",
"filename_or_string",
")",
"if",
"is_string",
"else",
"filename_or_string",
"if",
"cache_key"... | Gets a jinja2 ``Template`` object for the input filename or string, with caching
based on the filename of the template, or the SHA1 of the input string. | [
"Gets",
"a",
"jinja2",
"Template",
"object",
"for",
"the",
"input",
"filename",
"or",
"string",
"with",
"caching",
"based",
"on",
"the",
"filename",
"of",
"the",
"template",
"or",
"the",
"SHA1",
"of",
"the",
"input",
"string",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/util.py#L202-L224 |
24,290 | Fizzadar/pyinfra | pyinfra/api/util.py | underscore | def underscore(name):
'''
Transform CamelCase -> snake_case.
'''
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | python | def underscore(name):
'''
Transform CamelCase -> snake_case.
'''
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | [
"def",
"underscore",
"(",
"name",
")",
":",
"s1",
"=",
"re",
".",
"sub",
"(",
"'(.)([A-Z][a-z]+)'",
",",
"r'\\1_\\2'",
",",
"name",
")",
"return",
"re",
".",
"sub",
"(",
"'([a-z0-9])([A-Z])'",
",",
"r'\\1_\\2'",
",",
"s1",
")",
".",
"lower",
"(",
")"
] | Transform CamelCase -> snake_case. | [
"Transform",
"CamelCase",
"-",
">",
"snake_case",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/util.py#L227-L233 |
24,291 | Fizzadar/pyinfra | pyinfra/api/util.py | sha1_hash | def sha1_hash(string):
'''
Return the SHA1 of the input string.
'''
hasher = sha1()
hasher.update(string.encode())
return hasher.hexdigest() | python | def sha1_hash(string):
'''
Return the SHA1 of the input string.
'''
hasher = sha1()
hasher.update(string.encode())
return hasher.hexdigest() | [
"def",
"sha1_hash",
"(",
"string",
")",
":",
"hasher",
"=",
"sha1",
"(",
")",
"hasher",
".",
"update",
"(",
"string",
".",
"encode",
"(",
")",
")",
"return",
"hasher",
".",
"hexdigest",
"(",
")"
] | Return the SHA1 of the input string. | [
"Return",
"the",
"SHA1",
"of",
"the",
"input",
"string",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/util.py#L236-L243 |
24,292 | Fizzadar/pyinfra | pyinfra/api/util.py | make_command | def make_command(
command,
env=None,
su_user=None,
sudo=False,
sudo_user=None,
preserve_sudo_env=False,
):
'''
Builds a shell command with various kwargs.
'''
debug_meta = {}
for key, value in (
('sudo', sudo),
('sudo_user', sudo_user),
('su_user', su_user),
('env', env),
):
if value:
debug_meta[key] = value
logger.debug('Building command ({0}): {1}'.format(' '.join(
'{0}: {1}'.format(key, value)
for key, value in six.iteritems(debug_meta)
), command))
# Use env & build our actual command
if env:
env_string = ' '.join([
'{0}={1}'.format(key, value)
for key, value in six.iteritems(env)
])
command = 'export {0}; {1}'.format(env_string, command)
# Quote the command as a string
command = shlex_quote(command)
# Switch user with su
if su_user:
command = 'su {0} -c {1}'.format(su_user, command)
# Otherwise just sh wrap the command
else:
command = 'sh -c {0}'.format(command)
# Use sudo (w/user?)
if sudo:
sudo_bits = ['sudo', '-H']
if preserve_sudo_env:
sudo_bits.append('-E')
if sudo_user:
sudo_bits.extend(('-u', sudo_user))
command = '{0} {1}'.format(' '.join(sudo_bits), command)
return command | python | def make_command(
command,
env=None,
su_user=None,
sudo=False,
sudo_user=None,
preserve_sudo_env=False,
):
'''
Builds a shell command with various kwargs.
'''
debug_meta = {}
for key, value in (
('sudo', sudo),
('sudo_user', sudo_user),
('su_user', su_user),
('env', env),
):
if value:
debug_meta[key] = value
logger.debug('Building command ({0}): {1}'.format(' '.join(
'{0}: {1}'.format(key, value)
for key, value in six.iteritems(debug_meta)
), command))
# Use env & build our actual command
if env:
env_string = ' '.join([
'{0}={1}'.format(key, value)
for key, value in six.iteritems(env)
])
command = 'export {0}; {1}'.format(env_string, command)
# Quote the command as a string
command = shlex_quote(command)
# Switch user with su
if su_user:
command = 'su {0} -c {1}'.format(su_user, command)
# Otherwise just sh wrap the command
else:
command = 'sh -c {0}'.format(command)
# Use sudo (w/user?)
if sudo:
sudo_bits = ['sudo', '-H']
if preserve_sudo_env:
sudo_bits.append('-E')
if sudo_user:
sudo_bits.extend(('-u', sudo_user))
command = '{0} {1}'.format(' '.join(sudo_bits), command)
return command | [
"def",
"make_command",
"(",
"command",
",",
"env",
"=",
"None",
",",
"su_user",
"=",
"None",
",",
"sudo",
"=",
"False",
",",
"sudo_user",
"=",
"None",
",",
"preserve_sudo_env",
"=",
"False",
",",
")",
":",
"debug_meta",
"=",
"{",
"}",
"for",
"key",
"... | Builds a shell command with various kwargs. | [
"Builds",
"a",
"shell",
"command",
"with",
"various",
"kwargs",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/util.py#L280-L339 |
24,293 | Fizzadar/pyinfra | pyinfra/api/util.py | make_hash | def make_hash(obj):
'''
Make a hash from an arbitrary nested dictionary, list, tuple or set, used to generate
ID's for operations based on their name & arguments.
'''
if isinstance(obj, (set, tuple, list)):
hash_string = ''.join([make_hash(e) for e in obj])
elif isinstance(obj, dict):
hash_string = ''.join(
''.join((key, make_hash(value)))
for key, value in six.iteritems(obj)
)
else:
hash_string = (
# Constants - the values can change between hosts but we should still
# group them under the same operation hash.
'_PYINFRA_CONSTANT' if obj in (True, False, None)
# Plain strings
else obj if isinstance(obj, six.string_types)
# Objects with __name__s
else obj.__name__ if hasattr(obj, '__name__')
# Objects with names
else obj.name if hasattr(obj, 'name')
# Repr anything else
else repr(obj)
)
return sha1_hash(hash_string) | python | def make_hash(obj):
'''
Make a hash from an arbitrary nested dictionary, list, tuple or set, used to generate
ID's for operations based on their name & arguments.
'''
if isinstance(obj, (set, tuple, list)):
hash_string = ''.join([make_hash(e) for e in obj])
elif isinstance(obj, dict):
hash_string = ''.join(
''.join((key, make_hash(value)))
for key, value in six.iteritems(obj)
)
else:
hash_string = (
# Constants - the values can change between hosts but we should still
# group them under the same operation hash.
'_PYINFRA_CONSTANT' if obj in (True, False, None)
# Plain strings
else obj if isinstance(obj, six.string_types)
# Objects with __name__s
else obj.__name__ if hasattr(obj, '__name__')
# Objects with names
else obj.name if hasattr(obj, 'name')
# Repr anything else
else repr(obj)
)
return sha1_hash(hash_string) | [
"def",
"make_hash",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"set",
",",
"tuple",
",",
"list",
")",
")",
":",
"hash_string",
"=",
"''",
".",
"join",
"(",
"[",
"make_hash",
"(",
"e",
")",
"for",
"e",
"in",
"obj",
"]",
")",... | Make a hash from an arbitrary nested dictionary, list, tuple or set, used to generate
ID's for operations based on their name & arguments. | [
"Make",
"a",
"hash",
"from",
"an",
"arbitrary",
"nested",
"dictionary",
"list",
"tuple",
"or",
"set",
"used",
"to",
"generate",
"ID",
"s",
"for",
"operations",
"based",
"on",
"their",
"name",
"&",
"arguments",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/util.py#L376-L406 |
24,294 | Fizzadar/pyinfra | pyinfra/api/util.py | get_file_sha1 | def get_file_sha1(filename_or_io):
'''
Calculates the SHA1 of a file or file object using a buffer to handle larger files.
'''
file_data = get_file_io(filename_or_io)
cache_key = file_data.cache_key
if cache_key and cache_key in FILE_SHAS:
return FILE_SHAS[cache_key]
with file_data as file_io:
hasher = sha1()
buff = file_io.read(BLOCKSIZE)
while len(buff) > 0:
if isinstance(buff, six.text_type):
buff = buff.encode('utf-8')
hasher.update(buff)
buff = file_io.read(BLOCKSIZE)
digest = hasher.hexdigest()
if cache_key:
FILE_SHAS[cache_key] = digest
return digest | python | def get_file_sha1(filename_or_io):
'''
Calculates the SHA1 of a file or file object using a buffer to handle larger files.
'''
file_data = get_file_io(filename_or_io)
cache_key = file_data.cache_key
if cache_key and cache_key in FILE_SHAS:
return FILE_SHAS[cache_key]
with file_data as file_io:
hasher = sha1()
buff = file_io.read(BLOCKSIZE)
while len(buff) > 0:
if isinstance(buff, six.text_type):
buff = buff.encode('utf-8')
hasher.update(buff)
buff = file_io.read(BLOCKSIZE)
digest = hasher.hexdigest()
if cache_key:
FILE_SHAS[cache_key] = digest
return digest | [
"def",
"get_file_sha1",
"(",
"filename_or_io",
")",
":",
"file_data",
"=",
"get_file_io",
"(",
"filename_or_io",
")",
"cache_key",
"=",
"file_data",
".",
"cache_key",
"if",
"cache_key",
"and",
"cache_key",
"in",
"FILE_SHAS",
":",
"return",
"FILE_SHAS",
"[",
"cac... | Calculates the SHA1 of a file or file object using a buffer to handle larger files. | [
"Calculates",
"the",
"SHA1",
"of",
"a",
"file",
"or",
"file",
"object",
"using",
"a",
"buffer",
"to",
"handle",
"larger",
"files",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/util.py#L459-L486 |
24,295 | Fizzadar/pyinfra | pyinfra/api/util.py | read_buffer | def read_buffer(io, print_output=False, print_func=None):
'''
Reads a file-like buffer object into lines and optionally prints the output.
'''
# TODO: research this further - some steps towards handling stdin (ie password requests
# from programs that don't notice there's no TTY to accept passwords from!). This just
# prints output as below, but stores partial lines in a buffer, which could be printed
# when ready to accept input. Or detected and raise an error.
# GitHub issue: https://github.com/Fizzadar/pyinfra/issues/40
# buff = ''
# data = io.read(1)
# while data:
# # Append to the buffer
# buff += data
# # Newlines in the buffer? Break them out
# if '\n' in buff:
# lines = buff.split('\n')
# # Set the buffer back to just the last line
# buff = lines[-1]
# # Get the other lines, strip them
# lines = [
# line.strip()
# for line in lines[:-1]
# ]
# out.extend(lines)
# for line in lines:
# _print(line)
# # Get next data
# data = io.read(1)
# if buff:
# line = buff.strip()
# out.append(line)
# _print(line)
def _print(line):
if print_output:
if print_func:
formatted_line = print_func(line)
else:
formatted_line = line
encoded_line = unicode(formatted_line).encode('utf-8')
print(encoded_line)
out = []
for line in io:
# Handle local Popen shells returning list of bytes, not strings
if not isinstance(line, six.text_type):
line = line.decode('utf-8')
line = line.strip()
out.append(line)
_print(line)
return out | python | def read_buffer(io, print_output=False, print_func=None):
'''
Reads a file-like buffer object into lines and optionally prints the output.
'''
# TODO: research this further - some steps towards handling stdin (ie password requests
# from programs that don't notice there's no TTY to accept passwords from!). This just
# prints output as below, but stores partial lines in a buffer, which could be printed
# when ready to accept input. Or detected and raise an error.
# GitHub issue: https://github.com/Fizzadar/pyinfra/issues/40
# buff = ''
# data = io.read(1)
# while data:
# # Append to the buffer
# buff += data
# # Newlines in the buffer? Break them out
# if '\n' in buff:
# lines = buff.split('\n')
# # Set the buffer back to just the last line
# buff = lines[-1]
# # Get the other lines, strip them
# lines = [
# line.strip()
# for line in lines[:-1]
# ]
# out.extend(lines)
# for line in lines:
# _print(line)
# # Get next data
# data = io.read(1)
# if buff:
# line = buff.strip()
# out.append(line)
# _print(line)
def _print(line):
if print_output:
if print_func:
formatted_line = print_func(line)
else:
formatted_line = line
encoded_line = unicode(formatted_line).encode('utf-8')
print(encoded_line)
out = []
for line in io:
# Handle local Popen shells returning list of bytes, not strings
if not isinstance(line, six.text_type):
line = line.decode('utf-8')
line = line.strip()
out.append(line)
_print(line)
return out | [
"def",
"read_buffer",
"(",
"io",
",",
"print_output",
"=",
"False",
",",
"print_func",
"=",
"None",
")",
":",
"# TODO: research this further - some steps towards handling stdin (ie password requests",
"# from programs that don't notice there's no TTY to accept passwords from!). This ju... | Reads a file-like buffer object into lines and optionally prints the output. | [
"Reads",
"a",
"file",
"-",
"like",
"buffer",
"object",
"into",
"lines",
"and",
"optionally",
"prints",
"the",
"output",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/util.py#L489-L555 |
24,296 | Fizzadar/pyinfra | pyinfra/modules/vzctl.py | start | def start(state, host, ctid, force=False):
'''
Start OpenVZ containers.
+ ctid: CTID of the container to start
+ force: whether to force container start
'''
args = ['{0}'.format(ctid)]
if force:
args.append('--force')
yield 'vzctl start {0}'.format(' '.join(args)) | python | def start(state, host, ctid, force=False):
'''
Start OpenVZ containers.
+ ctid: CTID of the container to start
+ force: whether to force container start
'''
args = ['{0}'.format(ctid)]
if force:
args.append('--force')
yield 'vzctl start {0}'.format(' '.join(args)) | [
"def",
"start",
"(",
"state",
",",
"host",
",",
"ctid",
",",
"force",
"=",
"False",
")",
":",
"args",
"=",
"[",
"'{0}'",
".",
"format",
"(",
"ctid",
")",
"]",
"if",
"force",
":",
"args",
".",
"append",
"(",
"'--force'",
")",
"yield",
"'vzctl start ... | Start OpenVZ containers.
+ ctid: CTID of the container to start
+ force: whether to force container start | [
"Start",
"OpenVZ",
"containers",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/vzctl.py#L15-L28 |
24,297 | Fizzadar/pyinfra | pyinfra/modules/vzctl.py | stop | def stop(state, host, ctid):
'''
Stop OpenVZ containers.
+ ctid: CTID of the container to stop
'''
args = ['{0}'.format(ctid)]
yield 'vzctl stop {0}'.format(' '.join(args)) | python | def stop(state, host, ctid):
'''
Stop OpenVZ containers.
+ ctid: CTID of the container to stop
'''
args = ['{0}'.format(ctid)]
yield 'vzctl stop {0}'.format(' '.join(args)) | [
"def",
"stop",
"(",
"state",
",",
"host",
",",
"ctid",
")",
":",
"args",
"=",
"[",
"'{0}'",
".",
"format",
"(",
"ctid",
")",
"]",
"yield",
"'vzctl stop {0}'",
".",
"format",
"(",
"' '",
".",
"join",
"(",
"args",
")",
")"
] | Stop OpenVZ containers.
+ ctid: CTID of the container to stop | [
"Stop",
"OpenVZ",
"containers",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/vzctl.py#L32-L41 |
24,298 | Fizzadar/pyinfra | pyinfra/modules/vzctl.py | restart | def restart(state, host, ctid, force=False):
'''
Restart OpenVZ containers.
+ ctid: CTID of the container to restart
+ force: whether to force container start
'''
yield stop(state, host, ctid)
yield start(state, host, ctid, force=force) | python | def restart(state, host, ctid, force=False):
'''
Restart OpenVZ containers.
+ ctid: CTID of the container to restart
+ force: whether to force container start
'''
yield stop(state, host, ctid)
yield start(state, host, ctid, force=force) | [
"def",
"restart",
"(",
"state",
",",
"host",
",",
"ctid",
",",
"force",
"=",
"False",
")",
":",
"yield",
"stop",
"(",
"state",
",",
"host",
",",
"ctid",
")",
"yield",
"start",
"(",
"state",
",",
"host",
",",
"ctid",
",",
"force",
"=",
"force",
")... | Restart OpenVZ containers.
+ ctid: CTID of the container to restart
+ force: whether to force container start | [
"Restart",
"OpenVZ",
"containers",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/vzctl.py#L45-L54 |
24,299 | Fizzadar/pyinfra | pyinfra/modules/vzctl.py | create | def create(state, host, ctid, template=None):
'''
Create OpenVZ containers.
+ ctid: CTID of the container to create
'''
# Check we don't already have a container with this CTID
current_containers = host.fact.openvz_containers
if ctid in current_containers:
raise OperationError(
'An OpenVZ container with CTID {0} already exists'.format(ctid),
)
args = ['{0}'.format(ctid)]
if template:
args.append('--ostemplate {0}'.format(template))
yield 'vzctl create {0}'.format(' '.join(args)) | python | def create(state, host, ctid, template=None):
'''
Create OpenVZ containers.
+ ctid: CTID of the container to create
'''
# Check we don't already have a container with this CTID
current_containers = host.fact.openvz_containers
if ctid in current_containers:
raise OperationError(
'An OpenVZ container with CTID {0} already exists'.format(ctid),
)
args = ['{0}'.format(ctid)]
if template:
args.append('--ostemplate {0}'.format(template))
yield 'vzctl create {0}'.format(' '.join(args)) | [
"def",
"create",
"(",
"state",
",",
"host",
",",
"ctid",
",",
"template",
"=",
"None",
")",
":",
"# Check we don't already have a container with this CTID",
"current_containers",
"=",
"host",
".",
"fact",
".",
"openvz_containers",
"if",
"ctid",
"in",
"current_contai... | Create OpenVZ containers.
+ ctid: CTID of the container to create | [
"Create",
"OpenVZ",
"containers",
"."
] | 006f751f7db2e07d32522c0285160783de2feb79 | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/vzctl.py#L91-L110 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.