id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
8,400
ianmiell/shutit
shutit_class.py
ShutIt.login
def login(self, command='su -', user=None, password=None, prompt_prefix=None, expect=None, timeout=shutit_global.shutit_global_object.default_timeout, escape=False, echo=None, note=None, go_home=True, fail_on_fail=True, is_ssh=True, check_sudo=True, loglevel=logging.DEBUG): """Logs user in on default child. """ shutit_global.shutit_global_object.yield_to_draw() shutit_pexpect_session = self.get_current_shutit_pexpect_session() return shutit_pexpect_session.login(ShutItSendSpec(shutit_pexpect_session, user=user, send=command, password=password, prompt_prefix=prompt_prefix, expect=expect, timeout=timeout, escape=escape, echo=echo, note=note, go_home=go_home, fail_on_fail=fail_on_fail, is_ssh=is_ssh, check_sudo=check_sudo, loglevel=loglevel))
python
def login(self, command='su -', user=None, password=None, prompt_prefix=None, expect=None, timeout=shutit_global.shutit_global_object.default_timeout, escape=False, echo=None, note=None, go_home=True, fail_on_fail=True, is_ssh=True, check_sudo=True, loglevel=logging.DEBUG): """Logs user in on default child. """ shutit_global.shutit_global_object.yield_to_draw() shutit_pexpect_session = self.get_current_shutit_pexpect_session() return shutit_pexpect_session.login(ShutItSendSpec(shutit_pexpect_session, user=user, send=command, password=password, prompt_prefix=prompt_prefix, expect=expect, timeout=timeout, escape=escape, echo=echo, note=note, go_home=go_home, fail_on_fail=fail_on_fail, is_ssh=is_ssh, check_sudo=check_sudo, loglevel=loglevel))
[ "def", "login", "(", "self", ",", "command", "=", "'su -'", ",", "user", "=", "None", ",", "password", "=", "None", ",", "prompt_prefix", "=", "None", ",", "expect", "=", "None", ",", "timeout", "=", "shutit_global", ".", "shutit_global_object", ".", "default_timeout", ",", "escape", "=", "False", ",", "echo", "=", "None", ",", "note", "=", "None", ",", "go_home", "=", "True", ",", "fail_on_fail", "=", "True", ",", "is_ssh", "=", "True", ",", "check_sudo", "=", "True", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "shutit_pexpect_session", "=", "self", ".", "get_current_shutit_pexpect_session", "(", ")", "return", "shutit_pexpect_session", ".", "login", "(", "ShutItSendSpec", "(", "shutit_pexpect_session", ",", "user", "=", "user", ",", "send", "=", "command", ",", "password", "=", "password", ",", "prompt_prefix", "=", "prompt_prefix", ",", "expect", "=", "expect", ",", "timeout", "=", "timeout", ",", "escape", "=", "escape", ",", "echo", "=", "echo", ",", "note", "=", "note", ",", "go_home", "=", "go_home", ",", "fail_on_fail", "=", "fail_on_fail", ",", "is_ssh", "=", "is_ssh", ",", "check_sudo", "=", "check_sudo", ",", "loglevel", "=", "loglevel", ")", ")" ]
Logs user in on default child.
[ "Logs", "user", "in", "on", "default", "child", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2105-L2138
8,401
ianmiell/shutit
shutit_class.py
ShutIt.logout_all
def logout_all(self, command='exit', note=None, echo=None, timeout=shutit_global.shutit_global_object.default_timeout, nonewline=False, loglevel=logging.DEBUG): """Logs the user out of all pexpect sessions within this ShutIt object. @param command: Command to run to log out (default=exit) @param note: See send() """ shutit_global.shutit_global_object.yield_to_draw() for key in self.shutit_pexpect_sessions: shutit_pexpect_session = self.shutit_pexpect_sessions[key] shutit_pexpect_session.logout_all(ShutItSendSpec(shutit_pexpect_session, send=command, note=note, timeout=timeout, nonewline=nonewline, loglevel=loglevel, echo=echo)) return True
python
def logout_all(self, command='exit', note=None, echo=None, timeout=shutit_global.shutit_global_object.default_timeout, nonewline=False, loglevel=logging.DEBUG): """Logs the user out of all pexpect sessions within this ShutIt object. @param command: Command to run to log out (default=exit) @param note: See send() """ shutit_global.shutit_global_object.yield_to_draw() for key in self.shutit_pexpect_sessions: shutit_pexpect_session = self.shutit_pexpect_sessions[key] shutit_pexpect_session.logout_all(ShutItSendSpec(shutit_pexpect_session, send=command, note=note, timeout=timeout, nonewline=nonewline, loglevel=loglevel, echo=echo)) return True
[ "def", "logout_all", "(", "self", ",", "command", "=", "'exit'", ",", "note", "=", "None", ",", "echo", "=", "None", ",", "timeout", "=", "shutit_global", ".", "shutit_global_object", ".", "default_timeout", ",", "nonewline", "=", "False", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "for", "key", "in", "self", ".", "shutit_pexpect_sessions", ":", "shutit_pexpect_session", "=", "self", ".", "shutit_pexpect_sessions", "[", "key", "]", "shutit_pexpect_session", ".", "logout_all", "(", "ShutItSendSpec", "(", "shutit_pexpect_session", ",", "send", "=", "command", ",", "note", "=", "note", ",", "timeout", "=", "timeout", ",", "nonewline", "=", "nonewline", ",", "loglevel", "=", "loglevel", ",", "echo", "=", "echo", ")", ")", "return", "True" ]
Logs the user out of all pexpect sessions within this ShutIt object. @param command: Command to run to log out (default=exit) @param note: See send()
[ "Logs", "the", "user", "out", "of", "all", "pexpect", "sessions", "within", "this", "ShutIt", "object", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2141-L2163
8,402
ianmiell/shutit
shutit_class.py
ShutIt.push_repository
def push_repository(self, repository, docker_executable='docker', shutit_pexpect_child=None, expect=None, note=None, loglevel=logging.INFO): """Pushes the repository. @param repository: Repository to push. @param docker_executable: Defaults to 'docker' @param expect: See send() @param shutit_pexpect_child: See send() @type repository: string @type docker_executable: string """ shutit_global.shutit_global_object.yield_to_draw() self.handle_note(note) shutit_pexpect_child = shutit_pexpect_child or self.get_shutit_pexpect_session_from_id('host_child').pexpect_child expect = expect or self.expect_prompts['ORIGIN_ENV'] send = docker_executable + ' push ' + self.repository['user'] + '/' + repository timeout = 99999 self.log('Running: ' + send,level=logging.INFO) self.multisend(docker_executable + ' login', {'Username':self.repository['user'], 'Password':self.repository['password'], 'Email':self.repository['email']}, shutit_pexpect_child=shutit_pexpect_child, expect=expect) self.send(send, shutit_pexpect_child=shutit_pexpect_child, expect=expect, timeout=timeout, check_exit=False, fail_on_empty_before=False, loglevel=loglevel) self.handle_note_after(note) return True
python
def push_repository(self, repository, docker_executable='docker', shutit_pexpect_child=None, expect=None, note=None, loglevel=logging.INFO): """Pushes the repository. @param repository: Repository to push. @param docker_executable: Defaults to 'docker' @param expect: See send() @param shutit_pexpect_child: See send() @type repository: string @type docker_executable: string """ shutit_global.shutit_global_object.yield_to_draw() self.handle_note(note) shutit_pexpect_child = shutit_pexpect_child or self.get_shutit_pexpect_session_from_id('host_child').pexpect_child expect = expect or self.expect_prompts['ORIGIN_ENV'] send = docker_executable + ' push ' + self.repository['user'] + '/' + repository timeout = 99999 self.log('Running: ' + send,level=logging.INFO) self.multisend(docker_executable + ' login', {'Username':self.repository['user'], 'Password':self.repository['password'], 'Email':self.repository['email']}, shutit_pexpect_child=shutit_pexpect_child, expect=expect) self.send(send, shutit_pexpect_child=shutit_pexpect_child, expect=expect, timeout=timeout, check_exit=False, fail_on_empty_before=False, loglevel=loglevel) self.handle_note_after(note) return True
[ "def", "push_repository", "(", "self", ",", "repository", ",", "docker_executable", "=", "'docker'", ",", "shutit_pexpect_child", "=", "None", ",", "expect", "=", "None", ",", "note", "=", "None", ",", "loglevel", "=", "logging", ".", "INFO", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "self", ".", "handle_note", "(", "note", ")", "shutit_pexpect_child", "=", "shutit_pexpect_child", "or", "self", ".", "get_shutit_pexpect_session_from_id", "(", "'host_child'", ")", ".", "pexpect_child", "expect", "=", "expect", "or", "self", ".", "expect_prompts", "[", "'ORIGIN_ENV'", "]", "send", "=", "docker_executable", "+", "' push '", "+", "self", ".", "repository", "[", "'user'", "]", "+", "'/'", "+", "repository", "timeout", "=", "99999", "self", ".", "log", "(", "'Running: '", "+", "send", ",", "level", "=", "logging", ".", "INFO", ")", "self", ".", "multisend", "(", "docker_executable", "+", "' login'", ",", "{", "'Username'", ":", "self", ".", "repository", "[", "'user'", "]", ",", "'Password'", ":", "self", ".", "repository", "[", "'password'", "]", ",", "'Email'", ":", "self", ".", "repository", "[", "'email'", "]", "}", ",", "shutit_pexpect_child", "=", "shutit_pexpect_child", ",", "expect", "=", "expect", ")", "self", ".", "send", "(", "send", ",", "shutit_pexpect_child", "=", "shutit_pexpect_child", ",", "expect", "=", "expect", ",", "timeout", "=", "timeout", ",", "check_exit", "=", "False", ",", "fail_on_empty_before", "=", "False", ",", "loglevel", "=", "loglevel", ")", "self", ".", "handle_note_after", "(", "note", ")", "return", "True" ]
Pushes the repository. @param repository: Repository to push. @param docker_executable: Defaults to 'docker' @param expect: See send() @param shutit_pexpect_child: See send() @type repository: string @type docker_executable: string
[ "Pushes", "the", "repository", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2301-L2337
8,403
ianmiell/shutit
shutit_class.py
ShutIt.get_emailer
def get_emailer(self, cfg_section): """Sends an email using the mailer """ shutit_global.shutit_global_object.yield_to_draw() import emailer return emailer.Emailer(cfg_section, self)
python
def get_emailer(self, cfg_section): """Sends an email using the mailer """ shutit_global.shutit_global_object.yield_to_draw() import emailer return emailer.Emailer(cfg_section, self)
[ "def", "get_emailer", "(", "self", ",", "cfg_section", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "import", "emailer", "return", "emailer", ".", "Emailer", "(", "cfg_section", ",", "self", ")" ]
Sends an email using the mailer
[ "Sends", "an", "email", "using", "the", "mailer" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2617-L2622
8,404
ianmiell/shutit
shutit_class.py
ShutIt.get_shutit_pexpect_session_id
def get_shutit_pexpect_session_id(self, shutit_pexpect_child): """Given a pexpect child object, return the shutit_pexpect_session_id object. """ shutit_global.shutit_global_object.yield_to_draw() if not isinstance(shutit_pexpect_child, pexpect.pty_spawn.spawn): self.fail('Wrong type in get_shutit_pexpect_session_id',throw_exception=True) # pragma: no cover for key in self.shutit_pexpect_sessions: if self.shutit_pexpect_sessions[key].pexpect_child == shutit_pexpect_child: return key return self.fail('Should not get here in get_shutit_pexpect_session_id',throw_exception=True)
python
def get_shutit_pexpect_session_id(self, shutit_pexpect_child): """Given a pexpect child object, return the shutit_pexpect_session_id object. """ shutit_global.shutit_global_object.yield_to_draw() if not isinstance(shutit_pexpect_child, pexpect.pty_spawn.spawn): self.fail('Wrong type in get_shutit_pexpect_session_id',throw_exception=True) # pragma: no cover for key in self.shutit_pexpect_sessions: if self.shutit_pexpect_sessions[key].pexpect_child == shutit_pexpect_child: return key return self.fail('Should not get here in get_shutit_pexpect_session_id',throw_exception=True)
[ "def", "get_shutit_pexpect_session_id", "(", "self", ",", "shutit_pexpect_child", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "if", "not", "isinstance", "(", "shutit_pexpect_child", ",", "pexpect", ".", "pty_spawn", ".", "spawn", ")", ":", "self", ".", "fail", "(", "'Wrong type in get_shutit_pexpect_session_id'", ",", "throw_exception", "=", "True", ")", "# pragma: no cover", "for", "key", "in", "self", ".", "shutit_pexpect_sessions", ":", "if", "self", ".", "shutit_pexpect_sessions", "[", "key", "]", ".", "pexpect_child", "==", "shutit_pexpect_child", ":", "return", "key", "return", "self", ".", "fail", "(", "'Should not get here in get_shutit_pexpect_session_id'", ",", "throw_exception", "=", "True", ")" ]
Given a pexpect child object, return the shutit_pexpect_session_id object.
[ "Given", "a", "pexpect", "child", "object", "return", "the", "shutit_pexpect_session_id", "object", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2645-L2654
8,405
ianmiell/shutit
shutit_class.py
ShutIt.get_shutit_pexpect_session_from_id
def get_shutit_pexpect_session_from_id(self, shutit_pexpect_id): """Get the pexpect session from the given identifier. """ shutit_global.shutit_global_object.yield_to_draw() for key in self.shutit_pexpect_sessions: if self.shutit_pexpect_sessions[key].pexpect_session_id == shutit_pexpect_id: return self.shutit_pexpect_sessions[key] return self.fail('Should not get here in get_shutit_pexpect_session_from_id',throw_exception=True)
python
def get_shutit_pexpect_session_from_id(self, shutit_pexpect_id): """Get the pexpect session from the given identifier. """ shutit_global.shutit_global_object.yield_to_draw() for key in self.shutit_pexpect_sessions: if self.shutit_pexpect_sessions[key].pexpect_session_id == shutit_pexpect_id: return self.shutit_pexpect_sessions[key] return self.fail('Should not get here in get_shutit_pexpect_session_from_id',throw_exception=True)
[ "def", "get_shutit_pexpect_session_from_id", "(", "self", ",", "shutit_pexpect_id", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "for", "key", "in", "self", ".", "shutit_pexpect_sessions", ":", "if", "self", ".", "shutit_pexpect_sessions", "[", "key", "]", ".", "pexpect_session_id", "==", "shutit_pexpect_id", ":", "return", "self", ".", "shutit_pexpect_sessions", "[", "key", "]", "return", "self", ".", "fail", "(", "'Should not get here in get_shutit_pexpect_session_from_id'", ",", "throw_exception", "=", "True", ")" ]
Get the pexpect session from the given identifier.
[ "Get", "the", "pexpect", "session", "from", "the", "given", "identifier", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2657-L2664
8,406
ianmiell/shutit
shutit_class.py
ShutIt.get_commands
def get_commands(self): """Gets command that have been run and have not been redacted. """ shutit_global.shutit_global_object.yield_to_draw() s = '' for c in self.build['shutit_command_history']: if isinstance(c, str): #Ignore commands with leading spaces if c and c[0] != ' ': s += c + '\n' return s
python
def get_commands(self): """Gets command that have been run and have not been redacted. """ shutit_global.shutit_global_object.yield_to_draw() s = '' for c in self.build['shutit_command_history']: if isinstance(c, str): #Ignore commands with leading spaces if c and c[0] != ' ': s += c + '\n' return s
[ "def", "get_commands", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "s", "=", "''", "for", "c", "in", "self", ".", "build", "[", "'shutit_command_history'", "]", ":", "if", "isinstance", "(", "c", ",", "str", ")", ":", "#Ignore commands with leading spaces", "if", "c", "and", "c", "[", "0", "]", "!=", "' '", ":", "s", "+=", "c", "+", "'\\n'", "return", "s" ]
Gets command that have been run and have not been redacted.
[ "Gets", "command", "that", "have", "been", "run", "and", "have", "not", "been", "redacted", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2722-L2732
8,407
ianmiell/shutit
shutit_class.py
ShutIt.build_report
def build_report(self, msg=''): """Resposible for constructing a report to be output as part of the build. Returns report as a string. """ shutit_global.shutit_global_object.yield_to_draw() s = '\n' s += '################################################################################\n' s += '# COMMAND HISTORY BEGIN ' + shutit_global.shutit_global_object.build_id + '\n' s += self.get_commands() s += '# COMMAND HISTORY END ' + shutit_global.shutit_global_object.build_id + '\n' s += '################################################################################\n' s += '################################################################################\n' s += '# BUILD REPORT FOR BUILD BEGIN ' + shutit_global.shutit_global_object.build_id + '\n' s += '# ' + msg + '\n' if self.build['report'] != '': s += self.build['report'] + '\n' else: s += '# Nothing to report\n' if 'container_id' in self.target: s += '# CONTAINER_ID: ' + self.target['container_id'] + '\n' s += '# BUILD REPORT FOR BUILD END ' + shutit_global.shutit_global_object.build_id + '\n' s += '###############################################################################\n' s += '# INVOKING COMMAND WAS: ' + sys.executable for arg in sys.argv: s += ' ' + arg s += '\n' s += '###############################################################################\n' return s
python
def build_report(self, msg=''): """Resposible for constructing a report to be output as part of the build. Returns report as a string. """ shutit_global.shutit_global_object.yield_to_draw() s = '\n' s += '################################################################################\n' s += '# COMMAND HISTORY BEGIN ' + shutit_global.shutit_global_object.build_id + '\n' s += self.get_commands() s += '# COMMAND HISTORY END ' + shutit_global.shutit_global_object.build_id + '\n' s += '################################################################################\n' s += '################################################################################\n' s += '# BUILD REPORT FOR BUILD BEGIN ' + shutit_global.shutit_global_object.build_id + '\n' s += '# ' + msg + '\n' if self.build['report'] != '': s += self.build['report'] + '\n' else: s += '# Nothing to report\n' if 'container_id' in self.target: s += '# CONTAINER_ID: ' + self.target['container_id'] + '\n' s += '# BUILD REPORT FOR BUILD END ' + shutit_global.shutit_global_object.build_id + '\n' s += '###############################################################################\n' s += '# INVOKING COMMAND WAS: ' + sys.executable for arg in sys.argv: s += ' ' + arg s += '\n' s += '###############################################################################\n' return s
[ "def", "build_report", "(", "self", ",", "msg", "=", "''", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "s", "=", "'\\n'", "s", "+=", "'################################################################################\\n'", "s", "+=", "'# COMMAND HISTORY BEGIN '", "+", "shutit_global", ".", "shutit_global_object", ".", "build_id", "+", "'\\n'", "s", "+=", "self", ".", "get_commands", "(", ")", "s", "+=", "'# COMMAND HISTORY END '", "+", "shutit_global", ".", "shutit_global_object", ".", "build_id", "+", "'\\n'", "s", "+=", "'################################################################################\\n'", "s", "+=", "'################################################################################\\n'", "s", "+=", "'# BUILD REPORT FOR BUILD BEGIN '", "+", "shutit_global", ".", "shutit_global_object", ".", "build_id", "+", "'\\n'", "s", "+=", "'# '", "+", "msg", "+", "'\\n'", "if", "self", ".", "build", "[", "'report'", "]", "!=", "''", ":", "s", "+=", "self", ".", "build", "[", "'report'", "]", "+", "'\\n'", "else", ":", "s", "+=", "'# Nothing to report\\n'", "if", "'container_id'", "in", "self", ".", "target", ":", "s", "+=", "'# CONTAINER_ID: '", "+", "self", ".", "target", "[", "'container_id'", "]", "+", "'\\n'", "s", "+=", "'# BUILD REPORT FOR BUILD END '", "+", "shutit_global", ".", "shutit_global_object", ".", "build_id", "+", "'\\n'", "s", "+=", "'###############################################################################\\n'", "s", "+=", "'# INVOKING COMMAND WAS: '", "+", "sys", ".", "executable", "for", "arg", "in", "sys", ".", "argv", ":", "s", "+=", "' '", "+", "arg", "s", "+=", "'\\n'", "s", "+=", "'###############################################################################\\n'", "return", "s" ]
Resposible for constructing a report to be output as part of the build. Returns report as a string.
[ "Resposible", "for", "constructing", "a", "report", "to", "be", "output", "as", "part", "of", "the", "build", ".", "Returns", "report", "as", "a", "string", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2736-L2763
8,408
ianmiell/shutit
shutit_class.py
ShutIt.match_string
def match_string(self, string_to_match, regexp): """Get regular expression from the first of the lines passed in in string that matched. Handles first group of regexp as a return value. @param string_to_match: String to match on @param regexp: Regexp to check (per-line) against string @type string_to_match: string @type regexp: string Returns None if none of the lines matched. Returns True if there are no groups selected in the regexp. else returns matching group (ie non-None) """ shutit_global.shutit_global_object.yield_to_draw() if not isinstance(string_to_match, str): return None lines = string_to_match.split('\r\n') # sometimes they're separated by just a carriage return... new_lines = [] for line in lines: new_lines = new_lines + line.split('\r') # and sometimes they're separated by just a newline... for line in lines: new_lines = new_lines + line.split('\n') lines = new_lines if not shutit_util.check_regexp(regexp): self.fail('Illegal regexp found in match_string call: ' + regexp) # pragma: no cover for line in lines: match = re.match(regexp, line) if match is not None: if match.groups(): return match.group(1) return True return None
python
def match_string(self, string_to_match, regexp): """Get regular expression from the first of the lines passed in in string that matched. Handles first group of regexp as a return value. @param string_to_match: String to match on @param regexp: Regexp to check (per-line) against string @type string_to_match: string @type regexp: string Returns None if none of the lines matched. Returns True if there are no groups selected in the regexp. else returns matching group (ie non-None) """ shutit_global.shutit_global_object.yield_to_draw() if not isinstance(string_to_match, str): return None lines = string_to_match.split('\r\n') # sometimes they're separated by just a carriage return... new_lines = [] for line in lines: new_lines = new_lines + line.split('\r') # and sometimes they're separated by just a newline... for line in lines: new_lines = new_lines + line.split('\n') lines = new_lines if not shutit_util.check_regexp(regexp): self.fail('Illegal regexp found in match_string call: ' + regexp) # pragma: no cover for line in lines: match = re.match(regexp, line) if match is not None: if match.groups(): return match.group(1) return True return None
[ "def", "match_string", "(", "self", ",", "string_to_match", ",", "regexp", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "if", "not", "isinstance", "(", "string_to_match", ",", "str", ")", ":", "return", "None", "lines", "=", "string_to_match", ".", "split", "(", "'\\r\\n'", ")", "# sometimes they're separated by just a carriage return...", "new_lines", "=", "[", "]", "for", "line", "in", "lines", ":", "new_lines", "=", "new_lines", "+", "line", ".", "split", "(", "'\\r'", ")", "# and sometimes they're separated by just a newline...", "for", "line", "in", "lines", ":", "new_lines", "=", "new_lines", "+", "line", ".", "split", "(", "'\\n'", ")", "lines", "=", "new_lines", "if", "not", "shutit_util", ".", "check_regexp", "(", "regexp", ")", ":", "self", ".", "fail", "(", "'Illegal regexp found in match_string call: '", "+", "regexp", ")", "# pragma: no cover", "for", "line", "in", "lines", ":", "match", "=", "re", ".", "match", "(", "regexp", ",", "line", ")", "if", "match", "is", "not", "None", ":", "if", "match", ".", "groups", "(", ")", ":", "return", "match", ".", "group", "(", "1", ")", "return", "True", "return", "None" ]
Get regular expression from the first of the lines passed in in string that matched. Handles first group of regexp as a return value. @param string_to_match: String to match on @param regexp: Regexp to check (per-line) against string @type string_to_match: string @type regexp: string Returns None if none of the lines matched. Returns True if there are no groups selected in the regexp. else returns matching group (ie non-None)
[ "Get", "regular", "expression", "from", "the", "first", "of", "the", "lines", "passed", "in", "in", "string", "that", "matched", ".", "Handles", "first", "group", "of", "regexp", "as", "a", "return", "value", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2766-L2802
8,409
ianmiell/shutit
shutit_class.py
ShutIt.is_to_be_built_or_is_installed
def is_to_be_built_or_is_installed(self, shutit_module_obj): """Returns true if this module is configured to be built, or if it is already installed. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg if cfg[shutit_module_obj.module_id]['shutit.core.module.build']: return True return self.is_installed(shutit_module_obj)
python
def is_to_be_built_or_is_installed(self, shutit_module_obj): """Returns true if this module is configured to be built, or if it is already installed. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg if cfg[shutit_module_obj.module_id]['shutit.core.module.build']: return True return self.is_installed(shutit_module_obj)
[ "def", "is_to_be_built_or_is_installed", "(", "self", ",", "shutit_module_obj", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfg", "=", "self", ".", "cfg", "if", "cfg", "[", "shutit_module_obj", ".", "module_id", "]", "[", "'shutit.core.module.build'", "]", ":", "return", "True", "return", "self", ".", "is_installed", "(", "shutit_module_obj", ")" ]
Returns true if this module is configured to be built, or if it is already installed.
[ "Returns", "true", "if", "this", "module", "is", "configured", "to", "be", "built", "or", "if", "it", "is", "already", "installed", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2816-L2823
8,410
ianmiell/shutit
shutit_class.py
ShutIt.is_installed
def is_installed(self, shutit_module_obj): """Returns true if this module is installed. Uses cache where possible. """ shutit_global.shutit_global_object.yield_to_draw() # Cache first if shutit_module_obj.module_id in self.get_current_shutit_pexpect_session_environment().modules_installed: return True if shutit_module_obj.module_id in self.get_current_shutit_pexpect_session_environment().modules_not_installed: return False # Is it installed? if shutit_module_obj.is_installed(self): self.get_current_shutit_pexpect_session_environment().modules_installed.append(shutit_module_obj.module_id) return True # If not installed, and not in cache, add it. else: if shutit_module_obj.module_id not in self.get_current_shutit_pexpect_session_environment().modules_not_installed: self.get_current_shutit_pexpect_session_environment().modules_not_installed.append(shutit_module_obj.module_id) return False return False
python
def is_installed(self, shutit_module_obj): """Returns true if this module is installed. Uses cache where possible. """ shutit_global.shutit_global_object.yield_to_draw() # Cache first if shutit_module_obj.module_id in self.get_current_shutit_pexpect_session_environment().modules_installed: return True if shutit_module_obj.module_id in self.get_current_shutit_pexpect_session_environment().modules_not_installed: return False # Is it installed? if shutit_module_obj.is_installed(self): self.get_current_shutit_pexpect_session_environment().modules_installed.append(shutit_module_obj.module_id) return True # If not installed, and not in cache, add it. else: if shutit_module_obj.module_id not in self.get_current_shutit_pexpect_session_environment().modules_not_installed: self.get_current_shutit_pexpect_session_environment().modules_not_installed.append(shutit_module_obj.module_id) return False return False
[ "def", "is_installed", "(", "self", ",", "shutit_module_obj", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "# Cache first", "if", "shutit_module_obj", ".", "module_id", "in", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "modules_installed", ":", "return", "True", "if", "shutit_module_obj", ".", "module_id", "in", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "modules_not_installed", ":", "return", "False", "# Is it installed?", "if", "shutit_module_obj", ".", "is_installed", "(", "self", ")", ":", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "modules_installed", ".", "append", "(", "shutit_module_obj", ".", "module_id", ")", "return", "True", "# If not installed, and not in cache, add it.", "else", ":", "if", "shutit_module_obj", ".", "module_id", "not", "in", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "modules_not_installed", ":", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "modules_not_installed", ".", "append", "(", "shutit_module_obj", ".", "module_id", ")", "return", "False", "return", "False" ]
Returns true if this module is installed. Uses cache where possible.
[ "Returns", "true", "if", "this", "module", "is", "installed", ".", "Uses", "cache", "where", "possible", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2826-L2845
8,411
ianmiell/shutit
shutit_class.py
ShutIt.allowed_image
def allowed_image(self, module_id): """Given a module id, determine whether the image is allowed to be built. """ shutit_global.shutit_global_object.yield_to_draw() self.log("In allowed_image: " + module_id,level=logging.DEBUG) cfg = self.cfg if self.build['ignoreimage']: self.log("ignoreimage == true, returning true" + module_id,level=logging.DEBUG) return True self.log(str(cfg[module_id]['shutit.core.module.allowed_images']),level=logging.DEBUG) if cfg[module_id]['shutit.core.module.allowed_images']: # Try allowed images as regexps for regexp in cfg[module_id]['shutit.core.module.allowed_images']: if not shutit_util.check_regexp(regexp): self.fail('Illegal regexp found in allowed_images: ' + regexp) # pragma: no cover if re.match('^' + regexp + '$', self.target['docker_image']): return True return False
python
def allowed_image(self, module_id): """Given a module id, determine whether the image is allowed to be built. """ shutit_global.shutit_global_object.yield_to_draw() self.log("In allowed_image: " + module_id,level=logging.DEBUG) cfg = self.cfg if self.build['ignoreimage']: self.log("ignoreimage == true, returning true" + module_id,level=logging.DEBUG) return True self.log(str(cfg[module_id]['shutit.core.module.allowed_images']),level=logging.DEBUG) if cfg[module_id]['shutit.core.module.allowed_images']: # Try allowed images as regexps for regexp in cfg[module_id]['shutit.core.module.allowed_images']: if not shutit_util.check_regexp(regexp): self.fail('Illegal regexp found in allowed_images: ' + regexp) # pragma: no cover if re.match('^' + regexp + '$', self.target['docker_image']): return True return False
[ "def", "allowed_image", "(", "self", ",", "module_id", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "self", ".", "log", "(", "\"In allowed_image: \"", "+", "module_id", ",", "level", "=", "logging", ".", "DEBUG", ")", "cfg", "=", "self", ".", "cfg", "if", "self", ".", "build", "[", "'ignoreimage'", "]", ":", "self", ".", "log", "(", "\"ignoreimage == true, returning true\"", "+", "module_id", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "True", "self", ".", "log", "(", "str", "(", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.allowed_images'", "]", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "if", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.allowed_images'", "]", ":", "# Try allowed images as regexps", "for", "regexp", "in", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.allowed_images'", "]", ":", "if", "not", "shutit_util", ".", "check_regexp", "(", "regexp", ")", ":", "self", ".", "fail", "(", "'Illegal regexp found in allowed_images: '", "+", "regexp", ")", "# pragma: no cover", "if", "re", ".", "match", "(", "'^'", "+", "regexp", "+", "'$'", ",", "self", ".", "target", "[", "'docker_image'", "]", ")", ":", "return", "True", "return", "False" ]
Given a module id, determine whether the image is allowed to be built.
[ "Given", "a", "module", "id", "determine", "whether", "the", "image", "is", "allowed", "to", "be", "built", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2861-L2878
8,412
ianmiell/shutit
shutit_class.py
ShutIt.print_modules
def print_modules(self): """Returns a string table representing the modules in the ShutIt module map. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg module_string = '' module_string += 'Modules: \n' module_string += ' Run order Build Remove Module ID\n' for module_id in self.module_ids(): module_string += ' ' + str(self.shutit_map[module_id].run_order) + ' ' + str( cfg[module_id]['shutit.core.module.build']) + ' ' + str( cfg[module_id]['shutit.core.module.remove']) + ' ' + module_id + '\n' return module_string
python
def print_modules(self): """Returns a string table representing the modules in the ShutIt module map. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg module_string = '' module_string += 'Modules: \n' module_string += ' Run order Build Remove Module ID\n' for module_id in self.module_ids(): module_string += ' ' + str(self.shutit_map[module_id].run_order) + ' ' + str( cfg[module_id]['shutit.core.module.build']) + ' ' + str( cfg[module_id]['shutit.core.module.remove']) + ' ' + module_id + '\n' return module_string
[ "def", "print_modules", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfg", "=", "self", ".", "cfg", "module_string", "=", "''", "module_string", "+=", "'Modules: \\n'", "module_string", "+=", "' Run order Build Remove Module ID\\n'", "for", "module_id", "in", "self", ".", "module_ids", "(", ")", ":", "module_string", "+=", "' '", "+", "str", "(", "self", ".", "shutit_map", "[", "module_id", "]", ".", "run_order", ")", "+", "' '", "+", "str", "(", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.build'", "]", ")", "+", "' '", "+", "str", "(", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.remove'", "]", ")", "+", "' '", "+", "module_id", "+", "'\\n'", "return", "module_string" ]
Returns a string table representing the modules in the ShutIt module map.
[ "Returns", "a", "string", "table", "representing", "the", "modules", "in", "the", "ShutIt", "module", "map", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2881-L2893
8,413
ianmiell/shutit
shutit_class.py
ShutIt.load_shutit_modules
def load_shutit_modules(self): """Responsible for loading the shutit modules based on the configured module paths. """ shutit_global.shutit_global_object.yield_to_draw() if self.loglevel <= logging.DEBUG: self.log('ShutIt module paths now: ',level=logging.DEBUG) self.log(self.host['shutit_module_path'],level=logging.DEBUG) for shutit_module_path in self.host['shutit_module_path']: self.load_all_from_path(shutit_module_path)
python
def load_shutit_modules(self): """Responsible for loading the shutit modules based on the configured module paths. """ shutit_global.shutit_global_object.yield_to_draw() if self.loglevel <= logging.DEBUG: self.log('ShutIt module paths now: ',level=logging.DEBUG) self.log(self.host['shutit_module_path'],level=logging.DEBUG) for shutit_module_path in self.host['shutit_module_path']: self.load_all_from_path(shutit_module_path)
[ "def", "load_shutit_modules", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "if", "self", ".", "loglevel", "<=", "logging", ".", "DEBUG", ":", "self", ".", "log", "(", "'ShutIt module paths now: '", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "log", "(", "self", ".", "host", "[", "'shutit_module_path'", "]", ",", "level", "=", "logging", ".", "DEBUG", ")", "for", "shutit_module_path", "in", "self", ".", "host", "[", "'shutit_module_path'", "]", ":", "self", ".", "load_all_from_path", "(", "shutit_module_path", ")" ]
Responsible for loading the shutit modules based on the configured module paths.
[ "Responsible", "for", "loading", "the", "shutit", "modules", "based", "on", "the", "configured", "module", "paths", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2896-L2905
8,414
ianmiell/shutit
shutit_class.py
ShutIt.get_command
def get_command(self, command): """Helper function for osx - return gnu utils rather than default for eg head and md5sum where possible and needed. """ shutit_global.shutit_global_object.yield_to_draw() if command in ('md5sum','sed','head'): if self.get_current_shutit_pexpect_session_environment().distro == 'osx': return 'g' + command return command
python
def get_command(self, command): """Helper function for osx - return gnu utils rather than default for eg head and md5sum where possible and needed. """ shutit_global.shutit_global_object.yield_to_draw() if command in ('md5sum','sed','head'): if self.get_current_shutit_pexpect_session_environment().distro == 'osx': return 'g' + command return command
[ "def", "get_command", "(", "self", ",", "command", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "if", "command", "in", "(", "'md5sum'", ",", "'sed'", ",", "'head'", ")", ":", "if", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "distro", "==", "'osx'", ":", "return", "'g'", "+", "command", "return", "command" ]
Helper function for osx - return gnu utils rather than default for eg head and md5sum where possible and needed.
[ "Helper", "function", "for", "osx", "-", "return", "gnu", "utils", "rather", "than", "default", "for", "eg", "head", "and", "md5sum", "where", "possible", "and", "needed", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2908-L2916
8,415
ianmiell/shutit
shutit_class.py
ShutIt.get_send_command
def get_send_command(self, send): """Internal helper function to get command that's really sent """ shutit_global.shutit_global_object.yield_to_draw() if send is None: return send cmd_arr = send.split() if cmd_arr and cmd_arr[0] in ('md5sum','sed','head'): newcmd = self.get_command(cmd_arr[0]) send = send.replace(cmd_arr[0],newcmd) return send
python
def get_send_command(self, send): """Internal helper function to get command that's really sent """ shutit_global.shutit_global_object.yield_to_draw() if send is None: return send cmd_arr = send.split() if cmd_arr and cmd_arr[0] in ('md5sum','sed','head'): newcmd = self.get_command(cmd_arr[0]) send = send.replace(cmd_arr[0],newcmd) return send
[ "def", "get_send_command", "(", "self", ",", "send", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "if", "send", "is", "None", ":", "return", "send", "cmd_arr", "=", "send", ".", "split", "(", ")", "if", "cmd_arr", "and", "cmd_arr", "[", "0", "]", "in", "(", "'md5sum'", ",", "'sed'", ",", "'head'", ")", ":", "newcmd", "=", "self", ".", "get_command", "(", "cmd_arr", "[", "0", "]", ")", "send", "=", "send", ".", "replace", "(", "cmd_arr", "[", "0", "]", ",", "newcmd", ")", "return", "send" ]
Internal helper function to get command that's really sent
[ "Internal", "helper", "function", "to", "get", "command", "that", "s", "really", "sent" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2919-L2929
8,416
ianmiell/shutit
shutit_class.py
ShutIt.load_configs
def load_configs(self): """Responsible for loading config files into ShutIt. Recurses down from configured shutit module paths. """ shutit_global.shutit_global_object.yield_to_draw() # Get root default config. # TODO: change default_cnf so it places whatever the values are at this stage of the build. configs = [('defaults', StringIO(default_cnf)), os.path.expanduser('~/.shutit/config'), os.path.join(self.host['shutit_path'], 'config'), 'configs/build.cnf'] # Add the shutit global host- and user-specific config file. # Add the local build.cnf # Get passed-in config(s) for config_file_name in self.build['extra_configs']: run_config_file = os.path.expanduser(config_file_name) if not os.path.isfile(run_config_file): shutit_global.shutit_global_object.shutit_print('Did not recognise ' + run_config_file + ' as a file - do you need to touch ' + run_config_file + '?') shutit_global.shutit_global_object.handle_exit(exit_code=0) configs.append(run_config_file) # Image to use to start off. The script should be idempotent, so running it # on an already built image should be ok, and is advised to reduce diff space required. if self.action['list_configs'] or self.loglevel <= logging.DEBUG: msg = '' for c in configs: if isinstance(c, tuple): c = c[0] msg = msg + ' \n' + c self.log(' ' + c,level=logging.DEBUG) # Interpret any config overrides, write to a file and add them to the # list of configs to be interpreted if self.build['config_overrides']: # We don't need layers, this is a temporary configparser override_cp = ConfigParser.RawConfigParser() for o_sec, o_key, o_val in self.build['config_overrides']: if not override_cp.has_section(o_sec): override_cp.add_section(o_sec) override_cp.set(o_sec, o_key, o_val) override_fd = StringIO() override_cp.write(override_fd) override_fd.seek(0) configs.append(('overrides', override_fd)) self.config_parser = self.get_configs(configs) self.get_base_config()
python
def load_configs(self): """Responsible for loading config files into ShutIt. Recurses down from configured shutit module paths. """ shutit_global.shutit_global_object.yield_to_draw() # Get root default config. # TODO: change default_cnf so it places whatever the values are at this stage of the build. configs = [('defaults', StringIO(default_cnf)), os.path.expanduser('~/.shutit/config'), os.path.join(self.host['shutit_path'], 'config'), 'configs/build.cnf'] # Add the shutit global host- and user-specific config file. # Add the local build.cnf # Get passed-in config(s) for config_file_name in self.build['extra_configs']: run_config_file = os.path.expanduser(config_file_name) if not os.path.isfile(run_config_file): shutit_global.shutit_global_object.shutit_print('Did not recognise ' + run_config_file + ' as a file - do you need to touch ' + run_config_file + '?') shutit_global.shutit_global_object.handle_exit(exit_code=0) configs.append(run_config_file) # Image to use to start off. The script should be idempotent, so running it # on an already built image should be ok, and is advised to reduce diff space required. if self.action['list_configs'] or self.loglevel <= logging.DEBUG: msg = '' for c in configs: if isinstance(c, tuple): c = c[0] msg = msg + ' \n' + c self.log(' ' + c,level=logging.DEBUG) # Interpret any config overrides, write to a file and add them to the # list of configs to be interpreted if self.build['config_overrides']: # We don't need layers, this is a temporary configparser override_cp = ConfigParser.RawConfigParser() for o_sec, o_key, o_val in self.build['config_overrides']: if not override_cp.has_section(o_sec): override_cp.add_section(o_sec) override_cp.set(o_sec, o_key, o_val) override_fd = StringIO() override_cp.write(override_fd) override_fd.seek(0) configs.append(('overrides', override_fd)) self.config_parser = self.get_configs(configs) self.get_base_config()
[ "def", "load_configs", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "# Get root default config.", "# TODO: change default_cnf so it places whatever the values are at this stage of the build.", "configs", "=", "[", "(", "'defaults'", ",", "StringIO", "(", "default_cnf", ")", ")", ",", "os", ".", "path", ".", "expanduser", "(", "'~/.shutit/config'", ")", ",", "os", ".", "path", ".", "join", "(", "self", ".", "host", "[", "'shutit_path'", "]", ",", "'config'", ")", ",", "'configs/build.cnf'", "]", "# Add the shutit global host- and user-specific config file.", "# Add the local build.cnf", "# Get passed-in config(s)", "for", "config_file_name", "in", "self", ".", "build", "[", "'extra_configs'", "]", ":", "run_config_file", "=", "os", ".", "path", ".", "expanduser", "(", "config_file_name", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "run_config_file", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "'Did not recognise '", "+", "run_config_file", "+", "' as a file - do you need to touch '", "+", "run_config_file", "+", "'?'", ")", "shutit_global", ".", "shutit_global_object", ".", "handle_exit", "(", "exit_code", "=", "0", ")", "configs", ".", "append", "(", "run_config_file", ")", "# Image to use to start off. The script should be idempotent, so running it", "# on an already built image should be ok, and is advised to reduce diff space required.", "if", "self", ".", "action", "[", "'list_configs'", "]", "or", "self", ".", "loglevel", "<=", "logging", ".", "DEBUG", ":", "msg", "=", "''", "for", "c", "in", "configs", ":", "if", "isinstance", "(", "c", ",", "tuple", ")", ":", "c", "=", "c", "[", "0", "]", "msg", "=", "msg", "+", "' \\n'", "+", "c", "self", ".", "log", "(", "' '", "+", "c", ",", "level", "=", "logging", ".", "DEBUG", ")", "# Interpret any config overrides, write to a file and add them to the", "# list of configs to be interpreted", "if", "self", ".", "build", "[", "'config_overrides'", "]", ":", "# We don't need layers, this is a temporary configparser", "override_cp", "=", "ConfigParser", ".", "RawConfigParser", "(", ")", "for", "o_sec", ",", "o_key", ",", "o_val", "in", "self", ".", "build", "[", "'config_overrides'", "]", ":", "if", "not", "override_cp", ".", "has_section", "(", "o_sec", ")", ":", "override_cp", ".", "add_section", "(", "o_sec", ")", "override_cp", ".", "set", "(", "o_sec", ",", "o_key", ",", "o_val", ")", "override_fd", "=", "StringIO", "(", ")", "override_cp", ".", "write", "(", "override_fd", ")", "override_fd", ".", "seek", "(", "0", ")", "configs", ".", "append", "(", "(", "'overrides'", ",", "override_fd", ")", ")", "self", ".", "config_parser", "=", "self", ".", "get_configs", "(", "configs", ")", "self", ".", "get_base_config", "(", ")" ]
Responsible for loading config files into ShutIt. Recurses down from configured shutit module paths.
[ "Responsible", "for", "loading", "config", "files", "into", "ShutIt", ".", "Recurses", "down", "from", "configured", "shutit", "module", "paths", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2932-L2974
8,417
ianmiell/shutit
shutit_class.py
ShutIt.config_collection
def config_collection(self): """Collect core config from config files for all seen modules. """ shutit_global.shutit_global_object.yield_to_draw() self.log('In config_collection',level=logging.DEBUG) cfg = self.cfg for module_id in self.module_ids(): # Default to None so we can interpret as ifneeded self.get_config(module_id, 'shutit.core.module.build', None, boolean=True, forcenone=True) self.get_config(module_id, 'shutit.core.module.remove', False, boolean=True) self.get_config(module_id, 'shutit.core.module.tag', False, boolean=True) # Default to allow any image self.get_config(module_id, 'shutit.core.module.allowed_images', [".*"]) module = self.shutit_map[module_id] cfg_file = os.path.dirname(get_module_file(self,module)) + '/configs/build.cnf' if os.path.isfile(cfg_file): # use self.get_config, forcing the passed-in default config_parser = ConfigParser.ConfigParser() config_parser.read(cfg_file) for section in config_parser.sections(): if section == module_id: for option in config_parser.options(section): if option == 'shutit.core.module.allowed_images': override = False for mod, opt, val in self.build['config_overrides']: val = val # pylint # skip overrides if mod == module_id and opt == option: override = True if override: continue value = config_parser.get(section,option) if option == 'shutit.core.module.allowed_images': value = json.loads(value) self.get_config(module_id, option, value, forceask=True) # ifneeded will (by default) only take effect if 'build' is not # specified. It can, however, be forced to a value, but this # should be unusual. if cfg[module_id]['shutit.core.module.build'] is None: self.get_config(module_id, 'shutit.core.module.build_ifneeded', True, boolean=True) cfg[module_id]['shutit.core.module.build'] = False else: self.get_config(module_id, 'shutit.core.module.build_ifneeded', False, boolean=True)
python
def config_collection(self): """Collect core config from config files for all seen modules. """ shutit_global.shutit_global_object.yield_to_draw() self.log('In config_collection',level=logging.DEBUG) cfg = self.cfg for module_id in self.module_ids(): # Default to None so we can interpret as ifneeded self.get_config(module_id, 'shutit.core.module.build', None, boolean=True, forcenone=True) self.get_config(module_id, 'shutit.core.module.remove', False, boolean=True) self.get_config(module_id, 'shutit.core.module.tag', False, boolean=True) # Default to allow any image self.get_config(module_id, 'shutit.core.module.allowed_images', [".*"]) module = self.shutit_map[module_id] cfg_file = os.path.dirname(get_module_file(self,module)) + '/configs/build.cnf' if os.path.isfile(cfg_file): # use self.get_config, forcing the passed-in default config_parser = ConfigParser.ConfigParser() config_parser.read(cfg_file) for section in config_parser.sections(): if section == module_id: for option in config_parser.options(section): if option == 'shutit.core.module.allowed_images': override = False for mod, opt, val in self.build['config_overrides']: val = val # pylint # skip overrides if mod == module_id and opt == option: override = True if override: continue value = config_parser.get(section,option) if option == 'shutit.core.module.allowed_images': value = json.loads(value) self.get_config(module_id, option, value, forceask=True) # ifneeded will (by default) only take effect if 'build' is not # specified. It can, however, be forced to a value, but this # should be unusual. if cfg[module_id]['shutit.core.module.build'] is None: self.get_config(module_id, 'shutit.core.module.build_ifneeded', True, boolean=True) cfg[module_id]['shutit.core.module.build'] = False else: self.get_config(module_id, 'shutit.core.module.build_ifneeded', False, boolean=True)
[ "def", "config_collection", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "self", ".", "log", "(", "'In config_collection'", ",", "level", "=", "logging", ".", "DEBUG", ")", "cfg", "=", "self", ".", "cfg", "for", "module_id", "in", "self", ".", "module_ids", "(", ")", ":", "# Default to None so we can interpret as ifneeded", "self", ".", "get_config", "(", "module_id", ",", "'shutit.core.module.build'", ",", "None", ",", "boolean", "=", "True", ",", "forcenone", "=", "True", ")", "self", ".", "get_config", "(", "module_id", ",", "'shutit.core.module.remove'", ",", "False", ",", "boolean", "=", "True", ")", "self", ".", "get_config", "(", "module_id", ",", "'shutit.core.module.tag'", ",", "False", ",", "boolean", "=", "True", ")", "# Default to allow any image", "self", ".", "get_config", "(", "module_id", ",", "'shutit.core.module.allowed_images'", ",", "[", "\".*\"", "]", ")", "module", "=", "self", ".", "shutit_map", "[", "module_id", "]", "cfg_file", "=", "os", ".", "path", ".", "dirname", "(", "get_module_file", "(", "self", ",", "module", ")", ")", "+", "'/configs/build.cnf'", "if", "os", ".", "path", ".", "isfile", "(", "cfg_file", ")", ":", "# use self.get_config, forcing the passed-in default", "config_parser", "=", "ConfigParser", ".", "ConfigParser", "(", ")", "config_parser", ".", "read", "(", "cfg_file", ")", "for", "section", "in", "config_parser", ".", "sections", "(", ")", ":", "if", "section", "==", "module_id", ":", "for", "option", "in", "config_parser", ".", "options", "(", "section", ")", ":", "if", "option", "==", "'shutit.core.module.allowed_images'", ":", "override", "=", "False", "for", "mod", ",", "opt", ",", "val", "in", "self", ".", "build", "[", "'config_overrides'", "]", ":", "val", "=", "val", "# pylint", "# skip overrides", "if", "mod", "==", "module_id", "and", "opt", "==", "option", ":", "override", "=", "True", "if", "override", ":", "continue", "value", "=", "config_parser", ".", "get", "(", "section", ",", "option", ")", "if", "option", "==", "'shutit.core.module.allowed_images'", ":", "value", "=", "json", ".", "loads", "(", "value", ")", "self", ".", "get_config", "(", "module_id", ",", "option", ",", "value", ",", "forceask", "=", "True", ")", "# ifneeded will (by default) only take effect if 'build' is not", "# specified. It can, however, be forced to a value, but this", "# should be unusual.", "if", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.build'", "]", "is", "None", ":", "self", ".", "get_config", "(", "module_id", ",", "'shutit.core.module.build_ifneeded'", ",", "True", ",", "boolean", "=", "True", ")", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.build'", "]", "=", "False", "else", ":", "self", ".", "get_config", "(", "module_id", ",", "'shutit.core.module.build_ifneeded'", ",", "False", ",", "boolean", "=", "True", ")" ]
Collect core config from config files for all seen modules.
[ "Collect", "core", "config", "from", "config", "files", "for", "all", "seen", "modules", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L3195-L3237
8,418
ianmiell/shutit
shutit_class.py
ShutIt.print_config
def print_config(self, cfg, hide_password=True, history=False, module_id=None): """Returns a string representing the config of this ShutIt run. """ shutit_global.shutit_global_object.yield_to_draw() cp = self.config_parser s = '' keys1 = list(cfg.keys()) if keys1: keys1.sort() for k in keys1: if module_id is not None and k != module_id: continue if isinstance(k, str) and isinstance(cfg[k], dict): s += '\n[' + k + ']\n' keys2 = list(cfg[k].keys()) if keys2: keys2.sort() for k1 in keys2: line = '' line += k1 + ':' # If we want to hide passwords, we do so using a sha512 # done an aritrary number of times (27). if hide_password and (k1 == 'password' or k1 == 'passphrase'): p = hashlib.sha512(cfg[k][k1]).hexdigest() i = 27 while i > 0: i -= 1 p = hashlib.sha512(s).hexdigest() line += p else: if type(cfg[k][k1] == bool): line += str(cfg[k][k1]) elif type(cfg[k][k1] == str): line += cfg[k][k1] if history: try: line += (30-len(line)) * ' ' + ' # ' + cp.whereset(k, k1) except Exception: # Assume this is because it was never set by a config parser. line += (30-len(line)) * ' ' + ' # ' + "defaults in code" s += line + '\n' return s
python
def print_config(self, cfg, hide_password=True, history=False, module_id=None): """Returns a string representing the config of this ShutIt run. """ shutit_global.shutit_global_object.yield_to_draw() cp = self.config_parser s = '' keys1 = list(cfg.keys()) if keys1: keys1.sort() for k in keys1: if module_id is not None and k != module_id: continue if isinstance(k, str) and isinstance(cfg[k], dict): s += '\n[' + k + ']\n' keys2 = list(cfg[k].keys()) if keys2: keys2.sort() for k1 in keys2: line = '' line += k1 + ':' # If we want to hide passwords, we do so using a sha512 # done an aritrary number of times (27). if hide_password and (k1 == 'password' or k1 == 'passphrase'): p = hashlib.sha512(cfg[k][k1]).hexdigest() i = 27 while i > 0: i -= 1 p = hashlib.sha512(s).hexdigest() line += p else: if type(cfg[k][k1] == bool): line += str(cfg[k][k1]) elif type(cfg[k][k1] == str): line += cfg[k][k1] if history: try: line += (30-len(line)) * ' ' + ' # ' + cp.whereset(k, k1) except Exception: # Assume this is because it was never set by a config parser. line += (30-len(line)) * ' ' + ' # ' + "defaults in code" s += line + '\n' return s
[ "def", "print_config", "(", "self", ",", "cfg", ",", "hide_password", "=", "True", ",", "history", "=", "False", ",", "module_id", "=", "None", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cp", "=", "self", ".", "config_parser", "s", "=", "''", "keys1", "=", "list", "(", "cfg", ".", "keys", "(", ")", ")", "if", "keys1", ":", "keys1", ".", "sort", "(", ")", "for", "k", "in", "keys1", ":", "if", "module_id", "is", "not", "None", "and", "k", "!=", "module_id", ":", "continue", "if", "isinstance", "(", "k", ",", "str", ")", "and", "isinstance", "(", "cfg", "[", "k", "]", ",", "dict", ")", ":", "s", "+=", "'\\n['", "+", "k", "+", "']\\n'", "keys2", "=", "list", "(", "cfg", "[", "k", "]", ".", "keys", "(", ")", ")", "if", "keys2", ":", "keys2", ".", "sort", "(", ")", "for", "k1", "in", "keys2", ":", "line", "=", "''", "line", "+=", "k1", "+", "':'", "# If we want to hide passwords, we do so using a sha512", "# done an aritrary number of times (27).", "if", "hide_password", "and", "(", "k1", "==", "'password'", "or", "k1", "==", "'passphrase'", ")", ":", "p", "=", "hashlib", ".", "sha512", "(", "cfg", "[", "k", "]", "[", "k1", "]", ")", ".", "hexdigest", "(", ")", "i", "=", "27", "while", "i", ">", "0", ":", "i", "-=", "1", "p", "=", "hashlib", ".", "sha512", "(", "s", ")", ".", "hexdigest", "(", ")", "line", "+=", "p", "else", ":", "if", "type", "(", "cfg", "[", "k", "]", "[", "k1", "]", "==", "bool", ")", ":", "line", "+=", "str", "(", "cfg", "[", "k", "]", "[", "k1", "]", ")", "elif", "type", "(", "cfg", "[", "k", "]", "[", "k1", "]", "==", "str", ")", ":", "line", "+=", "cfg", "[", "k", "]", "[", "k1", "]", "if", "history", ":", "try", ":", "line", "+=", "(", "30", "-", "len", "(", "line", ")", ")", "*", "' '", "+", "' # '", "+", "cp", ".", "whereset", "(", "k", ",", "k1", ")", "except", "Exception", ":", "# Assume this is because it was never set by a config parser.", "line", "+=", "(", "30", "-", "len", "(", "line", ")", ")", "*", "' '", "+", "' # '", "+", "\"defaults in code\"", "s", "+=", "line", "+", "'\\n'", "return", "s" ]
Returns a string representing the config of this ShutIt run.
[ "Returns", "a", "string", "representing", "the", "config", "of", "this", "ShutIt", "run", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L3338-L3379
8,419
ianmiell/shutit
shutit_class.py
ShutIt.process_args
def process_args(self, args): """Process the args we have. 'args' is always a ShutItInit object. """ shutit_global.shutit_global_object.yield_to_draw() assert isinstance(args,ShutItInit), shutit_util.print_debug() if args.action == 'version': shutit_global.shutit_global_object.shutit_print('ShutIt version: ' + shutit.shutit_version) shutit_global.shutit_global_object.handle_exit(exit_code=0) # What are we asking shutit to do? self.action['list_configs'] = args.action == 'list_configs' self.action['list_modules'] = args.action == 'list_modules' self.action['list_deps'] = args.action == 'list_deps' self.action['skeleton'] = args.action == 'skeleton' self.action['build'] = args.action == 'build' self.action['run'] = args.action == 'run' # Logging if not self.logging_setup_done: self.logfile = args.logfile self.loglevel = args.loglevel if self.loglevel is None or self.loglevel == '': self.loglevel = 'INFO' self.setup_logging() shutit_global.shutit_global_object.setup_panes(action=args.action) # This mode is a bit special - it's the only one with different arguments if self.action['skeleton']: self.handle_skeleton(args) shutit_global.shutit_global_object.handle_exit() elif self.action['run']: self.handle_run(args) sys.exit(0) elif self.action['build'] or self.action['list_configs'] or self.action['list_modules']: self.handle_build(args) else: self.fail('Should not get here: action was: ' + str(self.action)) self.nocolor = args.nocolor
python
def process_args(self, args): """Process the args we have. 'args' is always a ShutItInit object. """ shutit_global.shutit_global_object.yield_to_draw() assert isinstance(args,ShutItInit), shutit_util.print_debug() if args.action == 'version': shutit_global.shutit_global_object.shutit_print('ShutIt version: ' + shutit.shutit_version) shutit_global.shutit_global_object.handle_exit(exit_code=0) # What are we asking shutit to do? self.action['list_configs'] = args.action == 'list_configs' self.action['list_modules'] = args.action == 'list_modules' self.action['list_deps'] = args.action == 'list_deps' self.action['skeleton'] = args.action == 'skeleton' self.action['build'] = args.action == 'build' self.action['run'] = args.action == 'run' # Logging if not self.logging_setup_done: self.logfile = args.logfile self.loglevel = args.loglevel if self.loglevel is None or self.loglevel == '': self.loglevel = 'INFO' self.setup_logging() shutit_global.shutit_global_object.setup_panes(action=args.action) # This mode is a bit special - it's the only one with different arguments if self.action['skeleton']: self.handle_skeleton(args) shutit_global.shutit_global_object.handle_exit() elif self.action['run']: self.handle_run(args) sys.exit(0) elif self.action['build'] or self.action['list_configs'] or self.action['list_modules']: self.handle_build(args) else: self.fail('Should not get here: action was: ' + str(self.action)) self.nocolor = args.nocolor
[ "def", "process_args", "(", "self", ",", "args", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "assert", "isinstance", "(", "args", ",", "ShutItInit", ")", ",", "shutit_util", ".", "print_debug", "(", ")", "if", "args", ".", "action", "==", "'version'", ":", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "'ShutIt version: '", "+", "shutit", ".", "shutit_version", ")", "shutit_global", ".", "shutit_global_object", ".", "handle_exit", "(", "exit_code", "=", "0", ")", "# What are we asking shutit to do?", "self", ".", "action", "[", "'list_configs'", "]", "=", "args", ".", "action", "==", "'list_configs'", "self", ".", "action", "[", "'list_modules'", "]", "=", "args", ".", "action", "==", "'list_modules'", "self", ".", "action", "[", "'list_deps'", "]", "=", "args", ".", "action", "==", "'list_deps'", "self", ".", "action", "[", "'skeleton'", "]", "=", "args", ".", "action", "==", "'skeleton'", "self", ".", "action", "[", "'build'", "]", "=", "args", ".", "action", "==", "'build'", "self", ".", "action", "[", "'run'", "]", "=", "args", ".", "action", "==", "'run'", "# Logging", "if", "not", "self", ".", "logging_setup_done", ":", "self", ".", "logfile", "=", "args", ".", "logfile", "self", ".", "loglevel", "=", "args", ".", "loglevel", "if", "self", ".", "loglevel", "is", "None", "or", "self", ".", "loglevel", "==", "''", ":", "self", ".", "loglevel", "=", "'INFO'", "self", ".", "setup_logging", "(", ")", "shutit_global", ".", "shutit_global_object", ".", "setup_panes", "(", "action", "=", "args", ".", "action", ")", "# This mode is a bit special - it's the only one with different arguments", "if", "self", ".", "action", "[", "'skeleton'", "]", ":", "self", ".", "handle_skeleton", "(", "args", ")", "shutit_global", ".", "shutit_global_object", ".", "handle_exit", "(", ")", "elif", "self", ".", "action", "[", "'run'", "]", ":", "self", ".", "handle_run", "(", "args", ")", "sys", ".", "exit", "(", "0", ")", "elif", "self", ".", "action", "[", "'build'", "]", "or", "self", ".", "action", "[", "'list_configs'", "]", "or", "self", ".", "action", "[", "'list_modules'", "]", ":", "self", ".", "handle_build", "(", "args", ")", "else", ":", "self", ".", "fail", "(", "'Should not get here: action was: '", "+", "str", "(", "self", ".", "action", ")", ")", "self", ".", "nocolor", "=", "args", ".", "nocolor" ]
Process the args we have. 'args' is always a ShutItInit object.
[ "Process", "the", "args", "we", "have", ".", "args", "is", "always", "a", "ShutItInit", "object", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L3382-L3420
8,420
ianmiell/shutit
shutit_class.py
ShutIt.check_deps
def check_deps(self): """Dependency checking phase is performed in this method. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg self.log('PHASE: dependencies', level=logging.DEBUG) self.pause_point('\nNow checking for dependencies between modules', print_input=False, level=3) # Get modules we're going to build to_build = [ self.shutit_map[module_id] for module_id in self.shutit_map if module_id in cfg and cfg[module_id]['shutit.core.module.build'] ] # Add any deps we may need by extending to_build and altering cfg for module in to_build: self.resolve_dependencies(to_build, module) # Dep checking def err_checker(errs, triples): """Collate error information. """ new_triples = [] for err, triple in zip(errs, triples): if not err: new_triples.append(triple) continue found_errs.append(err) return new_triples found_errs = [] triples = [] for depender in to_build: for dependee_id in depender.depends_on: triples.append((depender, self.shutit_map.get(dependee_id), dependee_id)) triples = err_checker([ self.check_dependee_exists(depender, dependee, dependee_id) for depender, dependee, dependee_id in triples ], triples) triples = err_checker([ self.check_dependee_build(depender, dependee, dependee_id) for depender, dependee, dependee_id in triples ], triples) triples = err_checker([ check_dependee_order(depender, dependee, dependee_id) for depender, dependee, dependee_id in triples ], triples) if found_errs: return [(err,) for err in found_errs] self.log('Modules configured to be built (in order) are: ', level=logging.DEBUG) for module_id in self.module_ids(): module = self.shutit_map[module_id] if cfg[module_id]['shutit.core.module.build']: self.log(module_id + ' ' + str(module.run_order), level=logging.DEBUG) self.log('\n', level=logging.DEBUG) return []
python
def check_deps(self): """Dependency checking phase is performed in this method. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg self.log('PHASE: dependencies', level=logging.DEBUG) self.pause_point('\nNow checking for dependencies between modules', print_input=False, level=3) # Get modules we're going to build to_build = [ self.shutit_map[module_id] for module_id in self.shutit_map if module_id in cfg and cfg[module_id]['shutit.core.module.build'] ] # Add any deps we may need by extending to_build and altering cfg for module in to_build: self.resolve_dependencies(to_build, module) # Dep checking def err_checker(errs, triples): """Collate error information. """ new_triples = [] for err, triple in zip(errs, triples): if not err: new_triples.append(triple) continue found_errs.append(err) return new_triples found_errs = [] triples = [] for depender in to_build: for dependee_id in depender.depends_on: triples.append((depender, self.shutit_map.get(dependee_id), dependee_id)) triples = err_checker([ self.check_dependee_exists(depender, dependee, dependee_id) for depender, dependee, dependee_id in triples ], triples) triples = err_checker([ self.check_dependee_build(depender, dependee, dependee_id) for depender, dependee, dependee_id in triples ], triples) triples = err_checker([ check_dependee_order(depender, dependee, dependee_id) for depender, dependee, dependee_id in triples ], triples) if found_errs: return [(err,) for err in found_errs] self.log('Modules configured to be built (in order) are: ', level=logging.DEBUG) for module_id in self.module_ids(): module = self.shutit_map[module_id] if cfg[module_id]['shutit.core.module.build']: self.log(module_id + ' ' + str(module.run_order), level=logging.DEBUG) self.log('\n', level=logging.DEBUG) return []
[ "def", "check_deps", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfg", "=", "self", ".", "cfg", "self", ".", "log", "(", "'PHASE: dependencies'", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "pause_point", "(", "'\\nNow checking for dependencies between modules'", ",", "print_input", "=", "False", ",", "level", "=", "3", ")", "# Get modules we're going to build", "to_build", "=", "[", "self", ".", "shutit_map", "[", "module_id", "]", "for", "module_id", "in", "self", ".", "shutit_map", "if", "module_id", "in", "cfg", "and", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.build'", "]", "]", "# Add any deps we may need by extending to_build and altering cfg", "for", "module", "in", "to_build", ":", "self", ".", "resolve_dependencies", "(", "to_build", ",", "module", ")", "# Dep checking", "def", "err_checker", "(", "errs", ",", "triples", ")", ":", "\"\"\"Collate error information.\n\t\t\t\"\"\"", "new_triples", "=", "[", "]", "for", "err", ",", "triple", "in", "zip", "(", "errs", ",", "triples", ")", ":", "if", "not", "err", ":", "new_triples", ".", "append", "(", "triple", ")", "continue", "found_errs", ".", "append", "(", "err", ")", "return", "new_triples", "found_errs", "=", "[", "]", "triples", "=", "[", "]", "for", "depender", "in", "to_build", ":", "for", "dependee_id", "in", "depender", ".", "depends_on", ":", "triples", ".", "append", "(", "(", "depender", ",", "self", ".", "shutit_map", ".", "get", "(", "dependee_id", ")", ",", "dependee_id", ")", ")", "triples", "=", "err_checker", "(", "[", "self", ".", "check_dependee_exists", "(", "depender", ",", "dependee", ",", "dependee_id", ")", "for", "depender", ",", "dependee", ",", "dependee_id", "in", "triples", "]", ",", "triples", ")", "triples", "=", "err_checker", "(", "[", "self", ".", "check_dependee_build", "(", "depender", ",", "dependee", ",", "dependee_id", ")", "for", "depender", ",", "dependee", ",", "dependee_id", "in", "triples", "]", ",", "triples", ")", "triples", "=", "err_checker", "(", "[", "check_dependee_order", "(", "depender", ",", "dependee", ",", "dependee_id", ")", "for", "depender", ",", "dependee", ",", "dependee_id", "in", "triples", "]", ",", "triples", ")", "if", "found_errs", ":", "return", "[", "(", "err", ",", ")", "for", "err", "in", "found_errs", "]", "self", ".", "log", "(", "'Modules configured to be built (in order) are: '", ",", "level", "=", "logging", ".", "DEBUG", ")", "for", "module_id", "in", "self", ".", "module_ids", "(", ")", ":", "module", "=", "self", ".", "shutit_map", "[", "module_id", "]", "if", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.build'", "]", ":", "self", ".", "log", "(", "module_id", "+", "' '", "+", "str", "(", "module", ".", "run_order", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "log", "(", "'\\n'", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "[", "]" ]
Dependency checking phase is performed in this method.
[ "Dependency", "checking", "phase", "is", "performed", "in", "this", "method", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4361-L4409
8,421
ianmiell/shutit
shutit_class.py
ShutIt.check_conflicts
def check_conflicts(self): """Checks for any conflicts between modules configured to be built. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg # Now consider conflicts self.log('PHASE: conflicts', level=logging.DEBUG) errs = [] self.pause_point('\nNow checking for conflicts between modules', print_input=False, level=3) for module_id in self.module_ids(): if not cfg[module_id]['shutit.core.module.build']: continue conflicter = self.shutit_map[module_id] for conflictee in conflicter.conflicts_with: # If the module id isn't there, there's no problem. conflictee_obj = self.shutit_map.get(conflictee) if conflictee_obj is None: continue if ((cfg[conflicter.module_id]['shutit.core.module.build'] or self.is_to_be_built_or_is_installed(conflicter)) and (cfg[conflictee_obj.module_id]['shutit.core.module.build'] or self.is_to_be_built_or_is_installed(conflictee_obj))): errs.append(('conflicter module id: ' + conflicter.module_id + ' is configured to be built or is already built but conflicts with module_id: ' + conflictee_obj.module_id,)) return errs
python
def check_conflicts(self): """Checks for any conflicts between modules configured to be built. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg # Now consider conflicts self.log('PHASE: conflicts', level=logging.DEBUG) errs = [] self.pause_point('\nNow checking for conflicts between modules', print_input=False, level=3) for module_id in self.module_ids(): if not cfg[module_id]['shutit.core.module.build']: continue conflicter = self.shutit_map[module_id] for conflictee in conflicter.conflicts_with: # If the module id isn't there, there's no problem. conflictee_obj = self.shutit_map.get(conflictee) if conflictee_obj is None: continue if ((cfg[conflicter.module_id]['shutit.core.module.build'] or self.is_to_be_built_or_is_installed(conflicter)) and (cfg[conflictee_obj.module_id]['shutit.core.module.build'] or self.is_to_be_built_or_is_installed(conflictee_obj))): errs.append(('conflicter module id: ' + conflicter.module_id + ' is configured to be built or is already built but conflicts with module_id: ' + conflictee_obj.module_id,)) return errs
[ "def", "check_conflicts", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfg", "=", "self", ".", "cfg", "# Now consider conflicts", "self", ".", "log", "(", "'PHASE: conflicts'", ",", "level", "=", "logging", ".", "DEBUG", ")", "errs", "=", "[", "]", "self", ".", "pause_point", "(", "'\\nNow checking for conflicts between modules'", ",", "print_input", "=", "False", ",", "level", "=", "3", ")", "for", "module_id", "in", "self", ".", "module_ids", "(", ")", ":", "if", "not", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.build'", "]", ":", "continue", "conflicter", "=", "self", ".", "shutit_map", "[", "module_id", "]", "for", "conflictee", "in", "conflicter", ".", "conflicts_with", ":", "# If the module id isn't there, there's no problem.", "conflictee_obj", "=", "self", ".", "shutit_map", ".", "get", "(", "conflictee", ")", "if", "conflictee_obj", "is", "None", ":", "continue", "if", "(", "(", "cfg", "[", "conflicter", ".", "module_id", "]", "[", "'shutit.core.module.build'", "]", "or", "self", ".", "is_to_be_built_or_is_installed", "(", "conflicter", ")", ")", "and", "(", "cfg", "[", "conflictee_obj", ".", "module_id", "]", "[", "'shutit.core.module.build'", "]", "or", "self", ".", "is_to_be_built_or_is_installed", "(", "conflictee_obj", ")", ")", ")", ":", "errs", ".", "append", "(", "(", "'conflicter module id: '", "+", "conflicter", ".", "module_id", "+", "' is configured to be built or is already built but conflicts with module_id: '", "+", "conflictee_obj", ".", "module_id", ",", ")", ")", "return", "errs" ]
Checks for any conflicts between modules configured to be built.
[ "Checks", "for", "any", "conflicts", "between", "modules", "configured", "to", "be", "built", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4412-L4435
8,422
ianmiell/shutit
shutit_class.py
ShutIt.do_remove
def do_remove(self, loglevel=logging.DEBUG): """Remove modules by calling remove method on those configured for removal. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg # Now get the run_order keys in order and go. self.log('PHASE: remove', level=loglevel) self.pause_point('\nNow removing any modules that need removing', print_input=False, level=3) # Login at least once to get the exports. for module_id in self.module_ids(): module = self.shutit_map[module_id] self.log('considering whether to remove: ' + module_id, level=logging.DEBUG) if cfg[module_id]['shutit.core.module.remove']: self.log('removing: ' + module_id, level=logging.DEBUG) self.login(prompt_prefix=module_id,command=shutit_global.shutit_global_object.bash_startup_command,echo=False) if not module.remove(self): self.log(self.print_modules(), level=logging.DEBUG) self.fail(module_id + ' failed on remove', shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').pexpect_child) # pragma: no cover else: if self.build['delivery'] in ('docker','dockerfile'): # Create a directory and files to indicate this has been removed. self.send(' command mkdir -p ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/module_record/' + module.module_id + ' && command rm -f ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/module_record/' + module.module_id + '/built && command touch ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/module_record/' + module.module_id + '/removed', loglevel=loglevel, echo=False) # Remove from "installed" cache if module.module_id in self.get_current_shutit_pexpect_session_environment().modules_installed: self.get_current_shutit_pexpect_session_environment().modules_installed.remove(module.module_id) # Add to "not installed" cache self.get_current_shutit_pexpect_session_environment().modules_not_installed.append(module.module_id) self.logout(echo=False)
python
def do_remove(self, loglevel=logging.DEBUG): """Remove modules by calling remove method on those configured for removal. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg # Now get the run_order keys in order and go. self.log('PHASE: remove', level=loglevel) self.pause_point('\nNow removing any modules that need removing', print_input=False, level=3) # Login at least once to get the exports. for module_id in self.module_ids(): module = self.shutit_map[module_id] self.log('considering whether to remove: ' + module_id, level=logging.DEBUG) if cfg[module_id]['shutit.core.module.remove']: self.log('removing: ' + module_id, level=logging.DEBUG) self.login(prompt_prefix=module_id,command=shutit_global.shutit_global_object.bash_startup_command,echo=False) if not module.remove(self): self.log(self.print_modules(), level=logging.DEBUG) self.fail(module_id + ' failed on remove', shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').pexpect_child) # pragma: no cover else: if self.build['delivery'] in ('docker','dockerfile'): # Create a directory and files to indicate this has been removed. self.send(' command mkdir -p ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/module_record/' + module.module_id + ' && command rm -f ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/module_record/' + module.module_id + '/built && command touch ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/module_record/' + module.module_id + '/removed', loglevel=loglevel, echo=False) # Remove from "installed" cache if module.module_id in self.get_current_shutit_pexpect_session_environment().modules_installed: self.get_current_shutit_pexpect_session_environment().modules_installed.remove(module.module_id) # Add to "not installed" cache self.get_current_shutit_pexpect_session_environment().modules_not_installed.append(module.module_id) self.logout(echo=False)
[ "def", "do_remove", "(", "self", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfg", "=", "self", ".", "cfg", "# Now get the run_order keys in order and go.", "self", ".", "log", "(", "'PHASE: remove'", ",", "level", "=", "loglevel", ")", "self", ".", "pause_point", "(", "'\\nNow removing any modules that need removing'", ",", "print_input", "=", "False", ",", "level", "=", "3", ")", "# Login at least once to get the exports.", "for", "module_id", "in", "self", ".", "module_ids", "(", ")", ":", "module", "=", "self", ".", "shutit_map", "[", "module_id", "]", "self", ".", "log", "(", "'considering whether to remove: '", "+", "module_id", ",", "level", "=", "logging", ".", "DEBUG", ")", "if", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.remove'", "]", ":", "self", ".", "log", "(", "'removing: '", "+", "module_id", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "login", "(", "prompt_prefix", "=", "module_id", ",", "command", "=", "shutit_global", ".", "shutit_global_object", ".", "bash_startup_command", ",", "echo", "=", "False", ")", "if", "not", "module", ".", "remove", "(", "self", ")", ":", "self", ".", "log", "(", "self", ".", "print_modules", "(", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "fail", "(", "module_id", "+", "' failed on remove'", ",", "shutit_pexpect_child", "=", "self", ".", "get_shutit_pexpect_session_from_id", "(", "'target_child'", ")", ".", "pexpect_child", ")", "# pragma: no cover", "else", ":", "if", "self", ".", "build", "[", "'delivery'", "]", "in", "(", "'docker'", ",", "'dockerfile'", ")", ":", "# Create a directory and files to indicate this has been removed.", "self", ".", "send", "(", "' command mkdir -p '", "+", "shutit_global", ".", "shutit_global_object", ".", "shutit_state_dir_build_db_dir", "+", "'/module_record/'", "+", "module", ".", "module_id", "+", "' && command rm -f '", "+", "shutit_global", ".", "shutit_global_object", ".", "shutit_state_dir_build_db_dir", "+", "'/module_record/'", "+", "module", ".", "module_id", "+", "'/built && command touch '", "+", "shutit_global", ".", "shutit_global_object", ".", "shutit_state_dir_build_db_dir", "+", "'/module_record/'", "+", "module", ".", "module_id", "+", "'/removed'", ",", "loglevel", "=", "loglevel", ",", "echo", "=", "False", ")", "# Remove from \"installed\" cache", "if", "module", ".", "module_id", "in", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "modules_installed", ":", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "modules_installed", ".", "remove", "(", "module", ".", "module_id", ")", "# Add to \"not installed\" cache", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "modules_not_installed", ".", "append", "(", "module", ".", "module_id", ")", "self", ".", "logout", "(", "echo", "=", "False", ")" ]
Remove modules by calling remove method on those configured for removal.
[ "Remove", "modules", "by", "calling", "remove", "method", "on", "those", "configured", "for", "removal", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4466-L4493
8,423
ianmiell/shutit
shutit_class.py
ShutIt.do_build
def do_build(self): """Runs build phase, building any modules that we've determined need building. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg self.log('PHASE: build, repository work', level=logging.DEBUG) module_id_list = self.module_ids() if self.build['deps_only']: module_id_list_build_only = filter(lambda x: cfg[x]['shutit.core.module.build'], module_id_list) for module_id in module_id_list: module = self.shutit_map[module_id] self.log('Considering whether to build: ' + module.module_id, level=logging.INFO) if cfg[module.module_id]['shutit.core.module.build']: if self.build['delivery'] not in module.ok_delivery_methods: self.fail('Module: ' + module.module_id + ' can only be built with one of these --delivery methods: ' + str(module.ok_delivery_methods) + '\nSee shutit build -h for more info, or try adding: --delivery <method> to your shutit invocation') # pragma: no cover if self.is_installed(module): self.build['report'] = (self.build['report'] + '\nBuilt already: ' + module.module_id + ' with run order: ' + str(module.run_order)) else: # We move to the module directory to perform the build, returning immediately afterwards. if self.build['deps_only'] and module_id == module_id_list_build_only[-1]: # If this is the last module, and we are only building deps, stop here. self.build['report'] = (self.build['report'] + '\nSkipping: ' + module.module_id + ' with run order: ' + str(module.run_order) + '\n\tas this is the final module and we are building dependencies only') else: revert_dir = os.getcwd() self.get_current_shutit_pexpect_session_environment().module_root_dir = os.path.dirname(self.shutit_file_map[module_id]) self.chdir(self.get_current_shutit_pexpect_session_environment().module_root_dir) self.login(prompt_prefix=module_id,command=shutit_global.shutit_global_object.bash_startup_command,echo=False) self.build_module(module) self.logout(echo=False) self.chdir(revert_dir) if self.is_installed(module): self.log('Starting module',level=logging.DEBUG) if not module.start(self): self.fail(module.module_id + ' failed on start', shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').pexpect_child)
python
def do_build(self): """Runs build phase, building any modules that we've determined need building. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg self.log('PHASE: build, repository work', level=logging.DEBUG) module_id_list = self.module_ids() if self.build['deps_only']: module_id_list_build_only = filter(lambda x: cfg[x]['shutit.core.module.build'], module_id_list) for module_id in module_id_list: module = self.shutit_map[module_id] self.log('Considering whether to build: ' + module.module_id, level=logging.INFO) if cfg[module.module_id]['shutit.core.module.build']: if self.build['delivery'] not in module.ok_delivery_methods: self.fail('Module: ' + module.module_id + ' can only be built with one of these --delivery methods: ' + str(module.ok_delivery_methods) + '\nSee shutit build -h for more info, or try adding: --delivery <method> to your shutit invocation') # pragma: no cover if self.is_installed(module): self.build['report'] = (self.build['report'] + '\nBuilt already: ' + module.module_id + ' with run order: ' + str(module.run_order)) else: # We move to the module directory to perform the build, returning immediately afterwards. if self.build['deps_only'] and module_id == module_id_list_build_only[-1]: # If this is the last module, and we are only building deps, stop here. self.build['report'] = (self.build['report'] + '\nSkipping: ' + module.module_id + ' with run order: ' + str(module.run_order) + '\n\tas this is the final module and we are building dependencies only') else: revert_dir = os.getcwd() self.get_current_shutit_pexpect_session_environment().module_root_dir = os.path.dirname(self.shutit_file_map[module_id]) self.chdir(self.get_current_shutit_pexpect_session_environment().module_root_dir) self.login(prompt_prefix=module_id,command=shutit_global.shutit_global_object.bash_startup_command,echo=False) self.build_module(module) self.logout(echo=False) self.chdir(revert_dir) if self.is_installed(module): self.log('Starting module',level=logging.DEBUG) if not module.start(self): self.fail(module.module_id + ' failed on start', shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').pexpect_child)
[ "def", "do_build", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfg", "=", "self", ".", "cfg", "self", ".", "log", "(", "'PHASE: build, repository work'", ",", "level", "=", "logging", ".", "DEBUG", ")", "module_id_list", "=", "self", ".", "module_ids", "(", ")", "if", "self", ".", "build", "[", "'deps_only'", "]", ":", "module_id_list_build_only", "=", "filter", "(", "lambda", "x", ":", "cfg", "[", "x", "]", "[", "'shutit.core.module.build'", "]", ",", "module_id_list", ")", "for", "module_id", "in", "module_id_list", ":", "module", "=", "self", ".", "shutit_map", "[", "module_id", "]", "self", ".", "log", "(", "'Considering whether to build: '", "+", "module", ".", "module_id", ",", "level", "=", "logging", ".", "INFO", ")", "if", "cfg", "[", "module", ".", "module_id", "]", "[", "'shutit.core.module.build'", "]", ":", "if", "self", ".", "build", "[", "'delivery'", "]", "not", "in", "module", ".", "ok_delivery_methods", ":", "self", ".", "fail", "(", "'Module: '", "+", "module", ".", "module_id", "+", "' can only be built with one of these --delivery methods: '", "+", "str", "(", "module", ".", "ok_delivery_methods", ")", "+", "'\\nSee shutit build -h for more info, or try adding: --delivery <method> to your shutit invocation'", ")", "# pragma: no cover", "if", "self", ".", "is_installed", "(", "module", ")", ":", "self", ".", "build", "[", "'report'", "]", "=", "(", "self", ".", "build", "[", "'report'", "]", "+", "'\\nBuilt already: '", "+", "module", ".", "module_id", "+", "' with run order: '", "+", "str", "(", "module", ".", "run_order", ")", ")", "else", ":", "# We move to the module directory to perform the build, returning immediately afterwards.", "if", "self", ".", "build", "[", "'deps_only'", "]", "and", "module_id", "==", "module_id_list_build_only", "[", "-", "1", "]", ":", "# If this is the last module, and we are only building deps, stop here.", "self", ".", "build", "[", "'report'", "]", "=", "(", "self", ".", "build", "[", "'report'", "]", "+", "'\\nSkipping: '", "+", "module", ".", "module_id", "+", "' with run order: '", "+", "str", "(", "module", ".", "run_order", ")", "+", "'\\n\\tas this is the final module and we are building dependencies only'", ")", "else", ":", "revert_dir", "=", "os", ".", "getcwd", "(", ")", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "module_root_dir", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "shutit_file_map", "[", "module_id", "]", ")", "self", ".", "chdir", "(", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "module_root_dir", ")", "self", ".", "login", "(", "prompt_prefix", "=", "module_id", ",", "command", "=", "shutit_global", ".", "shutit_global_object", ".", "bash_startup_command", ",", "echo", "=", "False", ")", "self", ".", "build_module", "(", "module", ")", "self", ".", "logout", "(", "echo", "=", "False", ")", "self", ".", "chdir", "(", "revert_dir", ")", "if", "self", ".", "is_installed", "(", "module", ")", ":", "self", ".", "log", "(", "'Starting module'", ",", "level", "=", "logging", ".", "DEBUG", ")", "if", "not", "module", ".", "start", "(", "self", ")", ":", "self", ".", "fail", "(", "module", ".", "module_id", "+", "' failed on start'", ",", "shutit_pexpect_child", "=", "self", ".", "get_shutit_pexpect_session_from_id", "(", "'target_child'", ")", ".", "pexpect_child", ")" ]
Runs build phase, building any modules that we've determined need building.
[ "Runs", "build", "phase", "building", "any", "modules", "that", "we", "ve", "determined", "need", "building", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4535-L4569
8,424
ianmiell/shutit
shutit_class.py
ShutIt.stop_all
def stop_all(self, run_order=-1): """Runs stop method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we clean up state before committing run files etc. """ shutit_global.shutit_global_object.yield_to_draw() # sort them so they're stopped in reverse order for module_id in self.module_ids(rev=True): shutit_module_obj = self.shutit_map[module_id] if run_order == -1 or shutit_module_obj.run_order <= run_order: if self.is_installed(shutit_module_obj): if not shutit_module_obj.stop(self): self.fail('failed to stop: ' + module_id, shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').shutit_pexpect_child)
python
def stop_all(self, run_order=-1): """Runs stop method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we clean up state before committing run files etc. """ shutit_global.shutit_global_object.yield_to_draw() # sort them so they're stopped in reverse order for module_id in self.module_ids(rev=True): shutit_module_obj = self.shutit_map[module_id] if run_order == -1 or shutit_module_obj.run_order <= run_order: if self.is_installed(shutit_module_obj): if not shutit_module_obj.stop(self): self.fail('failed to stop: ' + module_id, shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').shutit_pexpect_child)
[ "def", "stop_all", "(", "self", ",", "run_order", "=", "-", "1", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "# sort them so they're stopped in reverse order", "for", "module_id", "in", "self", ".", "module_ids", "(", "rev", "=", "True", ")", ":", "shutit_module_obj", "=", "self", ".", "shutit_map", "[", "module_id", "]", "if", "run_order", "==", "-", "1", "or", "shutit_module_obj", ".", "run_order", "<=", "run_order", ":", "if", "self", ".", "is_installed", "(", "shutit_module_obj", ")", ":", "if", "not", "shutit_module_obj", ".", "stop", "(", "self", ")", ":", "self", ".", "fail", "(", "'failed to stop: '", "+", "module_id", ",", "shutit_pexpect_child", "=", "self", ".", "get_shutit_pexpect_session_from_id", "(", "'target_child'", ")", ".", "shutit_pexpect_child", ")" ]
Runs stop method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we clean up state before committing run files etc.
[ "Runs", "stop", "method", "on", "all", "modules", "less", "than", "the", "passed", "-", "in", "run_order", ".", "Used", "when", "target", "is", "exporting", "itself", "mid", "-", "build", "so", "we", "clean", "up", "state", "before", "committing", "run", "files", "etc", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4615-L4627
8,425
ianmiell/shutit
shutit_class.py
ShutIt.start_all
def start_all(self, run_order=-1): """Runs start method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we can export a clean target and still depended-on modules running if necessary. """ shutit_global.shutit_global_object.yield_to_draw() # sort them so they're started in order for module_id in self.module_ids(): shutit_module_obj = self.shutit_map[module_id] if run_order == -1 or shutit_module_obj.run_order <= run_order: if self.is_installed(shutit_module_obj): if not shutit_module_obj.start(self): self.fail('failed to start: ' + module_id, shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').shutit_pexpect_child)
python
def start_all(self, run_order=-1): """Runs start method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we can export a clean target and still depended-on modules running if necessary. """ shutit_global.shutit_global_object.yield_to_draw() # sort them so they're started in order for module_id in self.module_ids(): shutit_module_obj = self.shutit_map[module_id] if run_order == -1 or shutit_module_obj.run_order <= run_order: if self.is_installed(shutit_module_obj): if not shutit_module_obj.start(self): self.fail('failed to start: ' + module_id, shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').shutit_pexpect_child)
[ "def", "start_all", "(", "self", ",", "run_order", "=", "-", "1", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "# sort them so they're started in order", "for", "module_id", "in", "self", ".", "module_ids", "(", ")", ":", "shutit_module_obj", "=", "self", ".", "shutit_map", "[", "module_id", "]", "if", "run_order", "==", "-", "1", "or", "shutit_module_obj", ".", "run_order", "<=", "run_order", ":", "if", "self", ".", "is_installed", "(", "shutit_module_obj", ")", ":", "if", "not", "shutit_module_obj", ".", "start", "(", "self", ")", ":", "self", ".", "fail", "(", "'failed to start: '", "+", "module_id", ",", "shutit_pexpect_child", "=", "self", ".", "get_shutit_pexpect_session_from_id", "(", "'target_child'", ")", ".", "shutit_pexpect_child", ")" ]
Runs start method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we can export a clean target and still depended-on modules running if necessary.
[ "Runs", "start", "method", "on", "all", "modules", "less", "than", "the", "passed", "-", "in", "run_order", ".", "Used", "when", "target", "is", "exporting", "itself", "mid", "-", "build", "so", "we", "can", "export", "a", "clean", "target", "and", "still", "depended", "-", "on", "modules", "running", "if", "necessary", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4631-L4643
8,426
ianmiell/shutit
shutit_class.py
ShutIt.init_shutit_map
def init_shutit_map(self): """Initializes the module map of shutit based on the modules we have gathered. Checks we have core modules Checks for duplicate module details. Sets up common config. Sets up map of modules. """ shutit_global.shutit_global_object.yield_to_draw() modules = self.shutit_modules # Have we got anything to process outside of special modules? if len([mod for mod in modules if mod.run_order > 0]) < 1: self.log(modules,level=logging.DEBUG) path = ':'.join(self.host['shutit_module_path']) self.log('\nIf you are new to ShutIt, see:\n\n\thttp://ianmiell.github.io/shutit/\n\nor try running\n\n\tshutit skeleton\n\n',level=logging.INFO) if path == '': self.fail('No ShutIt modules aside from core ones found and no ShutIt module path given.\nDid you set --shutit_module_path/-m wrongly?\n') # pragma: no cover elif path == '.': self.fail('No modules aside from core ones found and no ShutIt module path given apart from default (.).\n\n- Did you set --shutit_module_path/-m?\n- Is there a STOP* file in your . dir?') # pragma: no cover else: self.fail('No modules aside from core ones found and no ShutIt modules in path:\n\n' + path + '\n\nor their subfolders. Check your --shutit_module_path/-m setting and check that there are ShutIt modules below without STOP* files in any relevant directories.') # pragma: no cover self.log('PHASE: base setup', level=logging.DEBUG) run_orders = {} has_core_module = False for module in modules: assert isinstance(module, ShutItModule), shutit_util.print_debug() if module.module_id in self.shutit_map: self.fail('Duplicated module id: ' + module.module_id + '\n\nYou may want to check your --shutit_module_path setting') # pragma: no cover if module.run_order in run_orders: self.fail('Duplicate run order: ' + str(module.run_order) + ' for ' + module.module_id + ' and ' + run_orders[module.run_order].module_id + '\n\nYou may want to check your --shutit_module_path setting') # pragma: no cover if module.run_order == 0: has_core_module = True self.shutit_map[module.module_id] = run_orders[module.run_order] = module self.shutit_file_map[module.module_id] = get_module_file(self, module) if not has_core_module: self.fail('No module with run_order=0 specified! This is required.')
python
def init_shutit_map(self): """Initializes the module map of shutit based on the modules we have gathered. Checks we have core modules Checks for duplicate module details. Sets up common config. Sets up map of modules. """ shutit_global.shutit_global_object.yield_to_draw() modules = self.shutit_modules # Have we got anything to process outside of special modules? if len([mod for mod in modules if mod.run_order > 0]) < 1: self.log(modules,level=logging.DEBUG) path = ':'.join(self.host['shutit_module_path']) self.log('\nIf you are new to ShutIt, see:\n\n\thttp://ianmiell.github.io/shutit/\n\nor try running\n\n\tshutit skeleton\n\n',level=logging.INFO) if path == '': self.fail('No ShutIt modules aside from core ones found and no ShutIt module path given.\nDid you set --shutit_module_path/-m wrongly?\n') # pragma: no cover elif path == '.': self.fail('No modules aside from core ones found and no ShutIt module path given apart from default (.).\n\n- Did you set --shutit_module_path/-m?\n- Is there a STOP* file in your . dir?') # pragma: no cover else: self.fail('No modules aside from core ones found and no ShutIt modules in path:\n\n' + path + '\n\nor their subfolders. Check your --shutit_module_path/-m setting and check that there are ShutIt modules below without STOP* files in any relevant directories.') # pragma: no cover self.log('PHASE: base setup', level=logging.DEBUG) run_orders = {} has_core_module = False for module in modules: assert isinstance(module, ShutItModule), shutit_util.print_debug() if module.module_id in self.shutit_map: self.fail('Duplicated module id: ' + module.module_id + '\n\nYou may want to check your --shutit_module_path setting') # pragma: no cover if module.run_order in run_orders: self.fail('Duplicate run order: ' + str(module.run_order) + ' for ' + module.module_id + ' and ' + run_orders[module.run_order].module_id + '\n\nYou may want to check your --shutit_module_path setting') # pragma: no cover if module.run_order == 0: has_core_module = True self.shutit_map[module.module_id] = run_orders[module.run_order] = module self.shutit_file_map[module.module_id] = get_module_file(self, module) if not has_core_module: self.fail('No module with run_order=0 specified! This is required.')
[ "def", "init_shutit_map", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "modules", "=", "self", ".", "shutit_modules", "# Have we got anything to process outside of special modules?", "if", "len", "(", "[", "mod", "for", "mod", "in", "modules", "if", "mod", ".", "run_order", ">", "0", "]", ")", "<", "1", ":", "self", ".", "log", "(", "modules", ",", "level", "=", "logging", ".", "DEBUG", ")", "path", "=", "':'", ".", "join", "(", "self", ".", "host", "[", "'shutit_module_path'", "]", ")", "self", ".", "log", "(", "'\\nIf you are new to ShutIt, see:\\n\\n\\thttp://ianmiell.github.io/shutit/\\n\\nor try running\\n\\n\\tshutit skeleton\\n\\n'", ",", "level", "=", "logging", ".", "INFO", ")", "if", "path", "==", "''", ":", "self", ".", "fail", "(", "'No ShutIt modules aside from core ones found and no ShutIt module path given.\\nDid you set --shutit_module_path/-m wrongly?\\n'", ")", "# pragma: no cover", "elif", "path", "==", "'.'", ":", "self", ".", "fail", "(", "'No modules aside from core ones found and no ShutIt module path given apart from default (.).\\n\\n- Did you set --shutit_module_path/-m?\\n- Is there a STOP* file in your . dir?'", ")", "# pragma: no cover", "else", ":", "self", ".", "fail", "(", "'No modules aside from core ones found and no ShutIt modules in path:\\n\\n'", "+", "path", "+", "'\\n\\nor their subfolders. Check your --shutit_module_path/-m setting and check that there are ShutIt modules below without STOP* files in any relevant directories.'", ")", "# pragma: no cover", "self", ".", "log", "(", "'PHASE: base setup'", ",", "level", "=", "logging", ".", "DEBUG", ")", "run_orders", "=", "{", "}", "has_core_module", "=", "False", "for", "module", "in", "modules", ":", "assert", "isinstance", "(", "module", ",", "ShutItModule", ")", ",", "shutit_util", ".", "print_debug", "(", ")", "if", "module", ".", "module_id", "in", "self", ".", "shutit_map", ":", "self", ".", "fail", "(", "'Duplicated module id: '", "+", "module", ".", "module_id", "+", "'\\n\\nYou may want to check your --shutit_module_path setting'", ")", "# pragma: no cover", "if", "module", ".", "run_order", "in", "run_orders", ":", "self", ".", "fail", "(", "'Duplicate run order: '", "+", "str", "(", "module", ".", "run_order", ")", "+", "' for '", "+", "module", ".", "module_id", "+", "' and '", "+", "run_orders", "[", "module", ".", "run_order", "]", ".", "module_id", "+", "'\\n\\nYou may want to check your --shutit_module_path setting'", ")", "# pragma: no cover", "if", "module", ".", "run_order", "==", "0", ":", "has_core_module", "=", "True", "self", ".", "shutit_map", "[", "module", ".", "module_id", "]", "=", "run_orders", "[", "module", ".", "run_order", "]", "=", "module", "self", ".", "shutit_file_map", "[", "module", ".", "module_id", "]", "=", "get_module_file", "(", "self", ",", "module", ")", "if", "not", "has_core_module", ":", "self", ".", "fail", "(", "'No module with run_order=0 specified! This is required.'", ")" ]
Initializes the module map of shutit based on the modules we have gathered. Checks we have core modules Checks for duplicate module details. Sets up common config. Sets up map of modules.
[ "Initializes", "the", "module", "map", "of", "shutit", "based", "on", "the", "modules", "we", "have", "gathered", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4661-L4700
8,427
ianmiell/shutit
shutit_class.py
ShutIt.conn_target
def conn_target(self): """Connect to the target. """ shutit_global.shutit_global_object.yield_to_draw() conn_module = None for mod in self.conn_modules: if mod.module_id == self.build['conn_module']: conn_module = mod break if conn_module is None: self.fail('Couldn\'t find conn_module ' + self.build['conn_module']) # pragma: no cover # Set up the target in pexpect. conn_module.get_config(self) conn_module.build(self)
python
def conn_target(self): """Connect to the target. """ shutit_global.shutit_global_object.yield_to_draw() conn_module = None for mod in self.conn_modules: if mod.module_id == self.build['conn_module']: conn_module = mod break if conn_module is None: self.fail('Couldn\'t find conn_module ' + self.build['conn_module']) # pragma: no cover # Set up the target in pexpect. conn_module.get_config(self) conn_module.build(self)
[ "def", "conn_target", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "conn_module", "=", "None", "for", "mod", "in", "self", ".", "conn_modules", ":", "if", "mod", ".", "module_id", "==", "self", ".", "build", "[", "'conn_module'", "]", ":", "conn_module", "=", "mod", "break", "if", "conn_module", "is", "None", ":", "self", ".", "fail", "(", "'Couldn\\'t find conn_module '", "+", "self", ".", "build", "[", "'conn_module'", "]", ")", "# pragma: no cover", "# Set up the target in pexpect.", "conn_module", ".", "get_config", "(", "self", ")", "conn_module", ".", "build", "(", "self", ")" ]
Connect to the target.
[ "Connect", "to", "the", "target", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4703-L4717
8,428
ianmiell/shutit
shutit_class.py
ShutIt.finalize_target
def finalize_target(self): """Finalize the target using the core finalize method. """ shutit_global.shutit_global_object.yield_to_draw() self.pause_point('\nFinalizing the target module (' + self.shutit_main_dir + '/shutit_setup.py)', print_input=False, level=3) # Can assume conn_module exists at this point for mod in self.conn_modules: if mod.module_id == self.build['conn_module']: conn_module = mod break conn_module.finalize(self)
python
def finalize_target(self): """Finalize the target using the core finalize method. """ shutit_global.shutit_global_object.yield_to_draw() self.pause_point('\nFinalizing the target module (' + self.shutit_main_dir + '/shutit_setup.py)', print_input=False, level=3) # Can assume conn_module exists at this point for mod in self.conn_modules: if mod.module_id == self.build['conn_module']: conn_module = mod break conn_module.finalize(self)
[ "def", "finalize_target", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "self", ".", "pause_point", "(", "'\\nFinalizing the target module ('", "+", "self", ".", "shutit_main_dir", "+", "'/shutit_setup.py)'", ",", "print_input", "=", "False", ",", "level", "=", "3", ")", "# Can assume conn_module exists at this point", "for", "mod", "in", "self", ".", "conn_modules", ":", "if", "mod", ".", "module_id", "==", "self", ".", "build", "[", "'conn_module'", "]", ":", "conn_module", "=", "mod", "break", "conn_module", ".", "finalize", "(", "self", ")" ]
Finalize the target using the core finalize method.
[ "Finalize", "the", "target", "using", "the", "core", "finalize", "method", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4720-L4730
8,429
ianmiell/shutit
shutit_class.py
ShutIt.resolve_dependencies
def resolve_dependencies(self, to_build, depender): """Add any required dependencies. """ shutit_global.shutit_global_object.yield_to_draw() self.log('In resolve_dependencies',level=logging.DEBUG) cfg = self.cfg for dependee_id in depender.depends_on: dependee = self.shutit_map.get(dependee_id) # Don't care if module doesn't exist, we check this later if (dependee and dependee not in to_build and cfg[dependee_id]['shutit.core.module.build_ifneeded']): to_build.append(dependee) cfg[dependee_id]['shutit.core.module.build'] = True return True
python
def resolve_dependencies(self, to_build, depender): """Add any required dependencies. """ shutit_global.shutit_global_object.yield_to_draw() self.log('In resolve_dependencies',level=logging.DEBUG) cfg = self.cfg for dependee_id in depender.depends_on: dependee = self.shutit_map.get(dependee_id) # Don't care if module doesn't exist, we check this later if (dependee and dependee not in to_build and cfg[dependee_id]['shutit.core.module.build_ifneeded']): to_build.append(dependee) cfg[dependee_id]['shutit.core.module.build'] = True return True
[ "def", "resolve_dependencies", "(", "self", ",", "to_build", ",", "depender", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "self", ".", "log", "(", "'In resolve_dependencies'", ",", "level", "=", "logging", ".", "DEBUG", ")", "cfg", "=", "self", ".", "cfg", "for", "dependee_id", "in", "depender", ".", "depends_on", ":", "dependee", "=", "self", ".", "shutit_map", ".", "get", "(", "dependee_id", ")", "# Don't care if module doesn't exist, we check this later", "if", "(", "dependee", "and", "dependee", "not", "in", "to_build", "and", "cfg", "[", "dependee_id", "]", "[", "'shutit.core.module.build_ifneeded'", "]", ")", ":", "to_build", ".", "append", "(", "dependee", ")", "cfg", "[", "dependee_id", "]", "[", "'shutit.core.module.build'", "]", "=", "True", "return", "True" ]
Add any required dependencies.
[ "Add", "any", "required", "dependencies", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4735-L4748
8,430
ianmiell/shutit
shutit_class.py
ShutIt.check_dependee_exists
def check_dependee_exists(self, depender, dependee, dependee_id): """Checks whether a depended-on module is available. """ shutit_global.shutit_global_object.yield_to_draw() # If the module id isn't there, there's a problem. if dependee is None: return 'module: \n\n' + dependee_id + '\n\nnot found in paths: ' + str(self.host['shutit_module_path']) + ' but needed for ' + depender.module_id + '\nCheck your --shutit_module_path setting and ensure that all modules configured to be built are in that path setting, eg "--shutit_module_path /path/to/other/module/:."\n\nAlso check that the module is configured to be built with the correct module id in that module\'s configs/build.cnf file.\n\nSee also help.' return ''
python
def check_dependee_exists(self, depender, dependee, dependee_id): """Checks whether a depended-on module is available. """ shutit_global.shutit_global_object.yield_to_draw() # If the module id isn't there, there's a problem. if dependee is None: return 'module: \n\n' + dependee_id + '\n\nnot found in paths: ' + str(self.host['shutit_module_path']) + ' but needed for ' + depender.module_id + '\nCheck your --shutit_module_path setting and ensure that all modules configured to be built are in that path setting, eg "--shutit_module_path /path/to/other/module/:."\n\nAlso check that the module is configured to be built with the correct module id in that module\'s configs/build.cnf file.\n\nSee also help.' return ''
[ "def", "check_dependee_exists", "(", "self", ",", "depender", ",", "dependee", ",", "dependee_id", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "# If the module id isn't there, there's a problem.", "if", "dependee", "is", "None", ":", "return", "'module: \\n\\n'", "+", "dependee_id", "+", "'\\n\\nnot found in paths: '", "+", "str", "(", "self", ".", "host", "[", "'shutit_module_path'", "]", ")", "+", "' but needed for '", "+", "depender", ".", "module_id", "+", "'\\nCheck your --shutit_module_path setting and ensure that all modules configured to be built are in that path setting, eg \"--shutit_module_path /path/to/other/module/:.\"\\n\\nAlso check that the module is configured to be built with the correct module id in that module\\'s configs/build.cnf file.\\n\\nSee also help.'", "return", "''" ]
Checks whether a depended-on module is available.
[ "Checks", "whether", "a", "depended", "-", "on", "module", "is", "available", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4751-L4758
8,431
ianmiell/shutit
shutit_class.py
ShutIt.check_dependee_build
def check_dependee_build(self, depender, dependee, dependee_id): """Checks whether a depended on module is configured to be built. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg # If depender is installed or will be installed, so must the dependee if not (cfg[dependee.module_id]['shutit.core.module.build'] or self.is_to_be_built_or_is_installed(dependee)): return 'depender module id:\n\n[' + depender.module_id + ']\n\nis configured: "build:yes" or is already built but dependee module_id:\n\n[' + dependee_id + ']\n\n is not configured: "build:yes"' return ''
python
def check_dependee_build(self, depender, dependee, dependee_id): """Checks whether a depended on module is configured to be built. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg # If depender is installed or will be installed, so must the dependee if not (cfg[dependee.module_id]['shutit.core.module.build'] or self.is_to_be_built_or_is_installed(dependee)): return 'depender module id:\n\n[' + depender.module_id + ']\n\nis configured: "build:yes" or is already built but dependee module_id:\n\n[' + dependee_id + ']\n\n is not configured: "build:yes"' return ''
[ "def", "check_dependee_build", "(", "self", ",", "depender", ",", "dependee", ",", "dependee_id", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfg", "=", "self", ".", "cfg", "# If depender is installed or will be installed, so must the dependee", "if", "not", "(", "cfg", "[", "dependee", ".", "module_id", "]", "[", "'shutit.core.module.build'", "]", "or", "self", ".", "is_to_be_built_or_is_installed", "(", "dependee", ")", ")", ":", "return", "'depender module id:\\n\\n['", "+", "depender", ".", "module_id", "+", "']\\n\\nis configured: \"build:yes\" or is already built but dependee module_id:\\n\\n['", "+", "dependee_id", "+", "']\\n\\n is not configured: \"build:yes\"'", "return", "''" ]
Checks whether a depended on module is configured to be built.
[ "Checks", "whether", "a", "depended", "on", "module", "is", "configured", "to", "be", "built", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4761-L4770
8,432
ianmiell/shutit
shutit_class.py
ShutIt.destroy
def destroy(self): """Finish up a session. """ if self.session_type == 'bash': # TODO: does this work/handle already being logged out/logged in deep OK? self.logout() elif self.session_type == 'vagrant': # TODO: does this work/handle already being logged out/logged in deep OK? self.logout()
python
def destroy(self): """Finish up a session. """ if self.session_type == 'bash': # TODO: does this work/handle already being logged out/logged in deep OK? self.logout() elif self.session_type == 'vagrant': # TODO: does this work/handle already being logged out/logged in deep OK? self.logout()
[ "def", "destroy", "(", "self", ")", ":", "if", "self", ".", "session_type", "==", "'bash'", ":", "# TODO: does this work/handle already being logged out/logged in deep OK?", "self", ".", "logout", "(", ")", "elif", "self", ".", "session_type", "==", "'vagrant'", ":", "# TODO: does this work/handle already being logged out/logged in deep OK?", "self", ".", "logout", "(", ")" ]
Finish up a session.
[ "Finish", "up", "a", "session", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4858-L4866
8,433
ianmiell/shutit
shutit_module.py
shutit_method_scope
def shutit_method_scope(func): """Notifies the ShutIt object whenever we call a shutit module method. This allows setting values for the 'scope' of a function. """ def wrapper(self, shutit): """Wrapper to call a shutit module method, notifying the ShutIt object. """ ret = func(self, shutit) return ret return wrapper
python
def shutit_method_scope(func): """Notifies the ShutIt object whenever we call a shutit module method. This allows setting values for the 'scope' of a function. """ def wrapper(self, shutit): """Wrapper to call a shutit module method, notifying the ShutIt object. """ ret = func(self, shutit) return ret return wrapper
[ "def", "shutit_method_scope", "(", "func", ")", ":", "def", "wrapper", "(", "self", ",", "shutit", ")", ":", "\"\"\"Wrapper to call a shutit module method, notifying the ShutIt object.\n\t\t\"\"\"", "ret", "=", "func", "(", "self", ",", "shutit", ")", "return", "ret", "return", "wrapper" ]
Notifies the ShutIt object whenever we call a shutit module method. This allows setting values for the 'scope' of a function.
[ "Notifies", "the", "ShutIt", "object", "whenever", "we", "call", "a", "shutit", "module", "method", ".", "This", "allows", "setting", "values", "for", "the", "scope", "of", "a", "function", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_module.py#L53-L62
8,434
ianmiell/shutit
shutit_threads.py
managing_thread_main_simple
def managing_thread_main_simple(): """Simpler thread to track whether main thread has been quiet for long enough that a thread dump should be printed. """ import shutit_global last_msg = '' while True: printed_anything = False if shutit_global.shutit_global_object.log_trace_when_idle and time.time() - shutit_global.shutit_global_object.last_log_time > 10: this_msg = '' this_header = '' for thread_id, stack in sys._current_frames().items(): # ignore own thread: if thread_id == threading.current_thread().ident: continue printed_thread_started = False for filename, lineno, name, line in traceback.extract_stack(stack): if not printed_anything: printed_anything = True this_header += '\n='*80 + '\n' this_header += 'STACK TRACES PRINTED ON IDLE: THREAD_ID: ' + str(thread_id) + ' at ' + time.strftime('%c') + '\n' this_header += '='*80 + '\n' if not printed_thread_started: printed_thread_started = True this_msg += '%s:%d:%s' % (filename, lineno, name) + '\n' if line: this_msg += ' %s' % (line,) + '\n' if printed_anything: this_msg += '='*80 + '\n' this_msg += 'STACK TRACES DONE\n' this_msg += '='*80 + '\n' if this_msg != last_msg: print(this_header + this_msg) last_msg = this_msg time.sleep(5)
python
def managing_thread_main_simple(): """Simpler thread to track whether main thread has been quiet for long enough that a thread dump should be printed. """ import shutit_global last_msg = '' while True: printed_anything = False if shutit_global.shutit_global_object.log_trace_when_idle and time.time() - shutit_global.shutit_global_object.last_log_time > 10: this_msg = '' this_header = '' for thread_id, stack in sys._current_frames().items(): # ignore own thread: if thread_id == threading.current_thread().ident: continue printed_thread_started = False for filename, lineno, name, line in traceback.extract_stack(stack): if not printed_anything: printed_anything = True this_header += '\n='*80 + '\n' this_header += 'STACK TRACES PRINTED ON IDLE: THREAD_ID: ' + str(thread_id) + ' at ' + time.strftime('%c') + '\n' this_header += '='*80 + '\n' if not printed_thread_started: printed_thread_started = True this_msg += '%s:%d:%s' % (filename, lineno, name) + '\n' if line: this_msg += ' %s' % (line,) + '\n' if printed_anything: this_msg += '='*80 + '\n' this_msg += 'STACK TRACES DONE\n' this_msg += '='*80 + '\n' if this_msg != last_msg: print(this_header + this_msg) last_msg = this_msg time.sleep(5)
[ "def", "managing_thread_main_simple", "(", ")", ":", "import", "shutit_global", "last_msg", "=", "''", "while", "True", ":", "printed_anything", "=", "False", "if", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "and", "time", ".", "time", "(", ")", "-", "shutit_global", ".", "shutit_global_object", ".", "last_log_time", ">", "10", ":", "this_msg", "=", "''", "this_header", "=", "''", "for", "thread_id", ",", "stack", "in", "sys", ".", "_current_frames", "(", ")", ".", "items", "(", ")", ":", "# ignore own thread:", "if", "thread_id", "==", "threading", ".", "current_thread", "(", ")", ".", "ident", ":", "continue", "printed_thread_started", "=", "False", "for", "filename", ",", "lineno", ",", "name", ",", "line", "in", "traceback", ".", "extract_stack", "(", "stack", ")", ":", "if", "not", "printed_anything", ":", "printed_anything", "=", "True", "this_header", "+=", "'\\n='", "*", "80", "+", "'\\n'", "this_header", "+=", "'STACK TRACES PRINTED ON IDLE: THREAD_ID: '", "+", "str", "(", "thread_id", ")", "+", "' at '", "+", "time", ".", "strftime", "(", "'%c'", ")", "+", "'\\n'", "this_header", "+=", "'='", "*", "80", "+", "'\\n'", "if", "not", "printed_thread_started", ":", "printed_thread_started", "=", "True", "this_msg", "+=", "'%s:%d:%s'", "%", "(", "filename", ",", "lineno", ",", "name", ")", "+", "'\\n'", "if", "line", ":", "this_msg", "+=", "' %s'", "%", "(", "line", ",", ")", "+", "'\\n'", "if", "printed_anything", ":", "this_msg", "+=", "'='", "*", "80", "+", "'\\n'", "this_msg", "+=", "'STACK TRACES DONE\\n'", "this_msg", "+=", "'='", "*", "80", "+", "'\\n'", "if", "this_msg", "!=", "last_msg", ":", "print", "(", "this_header", "+", "this_msg", ")", "last_msg", "=", "this_msg", "time", ".", "sleep", "(", "5", ")" ]
Simpler thread to track whether main thread has been quiet for long enough that a thread dump should be printed.
[ "Simpler", "thread", "to", "track", "whether", "main", "thread", "has", "been", "quiet", "for", "long", "enough", "that", "a", "thread", "dump", "should", "be", "printed", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_threads.py#L138-L172
8,435
ianmiell/shutit
package_map.py
map_package
def map_package(shutit_pexpect_session, package, install_type): """If package mapping exists, then return it, else return package. """ if package in PACKAGE_MAP.keys(): for itype in PACKAGE_MAP[package].keys(): if itype == install_type: ret = PACKAGE_MAP[package][install_type] if isinstance(ret,str): return ret if callable(ret): ret(shutit_pexpect_session) return '' # Otherwise, simply return package return package
python
def map_package(shutit_pexpect_session, package, install_type): """If package mapping exists, then return it, else return package. """ if package in PACKAGE_MAP.keys(): for itype in PACKAGE_MAP[package].keys(): if itype == install_type: ret = PACKAGE_MAP[package][install_type] if isinstance(ret,str): return ret if callable(ret): ret(shutit_pexpect_session) return '' # Otherwise, simply return package return package
[ "def", "map_package", "(", "shutit_pexpect_session", ",", "package", ",", "install_type", ")", ":", "if", "package", "in", "PACKAGE_MAP", ".", "keys", "(", ")", ":", "for", "itype", "in", "PACKAGE_MAP", "[", "package", "]", ".", "keys", "(", ")", ":", "if", "itype", "==", "install_type", ":", "ret", "=", "PACKAGE_MAP", "[", "package", "]", "[", "install_type", "]", "if", "isinstance", "(", "ret", ",", "str", ")", ":", "return", "ret", "if", "callable", "(", "ret", ")", ":", "ret", "(", "shutit_pexpect_session", ")", "return", "''", "# Otherwise, simply return package", "return", "package" ]
If package mapping exists, then return it, else return package.
[ "If", "package", "mapping", "exists", "then", "return", "it", "else", "return", "package", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/package_map.py#L135-L148
8,436
ianmiell/shutit
shutit_util.py
is_file_secure
def is_file_secure(file_name): """Returns false if file is considered insecure, true if secure. If file doesn't exist, it's considered secure! """ if not os.path.isfile(file_name): return True file_mode = os.stat(file_name).st_mode if file_mode & (stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH): return False return True
python
def is_file_secure(file_name): """Returns false if file is considered insecure, true if secure. If file doesn't exist, it's considered secure! """ if not os.path.isfile(file_name): return True file_mode = os.stat(file_name).st_mode if file_mode & (stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH): return False return True
[ "def", "is_file_secure", "(", "file_name", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "file_name", ")", ":", "return", "True", "file_mode", "=", "os", ".", "stat", "(", "file_name", ")", ".", "st_mode", "if", "file_mode", "&", "(", "stat", ".", "S_IRGRP", "|", "stat", ".", "S_IWGRP", "|", "stat", ".", "S_IXGRP", "|", "stat", ".", "S_IROTH", "|", "stat", ".", "S_IWOTH", "|", "stat", ".", "S_IXOTH", ")", ":", "return", "False", "return", "True" ]
Returns false if file is considered insecure, true if secure. If file doesn't exist, it's considered secure!
[ "Returns", "false", "if", "file", "is", "considered", "insecure", "true", "if", "secure", ".", "If", "file", "doesn", "t", "exist", "it", "s", "considered", "secure!" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_util.py#L57-L66
8,437
ianmiell/shutit
shutit_util.py
random_id
def random_id(size=8, chars=string.ascii_letters + string.digits): """Generates a random string of given size from the given chars. @param size: The size of the random string. @param chars: Constituent pool of characters to draw random characters from. @type size: number @type chars: string @rtype: string @return: The string of random characters. """ return ''.join(random.choice(chars) for _ in range(size))
python
def random_id(size=8, chars=string.ascii_letters + string.digits): """Generates a random string of given size from the given chars. @param size: The size of the random string. @param chars: Constituent pool of characters to draw random characters from. @type size: number @type chars: string @rtype: string @return: The string of random characters. """ return ''.join(random.choice(chars) for _ in range(size))
[ "def", "random_id", "(", "size", "=", "8", ",", "chars", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", ")", ":", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "chars", ")", "for", "_", "in", "range", "(", "size", ")", ")" ]
Generates a random string of given size from the given chars. @param size: The size of the random string. @param chars: Constituent pool of characters to draw random characters from. @type size: number @type chars: string @rtype: string @return: The string of random characters.
[ "Generates", "a", "random", "string", "of", "given", "size", "from", "the", "given", "chars", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_util.py#L82-L92
8,438
ianmiell/shutit
shutit_util.py
random_word
def random_word(size=6): """Returns a random word in lower case. """ words = shutit_assets.get_words().splitlines() word = '' while len(word) != size or "'" in word: word = words[int(random.random() * (len(words) - 1))] return word.lower()
python
def random_word(size=6): """Returns a random word in lower case. """ words = shutit_assets.get_words().splitlines() word = '' while len(word) != size or "'" in word: word = words[int(random.random() * (len(words) - 1))] return word.lower()
[ "def", "random_word", "(", "size", "=", "6", ")", ":", "words", "=", "shutit_assets", ".", "get_words", "(", ")", ".", "splitlines", "(", ")", "word", "=", "''", "while", "len", "(", "word", ")", "!=", "size", "or", "\"'\"", "in", "word", ":", "word", "=", "words", "[", "int", "(", "random", ".", "random", "(", ")", "*", "(", "len", "(", "words", ")", "-", "1", ")", ")", "]", "return", "word", ".", "lower", "(", ")" ]
Returns a random word in lower case.
[ "Returns", "a", "random", "word", "in", "lower", "case", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_util.py#L95-L102
8,439
ianmiell/shutit
shutit_util.py
ctrl_c_signal_handler
def ctrl_c_signal_handler(_, frame): """CTRL-c signal handler - enters a pause point if it can. """ global ctrl_c_calls ctrl_c_calls += 1 if ctrl_c_calls > 10: shutit_global.shutit_global_object.handle_exit(exit_code=1) shutit_frame = get_shutit_frame(frame) if in_ctrlc: msg = 'CTRL-C hit twice, quitting' if shutit_frame: shutit_global.shutit_global_object.shutit_print('\n') shutit = shutit_frame.f_locals['shutit'] shutit.log(msg,level=logging.CRITICAL) else: shutit_global.shutit_global_object.shutit_print(msg) shutit_global.shutit_global_object.handle_exit(exit_code=1) if shutit_frame: shutit = shutit_frame.f_locals['shutit'] if shutit.build['ctrlc_passthrough']: shutit.self.get_current_shutit_pexpect_session().pexpect_child.sendline(r'') return shutit_global.shutit_global_object.shutit_print(colorise(31,"\r" + r"You may need to wait for a command to complete before a pause point is available. Alternatively, CTRL-\ to quit.")) shutit.build['ctrlc_stop'] = True t = threading.Thread(target=ctrlc_background) t.daemon = True t.start() # Reset the ctrl-c calls ctrl_c_calls = 0 return shutit_global.shutit_global_object.shutit_print(colorise(31,'\n' + '*' * 80)) shutit_global.shutit_global_object.shutit_print(colorise(31,"CTRL-c caught, CTRL-c twice to quit.")) shutit_global.shutit_global_object.shutit_print(colorise(31,'*' * 80)) t = threading.Thread(target=ctrlc_background) t.daemon = True t.start() # Reset the ctrl-c calls ctrl_c_calls = 0
python
def ctrl_c_signal_handler(_, frame): """CTRL-c signal handler - enters a pause point if it can. """ global ctrl_c_calls ctrl_c_calls += 1 if ctrl_c_calls > 10: shutit_global.shutit_global_object.handle_exit(exit_code=1) shutit_frame = get_shutit_frame(frame) if in_ctrlc: msg = 'CTRL-C hit twice, quitting' if shutit_frame: shutit_global.shutit_global_object.shutit_print('\n') shutit = shutit_frame.f_locals['shutit'] shutit.log(msg,level=logging.CRITICAL) else: shutit_global.shutit_global_object.shutit_print(msg) shutit_global.shutit_global_object.handle_exit(exit_code=1) if shutit_frame: shutit = shutit_frame.f_locals['shutit'] if shutit.build['ctrlc_passthrough']: shutit.self.get_current_shutit_pexpect_session().pexpect_child.sendline(r'') return shutit_global.shutit_global_object.shutit_print(colorise(31,"\r" + r"You may need to wait for a command to complete before a pause point is available. Alternatively, CTRL-\ to quit.")) shutit.build['ctrlc_stop'] = True t = threading.Thread(target=ctrlc_background) t.daemon = True t.start() # Reset the ctrl-c calls ctrl_c_calls = 0 return shutit_global.shutit_global_object.shutit_print(colorise(31,'\n' + '*' * 80)) shutit_global.shutit_global_object.shutit_print(colorise(31,"CTRL-c caught, CTRL-c twice to quit.")) shutit_global.shutit_global_object.shutit_print(colorise(31,'*' * 80)) t = threading.Thread(target=ctrlc_background) t.daemon = True t.start() # Reset the ctrl-c calls ctrl_c_calls = 0
[ "def", "ctrl_c_signal_handler", "(", "_", ",", "frame", ")", ":", "global", "ctrl_c_calls", "ctrl_c_calls", "+=", "1", "if", "ctrl_c_calls", ">", "10", ":", "shutit_global", ".", "shutit_global_object", ".", "handle_exit", "(", "exit_code", "=", "1", ")", "shutit_frame", "=", "get_shutit_frame", "(", "frame", ")", "if", "in_ctrlc", ":", "msg", "=", "'CTRL-C hit twice, quitting'", "if", "shutit_frame", ":", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "'\\n'", ")", "shutit", "=", "shutit_frame", ".", "f_locals", "[", "'shutit'", "]", "shutit", ".", "log", "(", "msg", ",", "level", "=", "logging", ".", "CRITICAL", ")", "else", ":", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "msg", ")", "shutit_global", ".", "shutit_global_object", ".", "handle_exit", "(", "exit_code", "=", "1", ")", "if", "shutit_frame", ":", "shutit", "=", "shutit_frame", ".", "f_locals", "[", "'shutit'", "]", "if", "shutit", ".", "build", "[", "'ctrlc_passthrough'", "]", ":", "shutit", ".", "self", ".", "get_current_shutit_pexpect_session", "(", ")", ".", "pexpect_child", ".", "sendline", "(", "r'\u0003'", ")", "return", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "colorise", "(", "31", ",", "\"\\r\"", "+", "r\"You may need to wait for a command to complete before a pause point is available. Alternatively, CTRL-\\ to quit.\"", ")", ")", "shutit", ".", "build", "[", "'ctrlc_stop'", "]", "=", "True", "t", "=", "threading", ".", "Thread", "(", "target", "=", "ctrlc_background", ")", "t", ".", "daemon", "=", "True", "t", ".", "start", "(", ")", "# Reset the ctrl-c calls", "ctrl_c_calls", "=", "0", "return", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "colorise", "(", "31", ",", "'\\n'", "+", "'*'", "*", "80", ")", ")", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "colorise", "(", "31", ",", "\"CTRL-c caught, CTRL-c twice to quit.\"", ")", ")", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "colorise", "(", "31", ",", "'*'", "*", "80", ")", ")", "t", "=", "threading", ".", "Thread", "(", "target", "=", "ctrlc_background", ")", "t", ".", "daemon", "=", "True", "t", ".", "start", "(", ")", "# Reset the ctrl-c calls", "ctrl_c_calls", "=", "0" ]
CTRL-c signal handler - enters a pause point if it can.
[ "CTRL", "-", "c", "signal", "handler", "-", "enters", "a", "pause", "point", "if", "it", "can", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_util.py#L145-L182
8,440
ianmiell/shutit
shutit_util.py
get_input
def get_input(msg, default='', valid=None, boolean=False, ispass=False, color=None): """Gets input from the user, and returns the answer. @param msg: message to send to user @param default: default value if nothing entered @param valid: valid input values (default == empty list == anything allowed) @param boolean: whether return value should be boolean @param ispass: True if this is a password (ie whether to not echo input) @param color: Color code to colorize with (eg 32 = green) """ # switch off log tracing when in get_input log_trace_when_idle_original_value = shutit_global.shutit_global_object.log_trace_when_idle shutit_global.shutit_global_object.log_trace_when_idle = False if boolean and valid is None: valid = ('yes','y','Y','1','true','no','n','N','0','false') if color: answer = util_raw_input(prompt=colorise(color,msg),ispass=ispass) else: answer = util_raw_input(msg,ispass=ispass) if boolean and answer in ('', None) and default != '': # Revert log trace value to original shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return default if valid is not None: while answer not in valid: shutit_global.shutit_global_object.shutit_print('Answer must be one of: ' + str(valid),transient=True) if color: answer = util_raw_input(prompt=colorise(color,msg),ispass=ispass) else: answer = util_raw_input(msg,ispass=ispass) if boolean: if answer.lower() in ('yes','y','1','true','t'): # Revert log trace value to original shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return True elif answer.lower() in ('no','n','0','false','f'): # Revert log trace value to original shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return False # Revert log trace value to original shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return answer or default
python
def get_input(msg, default='', valid=None, boolean=False, ispass=False, color=None): """Gets input from the user, and returns the answer. @param msg: message to send to user @param default: default value if nothing entered @param valid: valid input values (default == empty list == anything allowed) @param boolean: whether return value should be boolean @param ispass: True if this is a password (ie whether to not echo input) @param color: Color code to colorize with (eg 32 = green) """ # switch off log tracing when in get_input log_trace_when_idle_original_value = shutit_global.shutit_global_object.log_trace_when_idle shutit_global.shutit_global_object.log_trace_when_idle = False if boolean and valid is None: valid = ('yes','y','Y','1','true','no','n','N','0','false') if color: answer = util_raw_input(prompt=colorise(color,msg),ispass=ispass) else: answer = util_raw_input(msg,ispass=ispass) if boolean and answer in ('', None) and default != '': # Revert log trace value to original shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return default if valid is not None: while answer not in valid: shutit_global.shutit_global_object.shutit_print('Answer must be one of: ' + str(valid),transient=True) if color: answer = util_raw_input(prompt=colorise(color,msg),ispass=ispass) else: answer = util_raw_input(msg,ispass=ispass) if boolean: if answer.lower() in ('yes','y','1','true','t'): # Revert log trace value to original shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return True elif answer.lower() in ('no','n','0','false','f'): # Revert log trace value to original shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return False # Revert log trace value to original shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return answer or default
[ "def", "get_input", "(", "msg", ",", "default", "=", "''", ",", "valid", "=", "None", ",", "boolean", "=", "False", ",", "ispass", "=", "False", ",", "color", "=", "None", ")", ":", "# switch off log tracing when in get_input", "log_trace_when_idle_original_value", "=", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "=", "False", "if", "boolean", "and", "valid", "is", "None", ":", "valid", "=", "(", "'yes'", ",", "'y'", ",", "'Y'", ",", "'1'", ",", "'true'", ",", "'no'", ",", "'n'", ",", "'N'", ",", "'0'", ",", "'false'", ")", "if", "color", ":", "answer", "=", "util_raw_input", "(", "prompt", "=", "colorise", "(", "color", ",", "msg", ")", ",", "ispass", "=", "ispass", ")", "else", ":", "answer", "=", "util_raw_input", "(", "msg", ",", "ispass", "=", "ispass", ")", "if", "boolean", "and", "answer", "in", "(", "''", ",", "None", ")", "and", "default", "!=", "''", ":", "# Revert log trace value to original", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "=", "log_trace_when_idle_original_value", "return", "default", "if", "valid", "is", "not", "None", ":", "while", "answer", "not", "in", "valid", ":", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "'Answer must be one of: '", "+", "str", "(", "valid", ")", ",", "transient", "=", "True", ")", "if", "color", ":", "answer", "=", "util_raw_input", "(", "prompt", "=", "colorise", "(", "color", ",", "msg", ")", ",", "ispass", "=", "ispass", ")", "else", ":", "answer", "=", "util_raw_input", "(", "msg", ",", "ispass", "=", "ispass", ")", "if", "boolean", ":", "if", "answer", ".", "lower", "(", ")", "in", "(", "'yes'", ",", "'y'", ",", "'1'", ",", "'true'", ",", "'t'", ")", ":", "# Revert log trace value to original", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "=", "log_trace_when_idle_original_value", "return", "True", "elif", "answer", ".", "lower", "(", ")", "in", "(", "'no'", ",", "'n'", ",", "'0'", ",", "'false'", ",", "'f'", ")", ":", "# Revert log trace value to original", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "=", "log_trace_when_idle_original_value", "return", "False", "# Revert log trace value to original", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "=", "log_trace_when_idle_original_value", "return", "answer", "or", "default" ]
Gets input from the user, and returns the answer. @param msg: message to send to user @param default: default value if nothing entered @param valid: valid input values (default == empty list == anything allowed) @param boolean: whether return value should be boolean @param ispass: True if this is a password (ie whether to not echo input) @param color: Color code to colorize with (eg 32 = green)
[ "Gets", "input", "from", "the", "user", "and", "returns", "the", "answer", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_util.py#L281-L322
8,441
ianmiell/shutit
shutit_setup.py
ConnDocker.build
def build(self, shutit): """Sets up the target ready for building. """ target_child = self.start_container(shutit, 'target_child') self.setup_host_child(shutit) # TODO: on the host child, check that the image running has bash as its cmd/entrypoint. self.setup_target_child(shutit, target_child) shutit.send('chmod -R 777 ' + shutit_global.shutit_global_object.shutit_state_dir + ' && mkdir -p ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/' + shutit_global.shutit_global_object.build_id, shutit_pexpect_child=target_child, echo=False) return True
python
def build(self, shutit): """Sets up the target ready for building. """ target_child = self.start_container(shutit, 'target_child') self.setup_host_child(shutit) # TODO: on the host child, check that the image running has bash as its cmd/entrypoint. self.setup_target_child(shutit, target_child) shutit.send('chmod -R 777 ' + shutit_global.shutit_global_object.shutit_state_dir + ' && mkdir -p ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/' + shutit_global.shutit_global_object.build_id, shutit_pexpect_child=target_child, echo=False) return True
[ "def", "build", "(", "self", ",", "shutit", ")", ":", "target_child", "=", "self", ".", "start_container", "(", "shutit", ",", "'target_child'", ")", "self", ".", "setup_host_child", "(", "shutit", ")", "# TODO: on the host child, check that the image running has bash as its cmd/entrypoint.", "self", ".", "setup_target_child", "(", "shutit", ",", "target_child", ")", "shutit", ".", "send", "(", "'chmod -R 777 '", "+", "shutit_global", ".", "shutit_global_object", ".", "shutit_state_dir", "+", "' && mkdir -p '", "+", "shutit_global", ".", "shutit_global_object", ".", "shutit_state_dir_build_db_dir", "+", "'/'", "+", "shutit_global", ".", "shutit_global_object", ".", "build_id", ",", "shutit_pexpect_child", "=", "target_child", ",", "echo", "=", "False", ")", "return", "True" ]
Sets up the target ready for building.
[ "Sets", "up", "the", "target", "ready", "for", "building", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_setup.py#L82-L90
8,442
ianmiell/shutit
shutit_setup.py
ConnBash.build
def build(self, shutit): """Sets up the machine ready for building. """ shutit_pexpect_session = ShutItPexpectSession(shutit, 'target_child','/bin/bash') target_child = shutit_pexpect_session.pexpect_child shutit_pexpect_session.expect(shutit_global.shutit_global_object.base_prompt.strip(), timeout=10) self.setup_host_child(shutit) self.setup_target_child(shutit, target_child) return True
python
def build(self, shutit): """Sets up the machine ready for building. """ shutit_pexpect_session = ShutItPexpectSession(shutit, 'target_child','/bin/bash') target_child = shutit_pexpect_session.pexpect_child shutit_pexpect_session.expect(shutit_global.shutit_global_object.base_prompt.strip(), timeout=10) self.setup_host_child(shutit) self.setup_target_child(shutit, target_child) return True
[ "def", "build", "(", "self", ",", "shutit", ")", ":", "shutit_pexpect_session", "=", "ShutItPexpectSession", "(", "shutit", ",", "'target_child'", ",", "'/bin/bash'", ")", "target_child", "=", "shutit_pexpect_session", ".", "pexpect_child", "shutit_pexpect_session", ".", "expect", "(", "shutit_global", ".", "shutit_global_object", ".", "base_prompt", ".", "strip", "(", ")", ",", "timeout", "=", "10", ")", "self", ".", "setup_host_child", "(", "shutit", ")", "self", ".", "setup_target_child", "(", "shutit", ",", "target_child", ")", "return", "True" ]
Sets up the machine ready for building.
[ "Sets", "up", "the", "machine", "ready", "for", "building", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_setup.py#L131-L139
8,443
ianmiell/shutit
shutit_setup.py
setup.build
def build(self, shutit): """Initializes target ready for build and updating package management if in container. """ if shutit.build['delivery'] in ('docker','dockerfile'): if shutit.get_current_shutit_pexpect_session_environment().install_type == 'apt': shutit.add_to_bashrc('export DEBIAN_FRONTEND=noninteractive') if not shutit.command_available('lsb_release'): shutit.install('lsb-release') shutit.lsb_release() elif shutit.get_current_shutit_pexpect_session_environment().install_type == 'yum': # yum updates are so often "bad" that we let exit codes of 1 through. # TODO: make this more sophisticated shutit.send('yum update -y', timeout=9999, exit_values=['0', '1']) shutit.pause_point('Anything you want to do to the target host ' + 'before the build starts?', level=2) return True
python
def build(self, shutit): """Initializes target ready for build and updating package management if in container. """ if shutit.build['delivery'] in ('docker','dockerfile'): if shutit.get_current_shutit_pexpect_session_environment().install_type == 'apt': shutit.add_to_bashrc('export DEBIAN_FRONTEND=noninteractive') if not shutit.command_available('lsb_release'): shutit.install('lsb-release') shutit.lsb_release() elif shutit.get_current_shutit_pexpect_session_environment().install_type == 'yum': # yum updates are so often "bad" that we let exit codes of 1 through. # TODO: make this more sophisticated shutit.send('yum update -y', timeout=9999, exit_values=['0', '1']) shutit.pause_point('Anything you want to do to the target host ' + 'before the build starts?', level=2) return True
[ "def", "build", "(", "self", ",", "shutit", ")", ":", "if", "shutit", ".", "build", "[", "'delivery'", "]", "in", "(", "'docker'", ",", "'dockerfile'", ")", ":", "if", "shutit", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "install_type", "==", "'apt'", ":", "shutit", ".", "add_to_bashrc", "(", "'export DEBIAN_FRONTEND=noninteractive'", ")", "if", "not", "shutit", ".", "command_available", "(", "'lsb_release'", ")", ":", "shutit", ".", "install", "(", "'lsb-release'", ")", "shutit", ".", "lsb_release", "(", ")", "elif", "shutit", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "install_type", "==", "'yum'", ":", "# yum updates are so often \"bad\" that we let exit codes of 1 through.", "# TODO: make this more sophisticated", "shutit", ".", "send", "(", "'yum update -y'", ",", "timeout", "=", "9999", ",", "exit_values", "=", "[", "'0'", ",", "'1'", "]", ")", "shutit", ".", "pause_point", "(", "'Anything you want to do to the target host '", "+", "'before the build starts?'", ",", "level", "=", "2", ")", "return", "True" ]
Initializes target ready for build and updating package management if in container.
[ "Initializes", "target", "ready", "for", "build", "and", "updating", "package", "management", "if", "in", "container", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_setup.py#L170-L184
8,444
ianmiell/shutit
emailer.py
Emailer.__set_config
def __set_config(self, cfg_section): """Set a local config array up according to defaults and main shutit configuration cfg_section - see __init__ """ defaults = [ 'shutit.core.alerting.emailer.mailto', None, 'shutit.core.alerting.emailer.mailfrom', 'angry@shutit.tk', 'shutit.core.alerting.emailer.smtp_server', 'localhost', 'shutit.core.alerting.emailer.smtp_port', 25, 'shutit.core.alerting.emailer.use_tls', True, 'shutit.core.alerting.emailer.send_mail', True, 'shutit.core.alerting.emailer.subject', 'Shutit Report', 'shutit.core.alerting.emailer.signature', '--Angry Shutit', 'shutit.core.alerting.emailer.compress', True, 'shutit.core.alerting.emailer.username', '', 'shutit.core.alerting.emailer.password', '', 'shutit.core.alerting.emailer.safe_mode', True, 'shutit.core.alerting.emailer.maintainer','', 'shutit.core.alerting.emailer.mailto_maintainer', True ] for cfg_name, cfg_default in zip(defaults[0::2], defaults[1::2]): try: self.config[cfg_name] = self.shutit.cfg[cfg_section][cfg_name] except KeyError: if cfg_default is None: raise Exception(cfg_section + ' ' + cfg_name + ' must be set') else: self.config[cfg_name] = cfg_default # only send a mail to the module's maintainer if configured correctly if self.config['shutit.core.alerting.emailer.mailto_maintainer'] and \ (self.config['shutit.core.alerting.emailer.maintainer'] == "" or \ self.config['shutit.core.alerting.emailer.maintainer'] == self.config['shutit.core.alerting.emailer.mailto']): self.config['shutit.core.alerting.emailer.mailto_maintainer'] = False self.config['shutit.core.alerting.emailer.maintainer'] = ""
python
def __set_config(self, cfg_section): """Set a local config array up according to defaults and main shutit configuration cfg_section - see __init__ """ defaults = [ 'shutit.core.alerting.emailer.mailto', None, 'shutit.core.alerting.emailer.mailfrom', 'angry@shutit.tk', 'shutit.core.alerting.emailer.smtp_server', 'localhost', 'shutit.core.alerting.emailer.smtp_port', 25, 'shutit.core.alerting.emailer.use_tls', True, 'shutit.core.alerting.emailer.send_mail', True, 'shutit.core.alerting.emailer.subject', 'Shutit Report', 'shutit.core.alerting.emailer.signature', '--Angry Shutit', 'shutit.core.alerting.emailer.compress', True, 'shutit.core.alerting.emailer.username', '', 'shutit.core.alerting.emailer.password', '', 'shutit.core.alerting.emailer.safe_mode', True, 'shutit.core.alerting.emailer.maintainer','', 'shutit.core.alerting.emailer.mailto_maintainer', True ] for cfg_name, cfg_default in zip(defaults[0::2], defaults[1::2]): try: self.config[cfg_name] = self.shutit.cfg[cfg_section][cfg_name] except KeyError: if cfg_default is None: raise Exception(cfg_section + ' ' + cfg_name + ' must be set') else: self.config[cfg_name] = cfg_default # only send a mail to the module's maintainer if configured correctly if self.config['shutit.core.alerting.emailer.mailto_maintainer'] and \ (self.config['shutit.core.alerting.emailer.maintainer'] == "" or \ self.config['shutit.core.alerting.emailer.maintainer'] == self.config['shutit.core.alerting.emailer.mailto']): self.config['shutit.core.alerting.emailer.mailto_maintainer'] = False self.config['shutit.core.alerting.emailer.maintainer'] = ""
[ "def", "__set_config", "(", "self", ",", "cfg_section", ")", ":", "defaults", "=", "[", "'shutit.core.alerting.emailer.mailto'", ",", "None", ",", "'shutit.core.alerting.emailer.mailfrom'", ",", "'angry@shutit.tk'", ",", "'shutit.core.alerting.emailer.smtp_server'", ",", "'localhost'", ",", "'shutit.core.alerting.emailer.smtp_port'", ",", "25", ",", "'shutit.core.alerting.emailer.use_tls'", ",", "True", ",", "'shutit.core.alerting.emailer.send_mail'", ",", "True", ",", "'shutit.core.alerting.emailer.subject'", ",", "'Shutit Report'", ",", "'shutit.core.alerting.emailer.signature'", ",", "'--Angry Shutit'", ",", "'shutit.core.alerting.emailer.compress'", ",", "True", ",", "'shutit.core.alerting.emailer.username'", ",", "''", ",", "'shutit.core.alerting.emailer.password'", ",", "''", ",", "'shutit.core.alerting.emailer.safe_mode'", ",", "True", ",", "'shutit.core.alerting.emailer.maintainer'", ",", "''", ",", "'shutit.core.alerting.emailer.mailto_maintainer'", ",", "True", "]", "for", "cfg_name", ",", "cfg_default", "in", "zip", "(", "defaults", "[", "0", ":", ":", "2", "]", ",", "defaults", "[", "1", ":", ":", "2", "]", ")", ":", "try", ":", "self", ".", "config", "[", "cfg_name", "]", "=", "self", ".", "shutit", ".", "cfg", "[", "cfg_section", "]", "[", "cfg_name", "]", "except", "KeyError", ":", "if", "cfg_default", "is", "None", ":", "raise", "Exception", "(", "cfg_section", "+", "' '", "+", "cfg_name", "+", "' must be set'", ")", "else", ":", "self", ".", "config", "[", "cfg_name", "]", "=", "cfg_default", "# only send a mail to the module's maintainer if configured correctly", "if", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailto_maintainer'", "]", "and", "(", "self", ".", "config", "[", "'shutit.core.alerting.emailer.maintainer'", "]", "==", "\"\"", "or", "self", ".", "config", "[", "'shutit.core.alerting.emailer.maintainer'", "]", "==", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailto'", "]", ")", ":", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailto_maintainer'", "]", "=", "False", "self", ".", "config", "[", "'shutit.core.alerting.emailer.maintainer'", "]", "=", "\"\"" ]
Set a local config array up according to defaults and main shutit configuration cfg_section - see __init__
[ "Set", "a", "local", "config", "array", "up", "according", "to", "defaults", "and", "main", "shutit", "configuration" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/emailer.py#L88-L125
8,445
ianmiell/shutit
emailer.py
Emailer.__get_smtp
def __get_smtp(self): """ Return the appropraite smtplib depending on wherther we're using TLS """ use_tls = self.config['shutit.core.alerting.emailer.use_tls'] if use_tls: smtp = SMTP(self.config['shutit.core.alerting.emailer.smtp_server'], self.config['shutit.core.alerting.emailer.smtp_port']) smtp.starttls() else: smtp = SMTP_SSL(self.config['shutit.core.alerting.emailer.smtp_server'], self.config['shutit.core.alerting.emailer.smtp_port']) return smtp
python
def __get_smtp(self): """ Return the appropraite smtplib depending on wherther we're using TLS """ use_tls = self.config['shutit.core.alerting.emailer.use_tls'] if use_tls: smtp = SMTP(self.config['shutit.core.alerting.emailer.smtp_server'], self.config['shutit.core.alerting.emailer.smtp_port']) smtp.starttls() else: smtp = SMTP_SSL(self.config['shutit.core.alerting.emailer.smtp_server'], self.config['shutit.core.alerting.emailer.smtp_port']) return smtp
[ "def", "__get_smtp", "(", "self", ")", ":", "use_tls", "=", "self", ".", "config", "[", "'shutit.core.alerting.emailer.use_tls'", "]", "if", "use_tls", ":", "smtp", "=", "SMTP", "(", "self", ".", "config", "[", "'shutit.core.alerting.emailer.smtp_server'", "]", ",", "self", ".", "config", "[", "'shutit.core.alerting.emailer.smtp_port'", "]", ")", "smtp", ".", "starttls", "(", ")", "else", ":", "smtp", "=", "SMTP_SSL", "(", "self", ".", "config", "[", "'shutit.core.alerting.emailer.smtp_server'", "]", ",", "self", ".", "config", "[", "'shutit.core.alerting.emailer.smtp_port'", "]", ")", "return", "smtp" ]
Return the appropraite smtplib depending on wherther we're using TLS
[ "Return", "the", "appropraite", "smtplib", "depending", "on", "wherther", "we", "re", "using", "TLS" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/emailer.py#L139-L148
8,446
ianmiell/shutit
emailer.py
Emailer.__compose
def __compose(self): """ Compose the message, pulling together body, attachments etc """ msg = MIMEMultipart() msg['Subject'] = self.config['shutit.core.alerting.emailer.subject'] msg['To'] = self.config['shutit.core.alerting.emailer.mailto'] msg['From'] = self.config['shutit.core.alerting.emailer.mailfrom'] # add the module's maintainer as a CC if configured if self.config['shutit.core.alerting.emailer.mailto_maintainer']: msg['Cc'] = self.config['shutit.core.alerting.emailer.maintainer'] if self.config['shutit.core.alerting.emailer.signature'] != '': signature = '\n\n' + self.config['shutit.core.alerting.emailer.signature'] else: signature = self.config['shutit.core.alerting.emailer.signature'] body = MIMEText('\n'.join(self.lines) + signature) msg.attach(body) for attach in self.attaches: msg.attach(attach) return msg
python
def __compose(self): """ Compose the message, pulling together body, attachments etc """ msg = MIMEMultipart() msg['Subject'] = self.config['shutit.core.alerting.emailer.subject'] msg['To'] = self.config['shutit.core.alerting.emailer.mailto'] msg['From'] = self.config['shutit.core.alerting.emailer.mailfrom'] # add the module's maintainer as a CC if configured if self.config['shutit.core.alerting.emailer.mailto_maintainer']: msg['Cc'] = self.config['shutit.core.alerting.emailer.maintainer'] if self.config['shutit.core.alerting.emailer.signature'] != '': signature = '\n\n' + self.config['shutit.core.alerting.emailer.signature'] else: signature = self.config['shutit.core.alerting.emailer.signature'] body = MIMEText('\n'.join(self.lines) + signature) msg.attach(body) for attach in self.attaches: msg.attach(attach) return msg
[ "def", "__compose", "(", "self", ")", ":", "msg", "=", "MIMEMultipart", "(", ")", "msg", "[", "'Subject'", "]", "=", "self", ".", "config", "[", "'shutit.core.alerting.emailer.subject'", "]", "msg", "[", "'To'", "]", "=", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailto'", "]", "msg", "[", "'From'", "]", "=", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailfrom'", "]", "# add the module's maintainer as a CC if configured", "if", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailto_maintainer'", "]", ":", "msg", "[", "'Cc'", "]", "=", "self", ".", "config", "[", "'shutit.core.alerting.emailer.maintainer'", "]", "if", "self", ".", "config", "[", "'shutit.core.alerting.emailer.signature'", "]", "!=", "''", ":", "signature", "=", "'\\n\\n'", "+", "self", ".", "config", "[", "'shutit.core.alerting.emailer.signature'", "]", "else", ":", "signature", "=", "self", ".", "config", "[", "'shutit.core.alerting.emailer.signature'", "]", "body", "=", "MIMEText", "(", "'\\n'", ".", "join", "(", "self", ".", "lines", ")", "+", "signature", ")", "msg", ".", "attach", "(", "body", ")", "for", "attach", "in", "self", ".", "attaches", ":", "msg", ".", "attach", "(", "attach", ")", "return", "msg" ]
Compose the message, pulling together body, attachments etc
[ "Compose", "the", "message", "pulling", "together", "body", "attachments", "etc" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/emailer.py#L180-L198
8,447
ianmiell/shutit
emailer.py
Emailer.send
def send(self, attachment_failure=False): """Send the email according to the configured setup attachment_failure - used to indicate a recursive call after the smtp server has refused based on file size. Should not be used externally """ if not self.config['shutit.core.alerting.emailer.send_mail']: self.shutit.log('emailer.send: Not configured to send mail!',level=logging.INFO) return True msg = self.__compose() mailto = [self.config['shutit.core.alerting.emailer.mailto']] smtp = self.__get_smtp() if self.config['shutit.core.alerting.emailer.username'] != '': smtp.login(self.config['shutit.core.alerting.emailer.username'], self.config['shutit.core.alerting.emailer.password']) if self.config['shutit.core.alerting.emailer.mailto_maintainer']: mailto.append(self.config['shutit.core.alerting.emailer.maintainer']) try: self.shutit.log('Attempting to send email',level=logging.INFO) smtp.sendmail(self.config['shutit.core.alerting.emailer.mailfrom'], mailto, msg.as_string()) except SMTPSenderRefused as refused: code = refused.args[0] if code == 552 and not attachment_failure: self.shutit.log("Mailserver rejected message due to " + "oversize attachments, attempting to resend without",level=logging.INFO) self.attaches = [] self.lines.append("Oversized attachments not sent") self.send(attachment_failure=True) else: self.shutit.log("Unhandled SMTP error:" + str(refused),level=logging.INFO) if not self.config['shutit.core.alerting.emailer.safe_mode']: raise refused except Exception as error: self.shutit.log('Unhandled exception: ' + str(error),level=logging.INFO) if not self.config['shutit.core.alerting.emailer.safe_mode']: raise error finally: smtp.quit()
python
def send(self, attachment_failure=False): """Send the email according to the configured setup attachment_failure - used to indicate a recursive call after the smtp server has refused based on file size. Should not be used externally """ if not self.config['shutit.core.alerting.emailer.send_mail']: self.shutit.log('emailer.send: Not configured to send mail!',level=logging.INFO) return True msg = self.__compose() mailto = [self.config['shutit.core.alerting.emailer.mailto']] smtp = self.__get_smtp() if self.config['shutit.core.alerting.emailer.username'] != '': smtp.login(self.config['shutit.core.alerting.emailer.username'], self.config['shutit.core.alerting.emailer.password']) if self.config['shutit.core.alerting.emailer.mailto_maintainer']: mailto.append(self.config['shutit.core.alerting.emailer.maintainer']) try: self.shutit.log('Attempting to send email',level=logging.INFO) smtp.sendmail(self.config['shutit.core.alerting.emailer.mailfrom'], mailto, msg.as_string()) except SMTPSenderRefused as refused: code = refused.args[0] if code == 552 and not attachment_failure: self.shutit.log("Mailserver rejected message due to " + "oversize attachments, attempting to resend without",level=logging.INFO) self.attaches = [] self.lines.append("Oversized attachments not sent") self.send(attachment_failure=True) else: self.shutit.log("Unhandled SMTP error:" + str(refused),level=logging.INFO) if not self.config['shutit.core.alerting.emailer.safe_mode']: raise refused except Exception as error: self.shutit.log('Unhandled exception: ' + str(error),level=logging.INFO) if not self.config['shutit.core.alerting.emailer.safe_mode']: raise error finally: smtp.quit()
[ "def", "send", "(", "self", ",", "attachment_failure", "=", "False", ")", ":", "if", "not", "self", ".", "config", "[", "'shutit.core.alerting.emailer.send_mail'", "]", ":", "self", ".", "shutit", ".", "log", "(", "'emailer.send: Not configured to send mail!'", ",", "level", "=", "logging", ".", "INFO", ")", "return", "True", "msg", "=", "self", ".", "__compose", "(", ")", "mailto", "=", "[", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailto'", "]", "]", "smtp", "=", "self", ".", "__get_smtp", "(", ")", "if", "self", ".", "config", "[", "'shutit.core.alerting.emailer.username'", "]", "!=", "''", ":", "smtp", ".", "login", "(", "self", ".", "config", "[", "'shutit.core.alerting.emailer.username'", "]", ",", "self", ".", "config", "[", "'shutit.core.alerting.emailer.password'", "]", ")", "if", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailto_maintainer'", "]", ":", "mailto", ".", "append", "(", "self", ".", "config", "[", "'shutit.core.alerting.emailer.maintainer'", "]", ")", "try", ":", "self", ".", "shutit", ".", "log", "(", "'Attempting to send email'", ",", "level", "=", "logging", ".", "INFO", ")", "smtp", ".", "sendmail", "(", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailfrom'", "]", ",", "mailto", ",", "msg", ".", "as_string", "(", ")", ")", "except", "SMTPSenderRefused", "as", "refused", ":", "code", "=", "refused", ".", "args", "[", "0", "]", "if", "code", "==", "552", "and", "not", "attachment_failure", ":", "self", ".", "shutit", ".", "log", "(", "\"Mailserver rejected message due to \"", "+", "\"oversize attachments, attempting to resend without\"", ",", "level", "=", "logging", ".", "INFO", ")", "self", ".", "attaches", "=", "[", "]", "self", ".", "lines", ".", "append", "(", "\"Oversized attachments not sent\"", ")", "self", ".", "send", "(", "attachment_failure", "=", "True", ")", "else", ":", "self", ".", "shutit", ".", "log", "(", "\"Unhandled SMTP error:\"", "+", "str", "(", "refused", ")", ",", "level", "=", "logging", ".", "INFO", ")", "if", "not", "self", ".", "config", "[", "'shutit.core.alerting.emailer.safe_mode'", "]", ":", "raise", "refused", "except", "Exception", "as", "error", ":", "self", ".", "shutit", ".", "log", "(", "'Unhandled exception: '", "+", "str", "(", "error", ")", ",", "level", "=", "logging", ".", "INFO", ")", "if", "not", "self", ".", "config", "[", "'shutit.core.alerting.emailer.safe_mode'", "]", ":", "raise", "error", "finally", ":", "smtp", ".", "quit", "(", ")" ]
Send the email according to the configured setup attachment_failure - used to indicate a recursive call after the smtp server has refused based on file size. Should not be used externally
[ "Send", "the", "email", "according", "to", "the", "configured", "setup" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/emailer.py#L200-L236
8,448
ianmiell/shutit
shutit_global.py
setup_signals
def setup_signals(): """Set up the signal handlers. """ signal.signal(signal.SIGINT, shutit_util.ctrl_c_signal_handler) signal.signal(signal.SIGQUIT, shutit_util.ctrl_quit_signal_handler)
python
def setup_signals(): """Set up the signal handlers. """ signal.signal(signal.SIGINT, shutit_util.ctrl_c_signal_handler) signal.signal(signal.SIGQUIT, shutit_util.ctrl_quit_signal_handler)
[ "def", "setup_signals", "(", ")", ":", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "shutit_util", ".", "ctrl_c_signal_handler", ")", "signal", ".", "signal", "(", "signal", ".", "SIGQUIT", ",", "shutit_util", ".", "ctrl_quit_signal_handler", ")" ]
Set up the signal handlers.
[ "Set", "up", "the", "signal", "handlers", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_global.py#L583-L587
8,449
ianmiell/shutit
shutit_global.py
get_shutit_pexpect_sessions
def get_shutit_pexpect_sessions(): """Returns all the shutit_pexpect sessions in existence. """ sessions = [] for shutit_object in shutit_global_object.shutit_objects: for key in shutit_object.shutit_pexpect_sessions: sessions.append(shutit_object.shutit_pexpect_sessions[key]) return sessions
python
def get_shutit_pexpect_sessions(): """Returns all the shutit_pexpect sessions in existence. """ sessions = [] for shutit_object in shutit_global_object.shutit_objects: for key in shutit_object.shutit_pexpect_sessions: sessions.append(shutit_object.shutit_pexpect_sessions[key]) return sessions
[ "def", "get_shutit_pexpect_sessions", "(", ")", ":", "sessions", "=", "[", "]", "for", "shutit_object", "in", "shutit_global_object", ".", "shutit_objects", ":", "for", "key", "in", "shutit_object", ".", "shutit_pexpect_sessions", ":", "sessions", ".", "append", "(", "shutit_object", ".", "shutit_pexpect_sessions", "[", "key", "]", ")", "return", "sessions" ]
Returns all the shutit_pexpect sessions in existence.
[ "Returns", "all", "the", "shutit_pexpect", "sessions", "in", "existence", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_global.py#L590-L597
8,450
ianmiell/shutit
shutit.py
main
def main(): """Main ShutIt function. Handles the configured actions: - skeleton - create skeleton module - list_configs - output computed configuration - depgraph - output digraph of module dependencies """ # Create base shutit object. shutit = shutit_global.shutit_global_object.shutit_objects[0] if sys.version_info[0] == 2: if sys.version_info[1] < 7: shutit.fail('Python version must be 2.7+') # pragma: no cover try: shutit.setup_shutit_obj() except KeyboardInterrupt: shutit_util.print_debug(sys.exc_info()) shutit_global.shutit_global_object.shutit_print('Keyboard interrupt caught, exiting with status 1') sys.exit(1)
python
def main(): """Main ShutIt function. Handles the configured actions: - skeleton - create skeleton module - list_configs - output computed configuration - depgraph - output digraph of module dependencies """ # Create base shutit object. shutit = shutit_global.shutit_global_object.shutit_objects[0] if sys.version_info[0] == 2: if sys.version_info[1] < 7: shutit.fail('Python version must be 2.7+') # pragma: no cover try: shutit.setup_shutit_obj() except KeyboardInterrupt: shutit_util.print_debug(sys.exc_info()) shutit_global.shutit_global_object.shutit_print('Keyboard interrupt caught, exiting with status 1') sys.exit(1)
[ "def", "main", "(", ")", ":", "# Create base shutit object.", "shutit", "=", "shutit_global", ".", "shutit_global_object", ".", "shutit_objects", "[", "0", "]", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", ":", "if", "sys", ".", "version_info", "[", "1", "]", "<", "7", ":", "shutit", ".", "fail", "(", "'Python version must be 2.7+'", ")", "# pragma: no cover", "try", ":", "shutit", ".", "setup_shutit_obj", "(", ")", "except", "KeyboardInterrupt", ":", "shutit_util", ".", "print_debug", "(", "sys", ".", "exc_info", "(", ")", ")", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "'Keyboard interrupt caught, exiting with status 1'", ")", "sys", ".", "exit", "(", "1", ")" ]
Main ShutIt function. Handles the configured actions: - skeleton - create skeleton module - list_configs - output computed configuration - depgraph - output digraph of module dependencies
[ "Main", "ShutIt", "function", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit.py#L133-L152
8,451
ianmiell/shutit
shutit_login_stack.py
ShutItLoginStackItem.has_blocking_background_send
def has_blocking_background_send(self): """Check whether any blocking background commands are waiting to run. If any are, return True. If none are, return False. """ for background_object in self.background_objects: # If it's running, or not started yet, it should block other tasks. if background_object.block_other_commands and background_object.run_state in ('S','N'): self.shutit_obj.log('All objects are: ' + str(self),level=logging.DEBUG) self.shutit_obj.log('The current blocking send object is: ' + str(background_object),level=logging.DEBUG) return True elif background_object.block_other_commands and background_object.run_state in ('F','C','T'): assert False, shutit_util.print_debug(msg='Blocking command should have been removed, in run_state: ' + background_object.run_state) else: assert background_object.block_other_commands is False, shutit_util.print_debug() return False
python
def has_blocking_background_send(self): """Check whether any blocking background commands are waiting to run. If any are, return True. If none are, return False. """ for background_object in self.background_objects: # If it's running, or not started yet, it should block other tasks. if background_object.block_other_commands and background_object.run_state in ('S','N'): self.shutit_obj.log('All objects are: ' + str(self),level=logging.DEBUG) self.shutit_obj.log('The current blocking send object is: ' + str(background_object),level=logging.DEBUG) return True elif background_object.block_other_commands and background_object.run_state in ('F','C','T'): assert False, shutit_util.print_debug(msg='Blocking command should have been removed, in run_state: ' + background_object.run_state) else: assert background_object.block_other_commands is False, shutit_util.print_debug() return False
[ "def", "has_blocking_background_send", "(", "self", ")", ":", "for", "background_object", "in", "self", ".", "background_objects", ":", "# If it's running, or not started yet, it should block other tasks.", "if", "background_object", ".", "block_other_commands", "and", "background_object", ".", "run_state", "in", "(", "'S'", ",", "'N'", ")", ":", "self", ".", "shutit_obj", ".", "log", "(", "'All objects are: '", "+", "str", "(", "self", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "shutit_obj", ".", "log", "(", "'The current blocking send object is: '", "+", "str", "(", "background_object", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "True", "elif", "background_object", ".", "block_other_commands", "and", "background_object", ".", "run_state", "in", "(", "'F'", ",", "'C'", ",", "'T'", ")", ":", "assert", "False", ",", "shutit_util", ".", "print_debug", "(", "msg", "=", "'Blocking command should have been removed, in run_state: '", "+", "background_object", ".", "run_state", ")", "else", ":", "assert", "background_object", ".", "block_other_commands", "is", "False", ",", "shutit_util", ".", "print_debug", "(", ")", "return", "False" ]
Check whether any blocking background commands are waiting to run. If any are, return True. If none are, return False.
[ "Check", "whether", "any", "blocking", "background", "commands", "are", "waiting", "to", "run", ".", "If", "any", "are", "return", "True", ".", "If", "none", "are", "return", "False", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_login_stack.py#L85-L99
8,452
ianmiell/shutit
shutit_login_stack.py
ShutItLoginStackItem.check_background_commands_complete
def check_background_commands_complete(self): """Check whether any background commands are running or to be run. If none are, return True. If any are, return False. """ unstarted_command_exists = False self.shutit_obj.log('In check_background_commands_complete: all background objects: ' + str(self.background_objects),level=logging.DEBUG) self.shutit_obj.log('Login id: ' + str(self.login_id),level=logging.DEBUG) for background_object in self.background_objects: self.shutit_obj.log('Background object send: ' + str(background_object.sendspec.send),level=logging.DEBUG) background_objects_to_remove = [] def remove_background_objects(a_background_objects_to_remove): for background_object in a_background_objects_to_remove: self.background_objects.remove(background_object) for background_object in self.background_objects: self.shutit_obj.log('Checking background object: ' + str(background_object),level=logging.DEBUG) state = background_object.check_background_command_state() self.shutit_obj.log('State is: ' + state,level=logging.DEBUG) if state in ('C','F','T'): background_objects_to_remove.append(background_object) self.background_objects_completed.append(background_object) elif state == 'S': # Running command exists self.shutit_obj.log('check_background_command_state returning False (S) for ' + str(background_object),level=logging.DEBUG) remove_background_objects(background_objects_to_remove) return False, 'S', background_object elif state == 'N': self.shutit_obj.log('UNSTARTED COMMAND! ' + str(background_object.sendspec.send),level=logging.DEBUG) unstarted_command_exists = True else: remove_background_objects(background_objects_to_remove) assert False, shutit_util.print_debug(msg='Un-handled: ' + state) if state == 'F': self.shutit_obj.log('check_background_command_state returning False (F) for ' + str(background_object),level=logging.DEBUG) remove_background_objects(background_objects_to_remove) return False, 'F', background_object remove_background_objects(background_objects_to_remove) self.shutit_obj.log('Checking background objects done.',level=logging.DEBUG) if unstarted_command_exists: # Start up an unstarted one (in order), and return False for background_object in self.background_objects: state = background_object.check_background_command_state() if state == 'N': background_object.run_background_command() self.shutit_obj.log('check_background_command_state returning False (N) for ' + str(background_object),level=logging.DEBUG) return False, 'N', background_object # Nothing left to do - return True. self.shutit_obj.log('check_background_command_state returning True (OK)',level=logging.DEBUG) return True, 'OK', None
python
def check_background_commands_complete(self): """Check whether any background commands are running or to be run. If none are, return True. If any are, return False. """ unstarted_command_exists = False self.shutit_obj.log('In check_background_commands_complete: all background objects: ' + str(self.background_objects),level=logging.DEBUG) self.shutit_obj.log('Login id: ' + str(self.login_id),level=logging.DEBUG) for background_object in self.background_objects: self.shutit_obj.log('Background object send: ' + str(background_object.sendspec.send),level=logging.DEBUG) background_objects_to_remove = [] def remove_background_objects(a_background_objects_to_remove): for background_object in a_background_objects_to_remove: self.background_objects.remove(background_object) for background_object in self.background_objects: self.shutit_obj.log('Checking background object: ' + str(background_object),level=logging.DEBUG) state = background_object.check_background_command_state() self.shutit_obj.log('State is: ' + state,level=logging.DEBUG) if state in ('C','F','T'): background_objects_to_remove.append(background_object) self.background_objects_completed.append(background_object) elif state == 'S': # Running command exists self.shutit_obj.log('check_background_command_state returning False (S) for ' + str(background_object),level=logging.DEBUG) remove_background_objects(background_objects_to_remove) return False, 'S', background_object elif state == 'N': self.shutit_obj.log('UNSTARTED COMMAND! ' + str(background_object.sendspec.send),level=logging.DEBUG) unstarted_command_exists = True else: remove_background_objects(background_objects_to_remove) assert False, shutit_util.print_debug(msg='Un-handled: ' + state) if state == 'F': self.shutit_obj.log('check_background_command_state returning False (F) for ' + str(background_object),level=logging.DEBUG) remove_background_objects(background_objects_to_remove) return False, 'F', background_object remove_background_objects(background_objects_to_remove) self.shutit_obj.log('Checking background objects done.',level=logging.DEBUG) if unstarted_command_exists: # Start up an unstarted one (in order), and return False for background_object in self.background_objects: state = background_object.check_background_command_state() if state == 'N': background_object.run_background_command() self.shutit_obj.log('check_background_command_state returning False (N) for ' + str(background_object),level=logging.DEBUG) return False, 'N', background_object # Nothing left to do - return True. self.shutit_obj.log('check_background_command_state returning True (OK)',level=logging.DEBUG) return True, 'OK', None
[ "def", "check_background_commands_complete", "(", "self", ")", ":", "unstarted_command_exists", "=", "False", "self", ".", "shutit_obj", ".", "log", "(", "'In check_background_commands_complete: all background objects: '", "+", "str", "(", "self", ".", "background_objects", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "shutit_obj", ".", "log", "(", "'Login id: '", "+", "str", "(", "self", ".", "login_id", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "for", "background_object", "in", "self", ".", "background_objects", ":", "self", ".", "shutit_obj", ".", "log", "(", "'Background object send: '", "+", "str", "(", "background_object", ".", "sendspec", ".", "send", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "background_objects_to_remove", "=", "[", "]", "def", "remove_background_objects", "(", "a_background_objects_to_remove", ")", ":", "for", "background_object", "in", "a_background_objects_to_remove", ":", "self", ".", "background_objects", ".", "remove", "(", "background_object", ")", "for", "background_object", "in", "self", ".", "background_objects", ":", "self", ".", "shutit_obj", ".", "log", "(", "'Checking background object: '", "+", "str", "(", "background_object", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "state", "=", "background_object", ".", "check_background_command_state", "(", ")", "self", ".", "shutit_obj", ".", "log", "(", "'State is: '", "+", "state", ",", "level", "=", "logging", ".", "DEBUG", ")", "if", "state", "in", "(", "'C'", ",", "'F'", ",", "'T'", ")", ":", "background_objects_to_remove", ".", "append", "(", "background_object", ")", "self", ".", "background_objects_completed", ".", "append", "(", "background_object", ")", "elif", "state", "==", "'S'", ":", "# Running command exists", "self", ".", "shutit_obj", ".", "log", "(", "'check_background_command_state returning False (S) for '", "+", "str", "(", "background_object", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "remove_background_objects", "(", "background_objects_to_remove", ")", "return", "False", ",", "'S'", ",", "background_object", "elif", "state", "==", "'N'", ":", "self", ".", "shutit_obj", ".", "log", "(", "'UNSTARTED COMMAND! '", "+", "str", "(", "background_object", ".", "sendspec", ".", "send", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "unstarted_command_exists", "=", "True", "else", ":", "remove_background_objects", "(", "background_objects_to_remove", ")", "assert", "False", ",", "shutit_util", ".", "print_debug", "(", "msg", "=", "'Un-handled: '", "+", "state", ")", "if", "state", "==", "'F'", ":", "self", ".", "shutit_obj", ".", "log", "(", "'check_background_command_state returning False (F) for '", "+", "str", "(", "background_object", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "remove_background_objects", "(", "background_objects_to_remove", ")", "return", "False", ",", "'F'", ",", "background_object", "remove_background_objects", "(", "background_objects_to_remove", ")", "self", ".", "shutit_obj", ".", "log", "(", "'Checking background objects done.'", ",", "level", "=", "logging", ".", "DEBUG", ")", "if", "unstarted_command_exists", ":", "# Start up an unstarted one (in order), and return False", "for", "background_object", "in", "self", ".", "background_objects", ":", "state", "=", "background_object", ".", "check_background_command_state", "(", ")", "if", "state", "==", "'N'", ":", "background_object", ".", "run_background_command", "(", ")", "self", ".", "shutit_obj", ".", "log", "(", "'check_background_command_state returning False (N) for '", "+", "str", "(", "background_object", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "False", ",", "'N'", ",", "background_object", "# Nothing left to do - return True.", "self", ".", "shutit_obj", ".", "log", "(", "'check_background_command_state returning True (OK)'", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "True", ",", "'OK'", ",", "None" ]
Check whether any background commands are running or to be run. If none are, return True. If any are, return False.
[ "Check", "whether", "any", "background", "commands", "are", "running", "or", "to", "be", "run", ".", "If", "none", "are", "return", "True", ".", "If", "any", "are", "return", "False", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_login_stack.py#L102-L149
8,453
konomae/lastpass-python
lastpass/vault.py
Vault.open_remote
def open_remote(cls, username, password, multifactor_password=None, client_id=None): """Fetches a blob from the server and creates a vault""" blob = cls.fetch_blob(username, password, multifactor_password, client_id) return cls.open(blob, username, password)
python
def open_remote(cls, username, password, multifactor_password=None, client_id=None): """Fetches a blob from the server and creates a vault""" blob = cls.fetch_blob(username, password, multifactor_password, client_id) return cls.open(blob, username, password)
[ "def", "open_remote", "(", "cls", ",", "username", ",", "password", ",", "multifactor_password", "=", "None", ",", "client_id", "=", "None", ")", ":", "blob", "=", "cls", ".", "fetch_blob", "(", "username", ",", "password", ",", "multifactor_password", ",", "client_id", ")", "return", "cls", ".", "open", "(", "blob", ",", "username", ",", "password", ")" ]
Fetches a blob from the server and creates a vault
[ "Fetches", "a", "blob", "from", "the", "server", "and", "creates", "a", "vault" ]
5063911b789868a1fd9db9922db82cdf156b938a
https://github.com/konomae/lastpass-python/blob/5063911b789868a1fd9db9922db82cdf156b938a/lastpass/vault.py#L9-L12
8,454
konomae/lastpass-python
lastpass/vault.py
Vault.open
def open(cls, blob, username, password): """Creates a vault from a blob object""" return cls(blob, blob.encryption_key(username, password))
python
def open(cls, blob, username, password): """Creates a vault from a blob object""" return cls(blob, blob.encryption_key(username, password))
[ "def", "open", "(", "cls", ",", "blob", ",", "username", ",", "password", ")", ":", "return", "cls", "(", "blob", ",", "blob", ".", "encryption_key", "(", "username", ",", "password", ")", ")" ]
Creates a vault from a blob object
[ "Creates", "a", "vault", "from", "a", "blob", "object" ]
5063911b789868a1fd9db9922db82cdf156b938a
https://github.com/konomae/lastpass-python/blob/5063911b789868a1fd9db9922db82cdf156b938a/lastpass/vault.py#L21-L23
8,455
konomae/lastpass-python
lastpass/vault.py
Vault.fetch_blob
def fetch_blob(cls, username, password, multifactor_password=None, client_id=None): """Just fetches the blob, could be used to store it locally""" session = fetcher.login(username, password, multifactor_password, client_id) blob = fetcher.fetch(session) fetcher.logout(session) return blob
python
def fetch_blob(cls, username, password, multifactor_password=None, client_id=None): """Just fetches the blob, could be used to store it locally""" session = fetcher.login(username, password, multifactor_password, client_id) blob = fetcher.fetch(session) fetcher.logout(session) return blob
[ "def", "fetch_blob", "(", "cls", ",", "username", ",", "password", ",", "multifactor_password", "=", "None", ",", "client_id", "=", "None", ")", ":", "session", "=", "fetcher", ".", "login", "(", "username", ",", "password", ",", "multifactor_password", ",", "client_id", ")", "blob", "=", "fetcher", ".", "fetch", "(", "session", ")", "fetcher", ".", "logout", "(", "session", ")", "return", "blob" ]
Just fetches the blob, could be used to store it locally
[ "Just", "fetches", "the", "blob", "could", "be", "used", "to", "store", "it", "locally" ]
5063911b789868a1fd9db9922db82cdf156b938a
https://github.com/konomae/lastpass-python/blob/5063911b789868a1fd9db9922db82cdf156b938a/lastpass/vault.py#L26-L32
8,456
konomae/lastpass-python
lastpass/parser.py
extract_chunks
def extract_chunks(blob): """Splits the blob into chucks grouped by kind.""" chunks = [] stream = BytesIO(blob.bytes) current_pos = stream.tell() stream.seek(0, 2) length = stream.tell() stream.seek(current_pos, 0) while stream.tell() < length: chunks.append(read_chunk(stream)) return chunks
python
def extract_chunks(blob): """Splits the blob into chucks grouped by kind.""" chunks = [] stream = BytesIO(blob.bytes) current_pos = stream.tell() stream.seek(0, 2) length = stream.tell() stream.seek(current_pos, 0) while stream.tell() < length: chunks.append(read_chunk(stream)) return chunks
[ "def", "extract_chunks", "(", "blob", ")", ":", "chunks", "=", "[", "]", "stream", "=", "BytesIO", "(", "blob", ".", "bytes", ")", "current_pos", "=", "stream", ".", "tell", "(", ")", "stream", ".", "seek", "(", "0", ",", "2", ")", "length", "=", "stream", ".", "tell", "(", ")", "stream", ".", "seek", "(", "current_pos", ",", "0", ")", "while", "stream", ".", "tell", "(", ")", "<", "length", ":", "chunks", ".", "append", "(", "read_chunk", "(", "stream", ")", ")", "return", "chunks" ]
Splits the blob into chucks grouped by kind.
[ "Splits", "the", "blob", "into", "chucks", "grouped", "by", "kind", "." ]
5063911b789868a1fd9db9922db82cdf156b938a
https://github.com/konomae/lastpass-python/blob/5063911b789868a1fd9db9922db82cdf156b938a/lastpass/parser.py#L26-L37
8,457
konomae/lastpass-python
lastpass/parser.py
parse_ACCT
def parse_ACCT(chunk, encryption_key): """ Parses an account chunk, decrypts and creates an Account object. May return nil when the chunk does not represent an account. All secure notes are ACCTs but not all of them strore account information. """ # TODO: Make a test case that covers secure note account io = BytesIO(chunk.payload) id = read_item(io) name = decode_aes256_plain_auto(read_item(io), encryption_key) group = decode_aes256_plain_auto(read_item(io), encryption_key) url = decode_hex(read_item(io)) notes = decode_aes256_plain_auto(read_item(io), encryption_key) skip_item(io, 2) username = decode_aes256_plain_auto(read_item(io), encryption_key) password = decode_aes256_plain_auto(read_item(io), encryption_key) skip_item(io, 2) secure_note = read_item(io) # Parse secure note if secure_note == b'1': parsed = parse_secure_note_server(notes) if parsed.get('type') in ALLOWED_SECURE_NOTE_TYPES: url = parsed.get('url', url) username = parsed.get('username', username) password = parsed.get('password', password) return Account(id, name, username, password, url, group, notes)
python
def parse_ACCT(chunk, encryption_key): """ Parses an account chunk, decrypts and creates an Account object. May return nil when the chunk does not represent an account. All secure notes are ACCTs but not all of them strore account information. """ # TODO: Make a test case that covers secure note account io = BytesIO(chunk.payload) id = read_item(io) name = decode_aes256_plain_auto(read_item(io), encryption_key) group = decode_aes256_plain_auto(read_item(io), encryption_key) url = decode_hex(read_item(io)) notes = decode_aes256_plain_auto(read_item(io), encryption_key) skip_item(io, 2) username = decode_aes256_plain_auto(read_item(io), encryption_key) password = decode_aes256_plain_auto(read_item(io), encryption_key) skip_item(io, 2) secure_note = read_item(io) # Parse secure note if secure_note == b'1': parsed = parse_secure_note_server(notes) if parsed.get('type') in ALLOWED_SECURE_NOTE_TYPES: url = parsed.get('url', url) username = parsed.get('username', username) password = parsed.get('password', password) return Account(id, name, username, password, url, group, notes)
[ "def", "parse_ACCT", "(", "chunk", ",", "encryption_key", ")", ":", "# TODO: Make a test case that covers secure note account", "io", "=", "BytesIO", "(", "chunk", ".", "payload", ")", "id", "=", "read_item", "(", "io", ")", "name", "=", "decode_aes256_plain_auto", "(", "read_item", "(", "io", ")", ",", "encryption_key", ")", "group", "=", "decode_aes256_plain_auto", "(", "read_item", "(", "io", ")", ",", "encryption_key", ")", "url", "=", "decode_hex", "(", "read_item", "(", "io", ")", ")", "notes", "=", "decode_aes256_plain_auto", "(", "read_item", "(", "io", ")", ",", "encryption_key", ")", "skip_item", "(", "io", ",", "2", ")", "username", "=", "decode_aes256_plain_auto", "(", "read_item", "(", "io", ")", ",", "encryption_key", ")", "password", "=", "decode_aes256_plain_auto", "(", "read_item", "(", "io", ")", ",", "encryption_key", ")", "skip_item", "(", "io", ",", "2", ")", "secure_note", "=", "read_item", "(", "io", ")", "# Parse secure note", "if", "secure_note", "==", "b'1'", ":", "parsed", "=", "parse_secure_note_server", "(", "notes", ")", "if", "parsed", ".", "get", "(", "'type'", ")", "in", "ALLOWED_SECURE_NOTE_TYPES", ":", "url", "=", "parsed", ".", "get", "(", "'url'", ",", "url", ")", "username", "=", "parsed", ".", "get", "(", "'username'", ",", "username", ")", "password", "=", "parsed", ".", "get", "(", "'password'", ",", "password", ")", "return", "Account", "(", "id", ",", "name", ",", "username", ",", "password", ",", "url", ",", "group", ",", "notes", ")" ]
Parses an account chunk, decrypts and creates an Account object. May return nil when the chunk does not represent an account. All secure notes are ACCTs but not all of them strore account information.
[ "Parses", "an", "account", "chunk", "decrypts", "and", "creates", "an", "Account", "object", ".", "May", "return", "nil", "when", "the", "chunk", "does", "not", "represent", "an", "account", ".", "All", "secure", "notes", "are", "ACCTs", "but", "not", "all", "of", "them", "strore", "account", "information", "." ]
5063911b789868a1fd9db9922db82cdf156b938a
https://github.com/konomae/lastpass-python/blob/5063911b789868a1fd9db9922db82cdf156b938a/lastpass/parser.py#L40-L70
8,458
konomae/lastpass-python
lastpass/parser.py
parse_PRIK
def parse_PRIK(chunk, encryption_key): """Parse PRIK chunk which contains private RSA key""" decrypted = decode_aes256('cbc', encryption_key[:16], decode_hex(chunk.payload), encryption_key) hex_key = re.match(br'^LastPassPrivateKey<(?P<hex_key>.*)>LastPassPrivateKey$', decrypted).group('hex_key') rsa_key = RSA.importKey(decode_hex(hex_key)) rsa_key.dmp1 = rsa_key.d % (rsa_key.p - 1) rsa_key.dmq1 = rsa_key.d % (rsa_key.q - 1) rsa_key.iqmp = number.inverse(rsa_key.q, rsa_key.p) return rsa_key
python
def parse_PRIK(chunk, encryption_key): """Parse PRIK chunk which contains private RSA key""" decrypted = decode_aes256('cbc', encryption_key[:16], decode_hex(chunk.payload), encryption_key) hex_key = re.match(br'^LastPassPrivateKey<(?P<hex_key>.*)>LastPassPrivateKey$', decrypted).group('hex_key') rsa_key = RSA.importKey(decode_hex(hex_key)) rsa_key.dmp1 = rsa_key.d % (rsa_key.p - 1) rsa_key.dmq1 = rsa_key.d % (rsa_key.q - 1) rsa_key.iqmp = number.inverse(rsa_key.q, rsa_key.p) return rsa_key
[ "def", "parse_PRIK", "(", "chunk", ",", "encryption_key", ")", ":", "decrypted", "=", "decode_aes256", "(", "'cbc'", ",", "encryption_key", "[", ":", "16", "]", ",", "decode_hex", "(", "chunk", ".", "payload", ")", ",", "encryption_key", ")", "hex_key", "=", "re", ".", "match", "(", "br'^LastPassPrivateKey<(?P<hex_key>.*)>LastPassPrivateKey$'", ",", "decrypted", ")", ".", "group", "(", "'hex_key'", ")", "rsa_key", "=", "RSA", ".", "importKey", "(", "decode_hex", "(", "hex_key", ")", ")", "rsa_key", ".", "dmp1", "=", "rsa_key", ".", "d", "%", "(", "rsa_key", ".", "p", "-", "1", ")", "rsa_key", ".", "dmq1", "=", "rsa_key", ".", "d", "%", "(", "rsa_key", ".", "q", "-", "1", ")", "rsa_key", ".", "iqmp", "=", "number", ".", "inverse", "(", "rsa_key", ".", "q", ",", "rsa_key", ".", "p", ")", "return", "rsa_key" ]
Parse PRIK chunk which contains private RSA key
[ "Parse", "PRIK", "chunk", "which", "contains", "private", "RSA", "key" ]
5063911b789868a1fd9db9922db82cdf156b938a
https://github.com/konomae/lastpass-python/blob/5063911b789868a1fd9db9922db82cdf156b938a/lastpass/parser.py#L73-L87
8,459
konomae/lastpass-python
lastpass/parser.py
decode_aes256_cbc_base64
def decode_aes256_cbc_base64(data, encryption_key): """Decrypts base64 encoded AES-256 CBC bytes.""" if not data: return b'' else: # LastPass AES-256/CBC/base64 encryted string starts with an "!". # Next 24 bytes are the base64 encoded IV for the cipher. # Then comes the "|". # And the rest is the base64 encoded encrypted payload. return decode_aes256( 'cbc', decode_base64(data[1:25]), decode_base64(data[26:]), encryption_key)
python
def decode_aes256_cbc_base64(data, encryption_key): """Decrypts base64 encoded AES-256 CBC bytes.""" if not data: return b'' else: # LastPass AES-256/CBC/base64 encryted string starts with an "!". # Next 24 bytes are the base64 encoded IV for the cipher. # Then comes the "|". # And the rest is the base64 encoded encrypted payload. return decode_aes256( 'cbc', decode_base64(data[1:25]), decode_base64(data[26:]), encryption_key)
[ "def", "decode_aes256_cbc_base64", "(", "data", ",", "encryption_key", ")", ":", "if", "not", "data", ":", "return", "b''", "else", ":", "# LastPass AES-256/CBC/base64 encryted string starts with an \"!\".", "# Next 24 bytes are the base64 encoded IV for the cipher.", "# Then comes the \"|\".", "# And the rest is the base64 encoded encrypted payload.", "return", "decode_aes256", "(", "'cbc'", ",", "decode_base64", "(", "data", "[", "1", ":", "25", "]", ")", ",", "decode_base64", "(", "data", "[", "26", ":", "]", ")", ",", "encryption_key", ")" ]
Decrypts base64 encoded AES-256 CBC bytes.
[ "Decrypts", "base64", "encoded", "AES", "-", "256", "CBC", "bytes", "." ]
5063911b789868a1fd9db9922db82cdf156b938a
https://github.com/konomae/lastpass-python/blob/5063911b789868a1fd9db9922db82cdf156b938a/lastpass/parser.py#L253-L266
8,460
ehuggett/send-cli
sendclient/delete.py
api_delete
def api_delete(service, file_id, owner_token): """Delete a file already uploaded to Send""" service += 'api/delete/%s' % file_id r = requests.post(service, json={'owner_token': owner_token, 'delete_token': owner_token}) r.raise_for_status() if r.text == 'OK': return True return False
python
def api_delete(service, file_id, owner_token): """Delete a file already uploaded to Send""" service += 'api/delete/%s' % file_id r = requests.post(service, json={'owner_token': owner_token, 'delete_token': owner_token}) r.raise_for_status() if r.text == 'OK': return True return False
[ "def", "api_delete", "(", "service", ",", "file_id", ",", "owner_token", ")", ":", "service", "+=", "'api/delete/%s'", "%", "file_id", "r", "=", "requests", ".", "post", "(", "service", ",", "json", "=", "{", "'owner_token'", ":", "owner_token", ",", "'delete_token'", ":", "owner_token", "}", ")", "r", ".", "raise_for_status", "(", ")", "if", "r", ".", "text", "==", "'OK'", ":", "return", "True", "return", "False" ]
Delete a file already uploaded to Send
[ "Delete", "a", "file", "already", "uploaded", "to", "Send" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/delete.py#L3-L11
8,461
ehuggett/send-cli
sendclient/params.py
api_params
def api_params(service, file_id, owner_token, download_limit): """Change the download limit for a file hosted on a Send Server""" service += 'api/params/%s' % file_id r = requests.post(service, json={'owner_token': owner_token, 'dlimit': download_limit}) r.raise_for_status() if r.text == 'OK': return True return False
python
def api_params(service, file_id, owner_token, download_limit): """Change the download limit for a file hosted on a Send Server""" service += 'api/params/%s' % file_id r = requests.post(service, json={'owner_token': owner_token, 'dlimit': download_limit}) r.raise_for_status() if r.text == 'OK': return True return False
[ "def", "api_params", "(", "service", ",", "file_id", ",", "owner_token", ",", "download_limit", ")", ":", "service", "+=", "'api/params/%s'", "%", "file_id", "r", "=", "requests", ".", "post", "(", "service", ",", "json", "=", "{", "'owner_token'", ":", "owner_token", ",", "'dlimit'", ":", "download_limit", "}", ")", "r", ".", "raise_for_status", "(", ")", "if", "r", ".", "text", "==", "'OK'", ":", "return", "True", "return", "False" ]
Change the download limit for a file hosted on a Send Server
[ "Change", "the", "download", "limit", "for", "a", "file", "hosted", "on", "a", "Send", "Server" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/params.py#L3-L11
8,462
ehuggett/send-cli
sendclient/download.py
api_download
def api_download(service, fileId, authorisation): '''Given a Send url, download and return the encrypted data and metadata''' data = tempfile.SpooledTemporaryFile(max_size=SPOOL_SIZE, mode='w+b') headers = {'Authorization' : 'send-v1 ' + unpadded_urlsafe_b64encode(authorisation)} url = service + 'api/download/' + fileId r = requests.get(url, headers=headers, stream=True) r.raise_for_status() content_length = int(r.headers['Content-length']) pbar = progbar(content_length) for chunk in r.iter_content(chunk_size=CHUNK_SIZE): data.write(chunk) pbar.update(len(chunk)) pbar.close() data.seek(0) return data
python
def api_download(service, fileId, authorisation): '''Given a Send url, download and return the encrypted data and metadata''' data = tempfile.SpooledTemporaryFile(max_size=SPOOL_SIZE, mode='w+b') headers = {'Authorization' : 'send-v1 ' + unpadded_urlsafe_b64encode(authorisation)} url = service + 'api/download/' + fileId r = requests.get(url, headers=headers, stream=True) r.raise_for_status() content_length = int(r.headers['Content-length']) pbar = progbar(content_length) for chunk in r.iter_content(chunk_size=CHUNK_SIZE): data.write(chunk) pbar.update(len(chunk)) pbar.close() data.seek(0) return data
[ "def", "api_download", "(", "service", ",", "fileId", ",", "authorisation", ")", ":", "data", "=", "tempfile", ".", "SpooledTemporaryFile", "(", "max_size", "=", "SPOOL_SIZE", ",", "mode", "=", "'w+b'", ")", "headers", "=", "{", "'Authorization'", ":", "'send-v1 '", "+", "unpadded_urlsafe_b64encode", "(", "authorisation", ")", "}", "url", "=", "service", "+", "'api/download/'", "+", "fileId", "r", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "headers", ",", "stream", "=", "True", ")", "r", ".", "raise_for_status", "(", ")", "content_length", "=", "int", "(", "r", ".", "headers", "[", "'Content-length'", "]", ")", "pbar", "=", "progbar", "(", "content_length", ")", "for", "chunk", "in", "r", ".", "iter_content", "(", "chunk_size", "=", "CHUNK_SIZE", ")", ":", "data", ".", "write", "(", "chunk", ")", "pbar", ".", "update", "(", "len", "(", "chunk", ")", ")", "pbar", ".", "close", "(", ")", "data", ".", "seek", "(", "0", ")", "return", "data" ]
Given a Send url, download and return the encrypted data and metadata
[ "Given", "a", "Send", "url", "download", "and", "return", "the", "encrypted", "data", "and", "metadata" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/download.py#L13-L31
8,463
ehuggett/send-cli
sendclient/download.py
decrypt_filedata
def decrypt_filedata(data, keys): '''Decrypts a file from Send''' # The last 16 bytes / 128 bits of data is the GCM tag # https://www.w3.org/TR/WebCryptoAPI/#aes-gcm-operations :- # 7. Let ciphertext be equal to C | T, where '|' denotes concatenation. data.seek(-16, 2) tag = data.read() # now truncate the file to only contain encrypted data data.seek(-16, 2) data.truncate() data.seek(0) plain = tempfile.NamedTemporaryFile(mode='w+b', delete=False) pbar = progbar(fileSize(data)) obj = Cryptodome.Cipher.AES.new(keys.encryptKey, Cryptodome.Cipher.AES.MODE_GCM, keys.encryptIV) prev_chunk = b'' for chunk in iter(lambda: data.read(CHUNK_SIZE), b''): plain.write(obj.decrypt(prev_chunk)) pbar.update(len(chunk)) prev_chunk = chunk plain.write(obj.decrypt_and_verify(prev_chunk, tag)) data.close() pbar.close() plain.seek(0) return plain
python
def decrypt_filedata(data, keys): '''Decrypts a file from Send''' # The last 16 bytes / 128 bits of data is the GCM tag # https://www.w3.org/TR/WebCryptoAPI/#aes-gcm-operations :- # 7. Let ciphertext be equal to C | T, where '|' denotes concatenation. data.seek(-16, 2) tag = data.read() # now truncate the file to only contain encrypted data data.seek(-16, 2) data.truncate() data.seek(0) plain = tempfile.NamedTemporaryFile(mode='w+b', delete=False) pbar = progbar(fileSize(data)) obj = Cryptodome.Cipher.AES.new(keys.encryptKey, Cryptodome.Cipher.AES.MODE_GCM, keys.encryptIV) prev_chunk = b'' for chunk in iter(lambda: data.read(CHUNK_SIZE), b''): plain.write(obj.decrypt(prev_chunk)) pbar.update(len(chunk)) prev_chunk = chunk plain.write(obj.decrypt_and_verify(prev_chunk, tag)) data.close() pbar.close() plain.seek(0) return plain
[ "def", "decrypt_filedata", "(", "data", ",", "keys", ")", ":", "# The last 16 bytes / 128 bits of data is the GCM tag", "# https://www.w3.org/TR/WebCryptoAPI/#aes-gcm-operations :-", "# 7. Let ciphertext be equal to C | T, where '|' denotes concatenation.", "data", ".", "seek", "(", "-", "16", ",", "2", ")", "tag", "=", "data", ".", "read", "(", ")", "# now truncate the file to only contain encrypted data", "data", ".", "seek", "(", "-", "16", ",", "2", ")", "data", ".", "truncate", "(", ")", "data", ".", "seek", "(", "0", ")", "plain", "=", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "'w+b'", ",", "delete", "=", "False", ")", "pbar", "=", "progbar", "(", "fileSize", "(", "data", ")", ")", "obj", "=", "Cryptodome", ".", "Cipher", ".", "AES", ".", "new", "(", "keys", ".", "encryptKey", ",", "Cryptodome", ".", "Cipher", ".", "AES", ".", "MODE_GCM", ",", "keys", ".", "encryptIV", ")", "prev_chunk", "=", "b''", "for", "chunk", "in", "iter", "(", "lambda", ":", "data", ".", "read", "(", "CHUNK_SIZE", ")", ",", "b''", ")", ":", "plain", ".", "write", "(", "obj", ".", "decrypt", "(", "prev_chunk", ")", ")", "pbar", ".", "update", "(", "len", "(", "chunk", ")", ")", "prev_chunk", "=", "chunk", "plain", ".", "write", "(", "obj", ".", "decrypt_and_verify", "(", "prev_chunk", ",", "tag", ")", ")", "data", ".", "close", "(", ")", "pbar", ".", "close", "(", ")", "plain", ".", "seek", "(", "0", ")", "return", "plain" ]
Decrypts a file from Send
[ "Decrypts", "a", "file", "from", "Send" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/download.py#L33-L62
8,464
ehuggett/send-cli
sendclient/download.py
sign_nonce
def sign_nonce(key, nonce): ''' sign the server nonce from the WWW-Authenticate header with an authKey''' # HMAC.new(key, msg='', digestmod=None) return Cryptodome.Hash.HMAC.new(key, nonce, digestmod=Cryptodome.Hash.SHA256).digest()
python
def sign_nonce(key, nonce): ''' sign the server nonce from the WWW-Authenticate header with an authKey''' # HMAC.new(key, msg='', digestmod=None) return Cryptodome.Hash.HMAC.new(key, nonce, digestmod=Cryptodome.Hash.SHA256).digest()
[ "def", "sign_nonce", "(", "key", ",", "nonce", ")", ":", "# HMAC.new(key, msg='', digestmod=None)", "return", "Cryptodome", ".", "Hash", ".", "HMAC", ".", "new", "(", "key", ",", "nonce", ",", "digestmod", "=", "Cryptodome", ".", "Hash", ".", "SHA256", ")", ".", "digest", "(", ")" ]
sign the server nonce from the WWW-Authenticate header with an authKey
[ "sign", "the", "server", "nonce", "from", "the", "WWW", "-", "Authenticate", "header", "with", "an", "authKey" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/download.py#L95-L98
8,465
ehuggett/send-cli
sendclient/password.py
api_password
def api_password(service, fileId , ownerToken, newAuthKey): ''' changes the authKey required to download a file hosted on a send server ''' service += 'api/password/%s' % fileId auth = sendclient.common.unpadded_urlsafe_b64encode(newAuthKey) r = requests.post(service, json={'owner_token': ownerToken, 'auth': auth}) r.raise_for_status() if r.text == 'OK': return True return False
python
def api_password(service, fileId , ownerToken, newAuthKey): ''' changes the authKey required to download a file hosted on a send server ''' service += 'api/password/%s' % fileId auth = sendclient.common.unpadded_urlsafe_b64encode(newAuthKey) r = requests.post(service, json={'owner_token': ownerToken, 'auth': auth}) r.raise_for_status() if r.text == 'OK': return True return False
[ "def", "api_password", "(", "service", ",", "fileId", ",", "ownerToken", ",", "newAuthKey", ")", ":", "service", "+=", "'api/password/%s'", "%", "fileId", "auth", "=", "sendclient", ".", "common", ".", "unpadded_urlsafe_b64encode", "(", "newAuthKey", ")", "r", "=", "requests", ".", "post", "(", "service", ",", "json", "=", "{", "'owner_token'", ":", "ownerToken", ",", "'auth'", ":", "auth", "}", ")", "r", ".", "raise_for_status", "(", ")", "if", "r", ".", "text", "==", "'OK'", ":", "return", "True", "return", "False" ]
changes the authKey required to download a file hosted on a send server
[ "changes", "the", "authKey", "required", "to", "download", "a", "file", "hosted", "on", "a", "send", "server" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/password.py#L4-L16
8,466
ehuggett/send-cli
sendclient/password.py
set_password
def set_password(url, ownerToken, password): ''' set or change the password required to download a file hosted on a send server. ''' service, fileId, key = sendclient.common.splitkeyurl(url) rawKey = sendclient.common.unpadded_urlsafe_b64decode(key) keys = sendclient.common.secretKeys(rawKey, password, url) return api_password(service, fileId, ownerToken, keys.newAuthKey)
python
def set_password(url, ownerToken, password): ''' set or change the password required to download a file hosted on a send server. ''' service, fileId, key = sendclient.common.splitkeyurl(url) rawKey = sendclient.common.unpadded_urlsafe_b64decode(key) keys = sendclient.common.secretKeys(rawKey, password, url) return api_password(service, fileId, ownerToken, keys.newAuthKey)
[ "def", "set_password", "(", "url", ",", "ownerToken", ",", "password", ")", ":", "service", ",", "fileId", ",", "key", "=", "sendclient", ".", "common", ".", "splitkeyurl", "(", "url", ")", "rawKey", "=", "sendclient", ".", "common", ".", "unpadded_urlsafe_b64decode", "(", "key", ")", "keys", "=", "sendclient", ".", "common", ".", "secretKeys", "(", "rawKey", ",", "password", ",", "url", ")", "return", "api_password", "(", "service", ",", "fileId", ",", "ownerToken", ",", "keys", ".", "newAuthKey", ")" ]
set or change the password required to download a file hosted on a send server.
[ "set", "or", "change", "the", "password", "required", "to", "download", "a", "file", "hosted", "on", "a", "send", "server", "." ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/password.py#L18-L27
8,467
ehuggett/send-cli
sendclient/common.py
splitkeyurl
def splitkeyurl(url): ''' Splits a Send url into key, urlid and 'prefix' for the Send server Should handle any hostname, but will brake on key & id length changes ''' key = url[-22:] urlid = url[-34:-24] service = url[:-43] return service, urlid, key
python
def splitkeyurl(url): ''' Splits a Send url into key, urlid and 'prefix' for the Send server Should handle any hostname, but will brake on key & id length changes ''' key = url[-22:] urlid = url[-34:-24] service = url[:-43] return service, urlid, key
[ "def", "splitkeyurl", "(", "url", ")", ":", "key", "=", "url", "[", "-", "22", ":", "]", "urlid", "=", "url", "[", "-", "34", ":", "-", "24", "]", "service", "=", "url", "[", ":", "-", "43", "]", "return", "service", ",", "urlid", ",", "key" ]
Splits a Send url into key, urlid and 'prefix' for the Send server Should handle any hostname, but will brake on key & id length changes
[ "Splits", "a", "Send", "url", "into", "key", "urlid", "and", "prefix", "for", "the", "Send", "server", "Should", "handle", "any", "hostname", "but", "will", "brake", "on", "key", "&", "id", "length", "changes" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/common.py#L9-L17
8,468
ehuggett/send-cli
sendclient/upload.py
api_upload
def api_upload(service, encData, encMeta, keys): ''' Uploads data to Send. Caution! Data is uploaded as given, this function will not encrypt it for you ''' service += 'api/upload' files = requests_toolbelt.MultipartEncoder(fields={'file': ('blob', encData, 'application/octet-stream') }) pbar = progbar(files.len) monitor = requests_toolbelt.MultipartEncoderMonitor(files, lambda files: pbar.update(monitor.bytes_read - pbar.n)) headers = { 'X-File-Metadata' : unpadded_urlsafe_b64encode(encMeta), 'Authorization' : 'send-v1 ' + unpadded_urlsafe_b64encode(keys.authKey), 'Content-type' : monitor.content_type } r = requests.post(service, data=monitor, headers=headers, stream=True) r.raise_for_status() pbar.close() body_json = r.json() secretUrl = body_json['url'] + '#' + unpadded_urlsafe_b64encode(keys.secretKey) fileId = body_json['id'] fileNonce = unpadded_urlsafe_b64decode(r.headers['WWW-Authenticate'].replace('send-v1 ', '')) try: owner_token = body_json['owner'] except: owner_token = body_json['delete'] return secretUrl, fileId, fileNonce, owner_token
python
def api_upload(service, encData, encMeta, keys): ''' Uploads data to Send. Caution! Data is uploaded as given, this function will not encrypt it for you ''' service += 'api/upload' files = requests_toolbelt.MultipartEncoder(fields={'file': ('blob', encData, 'application/octet-stream') }) pbar = progbar(files.len) monitor = requests_toolbelt.MultipartEncoderMonitor(files, lambda files: pbar.update(monitor.bytes_read - pbar.n)) headers = { 'X-File-Metadata' : unpadded_urlsafe_b64encode(encMeta), 'Authorization' : 'send-v1 ' + unpadded_urlsafe_b64encode(keys.authKey), 'Content-type' : monitor.content_type } r = requests.post(service, data=monitor, headers=headers, stream=True) r.raise_for_status() pbar.close() body_json = r.json() secretUrl = body_json['url'] + '#' + unpadded_urlsafe_b64encode(keys.secretKey) fileId = body_json['id'] fileNonce = unpadded_urlsafe_b64decode(r.headers['WWW-Authenticate'].replace('send-v1 ', '')) try: owner_token = body_json['owner'] except: owner_token = body_json['delete'] return secretUrl, fileId, fileNonce, owner_token
[ "def", "api_upload", "(", "service", ",", "encData", ",", "encMeta", ",", "keys", ")", ":", "service", "+=", "'api/upload'", "files", "=", "requests_toolbelt", ".", "MultipartEncoder", "(", "fields", "=", "{", "'file'", ":", "(", "'blob'", ",", "encData", ",", "'application/octet-stream'", ")", "}", ")", "pbar", "=", "progbar", "(", "files", ".", "len", ")", "monitor", "=", "requests_toolbelt", ".", "MultipartEncoderMonitor", "(", "files", ",", "lambda", "files", ":", "pbar", ".", "update", "(", "monitor", ".", "bytes_read", "-", "pbar", ".", "n", ")", ")", "headers", "=", "{", "'X-File-Metadata'", ":", "unpadded_urlsafe_b64encode", "(", "encMeta", ")", ",", "'Authorization'", ":", "'send-v1 '", "+", "unpadded_urlsafe_b64encode", "(", "keys", ".", "authKey", ")", ",", "'Content-type'", ":", "monitor", ".", "content_type", "}", "r", "=", "requests", ".", "post", "(", "service", ",", "data", "=", "monitor", ",", "headers", "=", "headers", ",", "stream", "=", "True", ")", "r", ".", "raise_for_status", "(", ")", "pbar", ".", "close", "(", ")", "body_json", "=", "r", ".", "json", "(", ")", "secretUrl", "=", "body_json", "[", "'url'", "]", "+", "'#'", "+", "unpadded_urlsafe_b64encode", "(", "keys", ".", "secretKey", ")", "fileId", "=", "body_json", "[", "'id'", "]", "fileNonce", "=", "unpadded_urlsafe_b64decode", "(", "r", ".", "headers", "[", "'WWW-Authenticate'", "]", ".", "replace", "(", "'send-v1 '", ",", "''", ")", ")", "try", ":", "owner_token", "=", "body_json", "[", "'owner'", "]", "except", ":", "owner_token", "=", "body_json", "[", "'delete'", "]", "return", "secretUrl", ",", "fileId", ",", "fileNonce", ",", "owner_token" ]
Uploads data to Send. Caution! Data is uploaded as given, this function will not encrypt it for you
[ "Uploads", "data", "to", "Send", ".", "Caution!", "Data", "is", "uploaded", "as", "given", "this", "function", "will", "not", "encrypt", "it", "for", "you" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/upload.py#L45-L73
8,469
ehuggett/send-cli
sendclient/upload.py
send_file
def send_file(service, file, fileName=None, password=None, ignoreVersion=False): if checkServerVersion(service, ignoreVersion=ignoreVersion) == False: print('\033[1;41m!!! Potentially incompatible server version !!!\033[0m') ''' Encrypt & Upload a file to send and return the download URL''' fileName = fileName if fileName != None else os.path.basename(file.name) print('Encrypting data from "' + fileName + '"') keys = secretKeys() encData = encrypt_file(file, keys) encMeta = encrypt_metadata(keys, fileName) print('Uploading "' + fileName + '"') secretUrl, fileId, fileNonce, owner_token = api_upload(service, encData, encMeta, keys) if password != None: print('Setting password') sendclient.password.set_password(secretUrl, owner_token, password) return secretUrl, fileId, owner_token
python
def send_file(service, file, fileName=None, password=None, ignoreVersion=False): if checkServerVersion(service, ignoreVersion=ignoreVersion) == False: print('\033[1;41m!!! Potentially incompatible server version !!!\033[0m') ''' Encrypt & Upload a file to send and return the download URL''' fileName = fileName if fileName != None else os.path.basename(file.name) print('Encrypting data from "' + fileName + '"') keys = secretKeys() encData = encrypt_file(file, keys) encMeta = encrypt_metadata(keys, fileName) print('Uploading "' + fileName + '"') secretUrl, fileId, fileNonce, owner_token = api_upload(service, encData, encMeta, keys) if password != None: print('Setting password') sendclient.password.set_password(secretUrl, owner_token, password) return secretUrl, fileId, owner_token
[ "def", "send_file", "(", "service", ",", "file", ",", "fileName", "=", "None", ",", "password", "=", "None", ",", "ignoreVersion", "=", "False", ")", ":", "if", "checkServerVersion", "(", "service", ",", "ignoreVersion", "=", "ignoreVersion", ")", "==", "False", ":", "print", "(", "'\\033[1;41m!!! Potentially incompatible server version !!!\\033[0m'", ")", "fileName", "=", "fileName", "if", "fileName", "!=", "None", "else", "os", ".", "path", ".", "basename", "(", "file", ".", "name", ")", "print", "(", "'Encrypting data from \"'", "+", "fileName", "+", "'\"'", ")", "keys", "=", "secretKeys", "(", ")", "encData", "=", "encrypt_file", "(", "file", ",", "keys", ")", "encMeta", "=", "encrypt_metadata", "(", "keys", ",", "fileName", ")", "print", "(", "'Uploading \"'", "+", "fileName", "+", "'\"'", ")", "secretUrl", ",", "fileId", ",", "fileNonce", ",", "owner_token", "=", "api_upload", "(", "service", ",", "encData", ",", "encMeta", ",", "keys", ")", "if", "password", "!=", "None", ":", "print", "(", "'Setting password'", ")", "sendclient", ".", "password", ".", "set_password", "(", "secretUrl", ",", "owner_token", ",", "password", ")", "return", "secretUrl", ",", "fileId", ",", "owner_token" ]
Encrypt & Upload a file to send and return the download URL
[ "Encrypt", "&", "Upload", "a", "file", "to", "send", "and", "return", "the", "download", "URL" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/upload.py#L80-L100
8,470
haochi/personalcapital
personalcapital/personalcapital.py
PersonalCapital.fetch
def fetch(self, endpoint, data = None): """ for getting data after logged in """ payload = { "lastServerChangeId": "-1", "csrf": self.__csrf, "apiClient": "WEB" } if data is not None: payload.update(data) return self.post(endpoint, payload)
python
def fetch(self, endpoint, data = None): """ for getting data after logged in """ payload = { "lastServerChangeId": "-1", "csrf": self.__csrf, "apiClient": "WEB" } if data is not None: payload.update(data) return self.post(endpoint, payload)
[ "def", "fetch", "(", "self", ",", "endpoint", ",", "data", "=", "None", ")", ":", "payload", "=", "{", "\"lastServerChangeId\"", ":", "\"-1\"", ",", "\"csrf\"", ":", "self", ".", "__csrf", ",", "\"apiClient\"", ":", "\"WEB\"", "}", "if", "data", "is", "not", "None", ":", "payload", ".", "update", "(", "data", ")", "return", "self", ".", "post", "(", "endpoint", ",", "payload", ")" ]
for getting data after logged in
[ "for", "getting", "data", "after", "logged", "in" ]
2cdbab3f0a95cbc15aaab7a265f2634bc70dee9f
https://github.com/haochi/personalcapital/blob/2cdbab3f0a95cbc15aaab7a265f2634bc70dee9f/personalcapital/personalcapital.py#L73-L85
8,471
haochi/personalcapital
personalcapital/personalcapital.py
PersonalCapital.__identify_user
def __identify_user(self, username, csrf): """ Returns reusable CSRF code and the auth level as a 2-tuple """ data = { "username": username, "csrf": csrf, "apiClient": "WEB", "bindDevice": "false", "skipLinkAccount": "false", "redirectTo": "", "skipFirstUse": "", "referrerId": "", } r = self.post("/login/identifyUser", data) if r.status_code == requests.codes.ok: result = r.json() new_csrf = getSpHeaderValue(result, CSRF_KEY) auth_level = getSpHeaderValue(result, AUTH_LEVEL_KEY) return (new_csrf, auth_level) return (None, None)
python
def __identify_user(self, username, csrf): """ Returns reusable CSRF code and the auth level as a 2-tuple """ data = { "username": username, "csrf": csrf, "apiClient": "WEB", "bindDevice": "false", "skipLinkAccount": "false", "redirectTo": "", "skipFirstUse": "", "referrerId": "", } r = self.post("/login/identifyUser", data) if r.status_code == requests.codes.ok: result = r.json() new_csrf = getSpHeaderValue(result, CSRF_KEY) auth_level = getSpHeaderValue(result, AUTH_LEVEL_KEY) return (new_csrf, auth_level) return (None, None)
[ "def", "__identify_user", "(", "self", ",", "username", ",", "csrf", ")", ":", "data", "=", "{", "\"username\"", ":", "username", ",", "\"csrf\"", ":", "csrf", ",", "\"apiClient\"", ":", "\"WEB\"", ",", "\"bindDevice\"", ":", "\"false\"", ",", "\"skipLinkAccount\"", ":", "\"false\"", ",", "\"redirectTo\"", ":", "\"\"", ",", "\"skipFirstUse\"", ":", "\"\"", ",", "\"referrerId\"", ":", "\"\"", ",", "}", "r", "=", "self", ".", "post", "(", "\"/login/identifyUser\"", ",", "data", ")", "if", "r", ".", "status_code", "==", "requests", ".", "codes", ".", "ok", ":", "result", "=", "r", ".", "json", "(", ")", "new_csrf", "=", "getSpHeaderValue", "(", "result", ",", "CSRF_KEY", ")", "auth_level", "=", "getSpHeaderValue", "(", "result", ",", "AUTH_LEVEL_KEY", ")", "return", "(", "new_csrf", ",", "auth_level", ")", "return", "(", "None", ",", "None", ")" ]
Returns reusable CSRF code and the auth level as a 2-tuple
[ "Returns", "reusable", "CSRF", "code", "and", "the", "auth", "level", "as", "a", "2", "-", "tuple" ]
2cdbab3f0a95cbc15aaab7a265f2634bc70dee9f
https://github.com/haochi/personalcapital/blob/2cdbab3f0a95cbc15aaab7a265f2634bc70dee9f/personalcapital/personalcapital.py#L114-L137
8,472
linkedin/shiv
setup.py
get_args
def get_args(cls, dist, header=None): """Overrides easy_install.ScriptWriter.get_args This method avoids using pkg_resources to map a named entry_point to a callable at invocation time. """ if header is None: header = cls.get_header() spec = str(dist.as_requirement()) for type_ in 'console', 'gui': group = type_ + '_scripts' for name, ep in dist.get_entry_map(group).items(): # ensure_safe_name if re.search(r'[\\/]', name): raise ValueError("Path separators not allowed in script names") script_text = TEMPLATE.format( ep.module_name, ep.attrs[0], '.'.join(ep.attrs), spec, group, name, ) args = cls._get_script_args(type_, name, header, script_text) for res in args: yield res
python
def get_args(cls, dist, header=None): """Overrides easy_install.ScriptWriter.get_args This method avoids using pkg_resources to map a named entry_point to a callable at invocation time. """ if header is None: header = cls.get_header() spec = str(dist.as_requirement()) for type_ in 'console', 'gui': group = type_ + '_scripts' for name, ep in dist.get_entry_map(group).items(): # ensure_safe_name if re.search(r'[\\/]', name): raise ValueError("Path separators not allowed in script names") script_text = TEMPLATE.format( ep.module_name, ep.attrs[0], '.'.join(ep.attrs), spec, group, name, ) args = cls._get_script_args(type_, name, header, script_text) for res in args: yield res
[ "def", "get_args", "(", "cls", ",", "dist", ",", "header", "=", "None", ")", ":", "if", "header", "is", "None", ":", "header", "=", "cls", ".", "get_header", "(", ")", "spec", "=", "str", "(", "dist", ".", "as_requirement", "(", ")", ")", "for", "type_", "in", "'console'", ",", "'gui'", ":", "group", "=", "type_", "+", "'_scripts'", "for", "name", ",", "ep", "in", "dist", ".", "get_entry_map", "(", "group", ")", ".", "items", "(", ")", ":", "# ensure_safe_name", "if", "re", ".", "search", "(", "r'[\\\\/]'", ",", "name", ")", ":", "raise", "ValueError", "(", "\"Path separators not allowed in script names\"", ")", "script_text", "=", "TEMPLATE", ".", "format", "(", "ep", ".", "module_name", ",", "ep", ".", "attrs", "[", "0", "]", ",", "'.'", ".", "join", "(", "ep", ".", "attrs", ")", ",", "spec", ",", "group", ",", "name", ",", ")", "args", "=", "cls", ".", "_get_script_args", "(", "type_", ",", "name", ",", "header", ",", "script_text", ")", "for", "res", "in", "args", ":", "yield", "res" ]
Overrides easy_install.ScriptWriter.get_args This method avoids using pkg_resources to map a named entry_point to a callable at invocation time.
[ "Overrides", "easy_install", ".", "ScriptWriter", ".", "get_args" ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/setup.py#L47-L72
8,473
linkedin/shiv
src/shiv/pip.py
clean_pip_env
def clean_pip_env() -> Generator[None, None, None]: """A context manager for temporarily removing 'PIP_REQUIRE_VIRTUALENV' from the environment. Since shiv installs via `--target`, we need to ignore venv requirements if they exist. """ require_venv = os.environ.pop(PIP_REQUIRE_VIRTUALENV, None) try: yield finally: if require_venv is not None: os.environ[PIP_REQUIRE_VIRTUALENV] = require_venv
python
def clean_pip_env() -> Generator[None, None, None]: """A context manager for temporarily removing 'PIP_REQUIRE_VIRTUALENV' from the environment. Since shiv installs via `--target`, we need to ignore venv requirements if they exist. """ require_venv = os.environ.pop(PIP_REQUIRE_VIRTUALENV, None) try: yield finally: if require_venv is not None: os.environ[PIP_REQUIRE_VIRTUALENV] = require_venv
[ "def", "clean_pip_env", "(", ")", "->", "Generator", "[", "None", ",", "None", ",", "None", "]", ":", "require_venv", "=", "os", ".", "environ", ".", "pop", "(", "PIP_REQUIRE_VIRTUALENV", ",", "None", ")", "try", ":", "yield", "finally", ":", "if", "require_venv", "is", "not", "None", ":", "os", ".", "environ", "[", "PIP_REQUIRE_VIRTUALENV", "]", "=", "require_venv" ]
A context manager for temporarily removing 'PIP_REQUIRE_VIRTUALENV' from the environment. Since shiv installs via `--target`, we need to ignore venv requirements if they exist.
[ "A", "context", "manager", "for", "temporarily", "removing", "PIP_REQUIRE_VIRTUALENV", "from", "the", "environment", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/pip.py#L15-L28
8,474
linkedin/shiv
src/shiv/pip.py
install
def install(args: List[str]) -> None: """`pip install` as a function. Accepts a list of pip arguments. .. code-block:: py >>> install(['numpy', '--target', 'site-packages']) Collecting numpy Downloading numpy-1.13.3-cp35-cp35m-manylinux1_x86_64.whl (16.9MB) 100% || 16.9MB 53kB/s Installing collected packages: numpy Successfully installed numpy-1.13.3 """ with clean_pip_env(): # if being invoked as a pyz, we must ensure we have access to our own # site-packages when subprocessing since there is no guarantee that pip # will be available subprocess_env = os.environ.copy() sitedir_index = _first_sitedir_index() _extend_python_path(subprocess_env, sys.path[sitedir_index:]) process = subprocess.Popen( [sys.executable, "-m", "pip", "--disable-pip-version-check", "install"] + args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=subprocess_env, ) for output in process.stdout: if output: click.echo(output.decode().rstrip()) if process.wait() > 0: sys.exit(PIP_INSTALL_ERROR)
python
def install(args: List[str]) -> None: """`pip install` as a function. Accepts a list of pip arguments. .. code-block:: py >>> install(['numpy', '--target', 'site-packages']) Collecting numpy Downloading numpy-1.13.3-cp35-cp35m-manylinux1_x86_64.whl (16.9MB) 100% || 16.9MB 53kB/s Installing collected packages: numpy Successfully installed numpy-1.13.3 """ with clean_pip_env(): # if being invoked as a pyz, we must ensure we have access to our own # site-packages when subprocessing since there is no guarantee that pip # will be available subprocess_env = os.environ.copy() sitedir_index = _first_sitedir_index() _extend_python_path(subprocess_env, sys.path[sitedir_index:]) process = subprocess.Popen( [sys.executable, "-m", "pip", "--disable-pip-version-check", "install"] + args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=subprocess_env, ) for output in process.stdout: if output: click.echo(output.decode().rstrip()) if process.wait() > 0: sys.exit(PIP_INSTALL_ERROR)
[ "def", "install", "(", "args", ":", "List", "[", "str", "]", ")", "->", "None", ":", "with", "clean_pip_env", "(", ")", ":", "# if being invoked as a pyz, we must ensure we have access to our own", "# site-packages when subprocessing since there is no guarantee that pip", "# will be available", "subprocess_env", "=", "os", ".", "environ", ".", "copy", "(", ")", "sitedir_index", "=", "_first_sitedir_index", "(", ")", "_extend_python_path", "(", "subprocess_env", ",", "sys", ".", "path", "[", "sitedir_index", ":", "]", ")", "process", "=", "subprocess", ".", "Popen", "(", "[", "sys", ".", "executable", ",", "\"-m\"", ",", "\"pip\"", ",", "\"--disable-pip-version-check\"", ",", "\"install\"", "]", "+", "args", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "env", "=", "subprocess_env", ",", ")", "for", "output", "in", "process", ".", "stdout", ":", "if", "output", ":", "click", ".", "echo", "(", "output", ".", "decode", "(", ")", ".", "rstrip", "(", ")", ")", "if", "process", ".", "wait", "(", ")", ">", "0", ":", "sys", ".", "exit", "(", "PIP_INSTALL_ERROR", ")" ]
`pip install` as a function. Accepts a list of pip arguments. .. code-block:: py >>> install(['numpy', '--target', 'site-packages']) Collecting numpy Downloading numpy-1.13.3-cp35-cp35m-manylinux1_x86_64.whl (16.9MB) 100% || 16.9MB 53kB/s Installing collected packages: numpy Successfully installed numpy-1.13.3
[ "pip", "install", "as", "a", "function", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/pip.py#L31-L67
8,475
linkedin/shiv
src/shiv/bootstrap/__init__.py
current_zipfile
def current_zipfile(): """A function to vend the current zipfile, if any""" if zipfile.is_zipfile(sys.argv[0]): fd = open(sys.argv[0], "rb") return zipfile.ZipFile(fd)
python
def current_zipfile(): """A function to vend the current zipfile, if any""" if zipfile.is_zipfile(sys.argv[0]): fd = open(sys.argv[0], "rb") return zipfile.ZipFile(fd)
[ "def", "current_zipfile", "(", ")", ":", "if", "zipfile", ".", "is_zipfile", "(", "sys", ".", "argv", "[", "0", "]", ")", ":", "fd", "=", "open", "(", "sys", ".", "argv", "[", "0", "]", ",", "\"rb\"", ")", "return", "zipfile", ".", "ZipFile", "(", "fd", ")" ]
A function to vend the current zipfile, if any
[ "A", "function", "to", "vend", "the", "current", "zipfile", "if", "any" ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/bootstrap/__init__.py#L17-L21
8,476
linkedin/shiv
src/shiv/bootstrap/__init__.py
extract_site_packages
def extract_site_packages(archive, target_path, compile_pyc, compile_workers=0, force=False): """Extract everything in site-packages to a specified path. :param ZipFile archive: The zipfile object we are bootstrapping from. :param Path target_path: The path to extract our zip to. """ parent = target_path.parent target_path_tmp = Path(parent, target_path.stem + ".tmp") lock = Path(parent, target_path.stem + ".lock") # If this is the first time that a pyz is being extracted, we'll need to create the ~/.shiv dir if not parent.exists(): parent.mkdir(parents=True, exist_ok=True) with FileLock(lock): # we acquired a lock, it's possible that prior invocation was holding the lock and has # completed bootstrapping, so let's check (again) if we need to do any work if not target_path.exists() or force: # extract our site-packages for filename in archive.namelist(): if filename.startswith("site-packages"): archive.extract(filename, target_path_tmp) if compile_pyc: compileall.compile_dir(target_path_tmp, quiet=2, workers=compile_workers) # if using `force` we will need to delete our target path if target_path.exists(): shutil.rmtree(str(target_path)) # atomic move shutil.move(str(target_path_tmp), str(target_path))
python
def extract_site_packages(archive, target_path, compile_pyc, compile_workers=0, force=False): """Extract everything in site-packages to a specified path. :param ZipFile archive: The zipfile object we are bootstrapping from. :param Path target_path: The path to extract our zip to. """ parent = target_path.parent target_path_tmp = Path(parent, target_path.stem + ".tmp") lock = Path(parent, target_path.stem + ".lock") # If this is the first time that a pyz is being extracted, we'll need to create the ~/.shiv dir if not parent.exists(): parent.mkdir(parents=True, exist_ok=True) with FileLock(lock): # we acquired a lock, it's possible that prior invocation was holding the lock and has # completed bootstrapping, so let's check (again) if we need to do any work if not target_path.exists() or force: # extract our site-packages for filename in archive.namelist(): if filename.startswith("site-packages"): archive.extract(filename, target_path_tmp) if compile_pyc: compileall.compile_dir(target_path_tmp, quiet=2, workers=compile_workers) # if using `force` we will need to delete our target path if target_path.exists(): shutil.rmtree(str(target_path)) # atomic move shutil.move(str(target_path_tmp), str(target_path))
[ "def", "extract_site_packages", "(", "archive", ",", "target_path", ",", "compile_pyc", ",", "compile_workers", "=", "0", ",", "force", "=", "False", ")", ":", "parent", "=", "target_path", ".", "parent", "target_path_tmp", "=", "Path", "(", "parent", ",", "target_path", ".", "stem", "+", "\".tmp\"", ")", "lock", "=", "Path", "(", "parent", ",", "target_path", ".", "stem", "+", "\".lock\"", ")", "# If this is the first time that a pyz is being extracted, we'll need to create the ~/.shiv dir", "if", "not", "parent", ".", "exists", "(", ")", ":", "parent", ".", "mkdir", "(", "parents", "=", "True", ",", "exist_ok", "=", "True", ")", "with", "FileLock", "(", "lock", ")", ":", "# we acquired a lock, it's possible that prior invocation was holding the lock and has", "# completed bootstrapping, so let's check (again) if we need to do any work", "if", "not", "target_path", ".", "exists", "(", ")", "or", "force", ":", "# extract our site-packages", "for", "filename", "in", "archive", ".", "namelist", "(", ")", ":", "if", "filename", ".", "startswith", "(", "\"site-packages\"", ")", ":", "archive", ".", "extract", "(", "filename", ",", "target_path_tmp", ")", "if", "compile_pyc", ":", "compileall", ".", "compile_dir", "(", "target_path_tmp", ",", "quiet", "=", "2", ",", "workers", "=", "compile_workers", ")", "# if using `force` we will need to delete our target path", "if", "target_path", ".", "exists", "(", ")", ":", "shutil", ".", "rmtree", "(", "str", "(", "target_path", ")", ")", "# atomic move", "shutil", ".", "move", "(", "str", "(", "target_path_tmp", ")", ",", "str", "(", "target_path", ")", ")" ]
Extract everything in site-packages to a specified path. :param ZipFile archive: The zipfile object we are bootstrapping from. :param Path target_path: The path to extract our zip to.
[ "Extract", "everything", "in", "site", "-", "packages", "to", "a", "specified", "path", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/bootstrap/__init__.py#L70-L103
8,477
linkedin/shiv
src/shiv/bootstrap/__init__.py
bootstrap
def bootstrap(): # pragma: no cover """Actually bootstrap our shiv environment.""" # get a handle of the currently executing zip file archive = current_zipfile() # create an environment object (a combination of env vars and json metadata) env = Environment.from_json(archive.read("environment.json").decode()) # get a site-packages directory (from env var or via build id) site_packages = cache_path(archive, env.root, env.build_id) / "site-packages" # determine if first run or forcing extract if not site_packages.exists() or env.force_extract: extract_site_packages(archive, site_packages.parent, env.compile_pyc, env.compile_workers, env.force_extract) # get sys.path's length length = len(sys.path) # Find the first instance of an existing site-packages on sys.path index = _first_sitedir_index() or length # append site-packages using the stdlib blessed way of extending path # so as to handle .pth files correctly site.addsitedir(site_packages) # add our site-packages to the environment, if requested if env.extend_pythonpath: _extend_python_path(os.environ, sys.path[index:]) # reorder to place our site-packages before any others found sys.path = sys.path[:index] + sys.path[length:] + sys.path[index:length] # first check if we should drop into interactive mode if not env.interpreter: # do entry point import and call if env.entry_point is not None: mod = import_string(env.entry_point) try: sys.exit(mod()) except TypeError: # catch "<module> is not callable", which is thrown when the entry point's # callable shares a name with it's parent module # e.g. "from foo.bar import bar; bar()" sys.exit(getattr(mod, env.entry_point.replace(":", ".").split(".")[1])()) elif env.script is not None: sys.exit(runpy.run_path(site_packages / "bin" / env.script, run_name="__main__")) # all other options exhausted, drop into interactive mode execute_interpreter()
python
def bootstrap(): # pragma: no cover """Actually bootstrap our shiv environment.""" # get a handle of the currently executing zip file archive = current_zipfile() # create an environment object (a combination of env vars and json metadata) env = Environment.from_json(archive.read("environment.json").decode()) # get a site-packages directory (from env var or via build id) site_packages = cache_path(archive, env.root, env.build_id) / "site-packages" # determine if first run or forcing extract if not site_packages.exists() or env.force_extract: extract_site_packages(archive, site_packages.parent, env.compile_pyc, env.compile_workers, env.force_extract) # get sys.path's length length = len(sys.path) # Find the first instance of an existing site-packages on sys.path index = _first_sitedir_index() or length # append site-packages using the stdlib blessed way of extending path # so as to handle .pth files correctly site.addsitedir(site_packages) # add our site-packages to the environment, if requested if env.extend_pythonpath: _extend_python_path(os.environ, sys.path[index:]) # reorder to place our site-packages before any others found sys.path = sys.path[:index] + sys.path[length:] + sys.path[index:length] # first check if we should drop into interactive mode if not env.interpreter: # do entry point import and call if env.entry_point is not None: mod = import_string(env.entry_point) try: sys.exit(mod()) except TypeError: # catch "<module> is not callable", which is thrown when the entry point's # callable shares a name with it's parent module # e.g. "from foo.bar import bar; bar()" sys.exit(getattr(mod, env.entry_point.replace(":", ".").split(".")[1])()) elif env.script is not None: sys.exit(runpy.run_path(site_packages / "bin" / env.script, run_name="__main__")) # all other options exhausted, drop into interactive mode execute_interpreter()
[ "def", "bootstrap", "(", ")", ":", "# pragma: no cover", "# get a handle of the currently executing zip file", "archive", "=", "current_zipfile", "(", ")", "# create an environment object (a combination of env vars and json metadata)", "env", "=", "Environment", ".", "from_json", "(", "archive", ".", "read", "(", "\"environment.json\"", ")", ".", "decode", "(", ")", ")", "# get a site-packages directory (from env var or via build id)", "site_packages", "=", "cache_path", "(", "archive", ",", "env", ".", "root", ",", "env", ".", "build_id", ")", "/", "\"site-packages\"", "# determine if first run or forcing extract", "if", "not", "site_packages", ".", "exists", "(", ")", "or", "env", ".", "force_extract", ":", "extract_site_packages", "(", "archive", ",", "site_packages", ".", "parent", ",", "env", ".", "compile_pyc", ",", "env", ".", "compile_workers", ",", "env", ".", "force_extract", ")", "# get sys.path's length", "length", "=", "len", "(", "sys", ".", "path", ")", "# Find the first instance of an existing site-packages on sys.path", "index", "=", "_first_sitedir_index", "(", ")", "or", "length", "# append site-packages using the stdlib blessed way of extending path", "# so as to handle .pth files correctly", "site", ".", "addsitedir", "(", "site_packages", ")", "# add our site-packages to the environment, if requested", "if", "env", ".", "extend_pythonpath", ":", "_extend_python_path", "(", "os", ".", "environ", ",", "sys", ".", "path", "[", "index", ":", "]", ")", "# reorder to place our site-packages before any others found", "sys", ".", "path", "=", "sys", ".", "path", "[", ":", "index", "]", "+", "sys", ".", "path", "[", "length", ":", "]", "+", "sys", ".", "path", "[", "index", ":", "length", "]", "# first check if we should drop into interactive mode", "if", "not", "env", ".", "interpreter", ":", "# do entry point import and call", "if", "env", ".", "entry_point", "is", "not", "None", ":", "mod", "=", "import_string", "(", "env", ".", "entry_point", ")", "try", ":", "sys", ".", "exit", "(", "mod", "(", ")", ")", "except", "TypeError", ":", "# catch \"<module> is not callable\", which is thrown when the entry point's", "# callable shares a name with it's parent module", "# e.g. \"from foo.bar import bar; bar()\"", "sys", ".", "exit", "(", "getattr", "(", "mod", ",", "env", ".", "entry_point", ".", "replace", "(", "\":\"", ",", "\".\"", ")", ".", "split", "(", "\".\"", ")", "[", "1", "]", ")", "(", ")", ")", "elif", "env", ".", "script", "is", "not", "None", ":", "sys", ".", "exit", "(", "runpy", ".", "run_path", "(", "site_packages", "/", "\"bin\"", "/", "env", ".", "script", ",", "run_name", "=", "\"__main__\"", ")", ")", "# all other options exhausted, drop into interactive mode", "execute_interpreter", "(", ")" ]
Actually bootstrap our shiv environment.
[ "Actually", "bootstrap", "our", "shiv", "environment", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/bootstrap/__init__.py#L118-L169
8,478
linkedin/shiv
src/shiv/builder.py
write_file_prefix
def write_file_prefix(f: IO[Any], interpreter: str) -> None: """Write a shebang line. :param f: An open file handle. :param interpreter: A path to a python interpreter. """ # if the provided path is too long for a shebang we should error out if len(interpreter) > BINPRM_BUF_SIZE: sys.exit(BINPRM_ERROR) f.write(b"#!" + interpreter.encode(sys.getfilesystemencoding()) + b"\n")
python
def write_file_prefix(f: IO[Any], interpreter: str) -> None: """Write a shebang line. :param f: An open file handle. :param interpreter: A path to a python interpreter. """ # if the provided path is too long for a shebang we should error out if len(interpreter) > BINPRM_BUF_SIZE: sys.exit(BINPRM_ERROR) f.write(b"#!" + interpreter.encode(sys.getfilesystemencoding()) + b"\n")
[ "def", "write_file_prefix", "(", "f", ":", "IO", "[", "Any", "]", ",", "interpreter", ":", "str", ")", "->", "None", ":", "# if the provided path is too long for a shebang we should error out", "if", "len", "(", "interpreter", ")", ">", "BINPRM_BUF_SIZE", ":", "sys", ".", "exit", "(", "BINPRM_ERROR", ")", "f", ".", "write", "(", "b\"#!\"", "+", "interpreter", ".", "encode", "(", "sys", ".", "getfilesystemencoding", "(", ")", ")", "+", "b\"\\n\"", ")" ]
Write a shebang line. :param f: An open file handle. :param interpreter: A path to a python interpreter.
[ "Write", "a", "shebang", "line", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/builder.py#L30-L40
8,479
linkedin/shiv
src/shiv/builder.py
create_archive
def create_archive( source: Path, target: Path, interpreter: str, main: str, compressed: bool = True ) -> None: """Create an application archive from SOURCE. A slightly modified version of stdlib's `zipapp.create_archive <https://docs.python.org/3/library/zipapp.html#zipapp.create_archive>`_ """ # Check that main has the right format. mod, sep, fn = main.partition(":") mod_ok = all(part.isidentifier() for part in mod.split(".")) fn_ok = all(part.isidentifier() for part in fn.split(".")) if not (sep == ":" and mod_ok and fn_ok): raise zipapp.ZipAppError("Invalid entry point: " + main) main_py = MAIN_TEMPLATE.format(module=mod, fn=fn) with maybe_open(target, "wb") as fd: # write shebang write_file_prefix(fd, interpreter) # determine compression compression = zipfile.ZIP_DEFLATED if compressed else zipfile.ZIP_STORED # create zipapp with zipfile.ZipFile(fd, "w", compression=compression) as z: for child in source.rglob("*"): # skip compiled files if child.suffix == '.pyc': continue arcname = child.relative_to(source) z.write(str(child), str(arcname)) # write main z.writestr("__main__.py", main_py.encode("utf-8")) # make executable # NOTE on windows this is no-op target.chmod(target.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
python
def create_archive( source: Path, target: Path, interpreter: str, main: str, compressed: bool = True ) -> None: """Create an application archive from SOURCE. A slightly modified version of stdlib's `zipapp.create_archive <https://docs.python.org/3/library/zipapp.html#zipapp.create_archive>`_ """ # Check that main has the right format. mod, sep, fn = main.partition(":") mod_ok = all(part.isidentifier() for part in mod.split(".")) fn_ok = all(part.isidentifier() for part in fn.split(".")) if not (sep == ":" and mod_ok and fn_ok): raise zipapp.ZipAppError("Invalid entry point: " + main) main_py = MAIN_TEMPLATE.format(module=mod, fn=fn) with maybe_open(target, "wb") as fd: # write shebang write_file_prefix(fd, interpreter) # determine compression compression = zipfile.ZIP_DEFLATED if compressed else zipfile.ZIP_STORED # create zipapp with zipfile.ZipFile(fd, "w", compression=compression) as z: for child in source.rglob("*"): # skip compiled files if child.suffix == '.pyc': continue arcname = child.relative_to(source) z.write(str(child), str(arcname)) # write main z.writestr("__main__.py", main_py.encode("utf-8")) # make executable # NOTE on windows this is no-op target.chmod(target.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
[ "def", "create_archive", "(", "source", ":", "Path", ",", "target", ":", "Path", ",", "interpreter", ":", "str", ",", "main", ":", "str", ",", "compressed", ":", "bool", "=", "True", ")", "->", "None", ":", "# Check that main has the right format.", "mod", ",", "sep", ",", "fn", "=", "main", ".", "partition", "(", "\":\"", ")", "mod_ok", "=", "all", "(", "part", ".", "isidentifier", "(", ")", "for", "part", "in", "mod", ".", "split", "(", "\".\"", ")", ")", "fn_ok", "=", "all", "(", "part", ".", "isidentifier", "(", ")", "for", "part", "in", "fn", ".", "split", "(", "\".\"", ")", ")", "if", "not", "(", "sep", "==", "\":\"", "and", "mod_ok", "and", "fn_ok", ")", ":", "raise", "zipapp", ".", "ZipAppError", "(", "\"Invalid entry point: \"", "+", "main", ")", "main_py", "=", "MAIN_TEMPLATE", ".", "format", "(", "module", "=", "mod", ",", "fn", "=", "fn", ")", "with", "maybe_open", "(", "target", ",", "\"wb\"", ")", "as", "fd", ":", "# write shebang", "write_file_prefix", "(", "fd", ",", "interpreter", ")", "# determine compression", "compression", "=", "zipfile", ".", "ZIP_DEFLATED", "if", "compressed", "else", "zipfile", ".", "ZIP_STORED", "# create zipapp", "with", "zipfile", ".", "ZipFile", "(", "fd", ",", "\"w\"", ",", "compression", "=", "compression", ")", "as", "z", ":", "for", "child", "in", "source", ".", "rglob", "(", "\"*\"", ")", ":", "# skip compiled files", "if", "child", ".", "suffix", "==", "'.pyc'", ":", "continue", "arcname", "=", "child", ".", "relative_to", "(", "source", ")", "z", ".", "write", "(", "str", "(", "child", ")", ",", "str", "(", "arcname", ")", ")", "# write main", "z", ".", "writestr", "(", "\"__main__.py\"", ",", "main_py", ".", "encode", "(", "\"utf-8\"", ")", ")", "# make executable", "# NOTE on windows this is no-op", "target", ".", "chmod", "(", "target", ".", "stat", "(", ")", ".", "st_mode", "|", "stat", ".", "S_IXUSR", "|", "stat", ".", "S_IXGRP", "|", "stat", ".", "S_IXOTH", ")" ]
Create an application archive from SOURCE. A slightly modified version of stdlib's `zipapp.create_archive <https://docs.python.org/3/library/zipapp.html#zipapp.create_archive>`_
[ "Create", "an", "application", "archive", "from", "SOURCE", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/builder.py#L53-L98
8,480
linkedin/shiv
src/shiv/bootstrap/filelock.py
acquire_win
def acquire_win(lock_file): # pragma: no cover """Acquire a lock file on windows.""" try: fd = os.open(lock_file, OPEN_MODE) except OSError: pass else: try: msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) except (IOError, OSError): os.close(fd) else: return fd
python
def acquire_win(lock_file): # pragma: no cover """Acquire a lock file on windows.""" try: fd = os.open(lock_file, OPEN_MODE) except OSError: pass else: try: msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) except (IOError, OSError): os.close(fd) else: return fd
[ "def", "acquire_win", "(", "lock_file", ")", ":", "# pragma: no cover", "try", ":", "fd", "=", "os", ".", "open", "(", "lock_file", ",", "OPEN_MODE", ")", "except", "OSError", ":", "pass", "else", ":", "try", ":", "msvcrt", ".", "locking", "(", "fd", ",", "msvcrt", ".", "LK_NBLCK", ",", "1", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "os", ".", "close", "(", "fd", ")", "else", ":", "return", "fd" ]
Acquire a lock file on windows.
[ "Acquire", "a", "lock", "file", "on", "windows", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/bootstrap/filelock.py#L22-L34
8,481
linkedin/shiv
src/shiv/bootstrap/filelock.py
acquire_nix
def acquire_nix(lock_file): # pragma: no cover """Acquire a lock file on linux or osx.""" fd = os.open(lock_file, OPEN_MODE) try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except (IOError, OSError): os.close(fd) else: return fd
python
def acquire_nix(lock_file): # pragma: no cover """Acquire a lock file on linux or osx.""" fd = os.open(lock_file, OPEN_MODE) try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except (IOError, OSError): os.close(fd) else: return fd
[ "def", "acquire_nix", "(", "lock_file", ")", ":", "# pragma: no cover", "fd", "=", "os", ".", "open", "(", "lock_file", ",", "OPEN_MODE", ")", "try", ":", "fcntl", ".", "flock", "(", "fd", ",", "fcntl", ".", "LOCK_EX", "|", "fcntl", ".", "LOCK_NB", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "os", ".", "close", "(", "fd", ")", "else", ":", "return", "fd" ]
Acquire a lock file on linux or osx.
[ "Acquire", "a", "lock", "file", "on", "linux", "or", "osx", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/bootstrap/filelock.py#L37-L46
8,482
linkedin/shiv
src/shiv/cli.py
find_entry_point
def find_entry_point(site_packages: Path, console_script: str) -> str: """Find a console_script in a site-packages directory. Console script metadata is stored in entry_points.txt per setuptools convention. This function searches all entry_points.txt files and returns the import string for a given console_script argument. :param site_packages: A path to a site-packages directory on disk. :param console_script: A console_script string. """ config_parser = ConfigParser() config_parser.read(site_packages.rglob("entry_points.txt")) return config_parser["console_scripts"][console_script]
python
def find_entry_point(site_packages: Path, console_script: str) -> str: """Find a console_script in a site-packages directory. Console script metadata is stored in entry_points.txt per setuptools convention. This function searches all entry_points.txt files and returns the import string for a given console_script argument. :param site_packages: A path to a site-packages directory on disk. :param console_script: A console_script string. """ config_parser = ConfigParser() config_parser.read(site_packages.rglob("entry_points.txt")) return config_parser["console_scripts"][console_script]
[ "def", "find_entry_point", "(", "site_packages", ":", "Path", ",", "console_script", ":", "str", ")", "->", "str", ":", "config_parser", "=", "ConfigParser", "(", ")", "config_parser", ".", "read", "(", "site_packages", ".", "rglob", "(", "\"entry_points.txt\"", ")", ")", "return", "config_parser", "[", "\"console_scripts\"", "]", "[", "console_script", "]" ]
Find a console_script in a site-packages directory. Console script metadata is stored in entry_points.txt per setuptools convention. This function searches all entry_points.txt files and returns the import string for a given console_script argument. :param site_packages: A path to a site-packages directory on disk. :param console_script: A console_script string.
[ "Find", "a", "console_script", "in", "a", "site", "-", "packages", "directory", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/cli.py#L32-L45
8,483
linkedin/shiv
src/shiv/cli.py
copy_bootstrap
def copy_bootstrap(bootstrap_target: Path) -> None: """Copy bootstrap code from shiv into the pyz. This function is excluded from type checking due to the conditional import. :param bootstrap_target: The temporary directory where we are staging pyz contents. """ for bootstrap_file in importlib_resources.contents(bootstrap): if importlib_resources.is_resource(bootstrap, bootstrap_file): with importlib_resources.path(bootstrap, bootstrap_file) as f: shutil.copyfile(f.absolute(), bootstrap_target / f.name)
python
def copy_bootstrap(bootstrap_target: Path) -> None: """Copy bootstrap code from shiv into the pyz. This function is excluded from type checking due to the conditional import. :param bootstrap_target: The temporary directory where we are staging pyz contents. """ for bootstrap_file in importlib_resources.contents(bootstrap): if importlib_resources.is_resource(bootstrap, bootstrap_file): with importlib_resources.path(bootstrap, bootstrap_file) as f: shutil.copyfile(f.absolute(), bootstrap_target / f.name)
[ "def", "copy_bootstrap", "(", "bootstrap_target", ":", "Path", ")", "->", "None", ":", "for", "bootstrap_file", "in", "importlib_resources", ".", "contents", "(", "bootstrap", ")", ":", "if", "importlib_resources", ".", "is_resource", "(", "bootstrap", ",", "bootstrap_file", ")", ":", "with", "importlib_resources", ".", "path", "(", "bootstrap", ",", "bootstrap_file", ")", "as", "f", ":", "shutil", ".", "copyfile", "(", "f", ".", "absolute", "(", ")", ",", "bootstrap_target", "/", "f", ".", "name", ")" ]
Copy bootstrap code from shiv into the pyz. This function is excluded from type checking due to the conditional import. :param bootstrap_target: The temporary directory where we are staging pyz contents.
[ "Copy", "bootstrap", "code", "from", "shiv", "into", "the", "pyz", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/cli.py#L49-L60
8,484
linkedin/shiv
src/shiv/cli.py
_interpreter_path
def _interpreter_path(append_version: bool = False) -> str: """A function to return the path to the current Python interpreter. Even when inside a venv, this will return the interpreter the venv was created with. """ base_dir = Path(getattr(sys, "real_prefix", sys.base_prefix)).resolve() sys_exec = Path(sys.executable) name = sys_exec.stem suffix = sys_exec.suffix if append_version: name += str(sys.version_info.major) name += suffix try: return str(next(iter(base_dir.rglob(name)))) except StopIteration: if not append_version: # If we couldn't find an interpreter, it's likely that we looked for # "python" when we should've been looking for "python3" # so we try again with append_version=True return _interpreter_path(append_version=True) # If we were still unable to find a real interpreter for some reason # we fallback to the current runtime's interpreter return sys.executable
python
def _interpreter_path(append_version: bool = False) -> str: """A function to return the path to the current Python interpreter. Even when inside a venv, this will return the interpreter the venv was created with. """ base_dir = Path(getattr(sys, "real_prefix", sys.base_prefix)).resolve() sys_exec = Path(sys.executable) name = sys_exec.stem suffix = sys_exec.suffix if append_version: name += str(sys.version_info.major) name += suffix try: return str(next(iter(base_dir.rglob(name)))) except StopIteration: if not append_version: # If we couldn't find an interpreter, it's likely that we looked for # "python" when we should've been looking for "python3" # so we try again with append_version=True return _interpreter_path(append_version=True) # If we were still unable to find a real interpreter for some reason # we fallback to the current runtime's interpreter return sys.executable
[ "def", "_interpreter_path", "(", "append_version", ":", "bool", "=", "False", ")", "->", "str", ":", "base_dir", "=", "Path", "(", "getattr", "(", "sys", ",", "\"real_prefix\"", ",", "sys", ".", "base_prefix", ")", ")", ".", "resolve", "(", ")", "sys_exec", "=", "Path", "(", "sys", ".", "executable", ")", "name", "=", "sys_exec", ".", "stem", "suffix", "=", "sys_exec", ".", "suffix", "if", "append_version", ":", "name", "+=", "str", "(", "sys", ".", "version_info", ".", "major", ")", "name", "+=", "suffix", "try", ":", "return", "str", "(", "next", "(", "iter", "(", "base_dir", ".", "rglob", "(", "name", ")", ")", ")", ")", "except", "StopIteration", ":", "if", "not", "append_version", ":", "# If we couldn't find an interpreter, it's likely that we looked for", "# \"python\" when we should've been looking for \"python3\"", "# so we try again with append_version=True", "return", "_interpreter_path", "(", "append_version", "=", "True", ")", "# If we were still unable to find a real interpreter for some reason", "# we fallback to the current runtime's interpreter", "return", "sys", ".", "executable" ]
A function to return the path to the current Python interpreter. Even when inside a venv, this will return the interpreter the venv was created with.
[ "A", "function", "to", "return", "the", "path", "to", "the", "current", "Python", "interpreter", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/cli.py#L63-L93
8,485
linkedin/shiv
src/shiv/cli.py
main
def main( output_file: str, entry_point: Optional[str], console_script: Optional[str], python: Optional[str], site_packages: Optional[str], compressed: bool, compile_pyc: bool, extend_pythonpath: bool, pip_args: List[str], ) -> None: """ Shiv is a command line utility for building fully self-contained Python zipapps as outlined in PEP 441, but with all their dependencies included! """ if not pip_args and not site_packages: sys.exit(NO_PIP_ARGS_OR_SITE_PACKAGES) if output_file is None: sys.exit(NO_OUTFILE) # check for disallowed pip arguments for disallowed in DISALLOWED_ARGS: for supplied_arg in pip_args: if supplied_arg in disallowed: sys.exit( DISALLOWED_PIP_ARGS.format( arg=supplied_arg, reason=DISALLOWED_ARGS[disallowed] ) ) with TemporaryDirectory() as working_path: tmp_site_packages = Path(working_path, "site-packages") if site_packages: shutil.copytree(site_packages, tmp_site_packages) if pip_args: # install deps into staged site-packages pip.install(["--target", str(tmp_site_packages)] + list(pip_args)) # if entry_point is a console script, get the callable if entry_point is None and console_script is not None: try: entry_point = find_entry_point(tmp_site_packages, console_script) except KeyError: if not Path(tmp_site_packages, "bin", console_script).exists(): sys.exit(NO_ENTRY_POINT.format(entry_point=console_script)) # create runtime environment metadata env = Environment( build_id=str(uuid.uuid4()), entry_point=entry_point, script=console_script, compile_pyc=compile_pyc, extend_pythonpath=extend_pythonpath, ) Path(working_path, "environment.json").write_text(env.to_json()) # create bootstrapping directory in working path bootstrap_target = Path(working_path, "_bootstrap") bootstrap_target.mkdir(parents=True, exist_ok=True) # copy bootstrap code copy_bootstrap(bootstrap_target) # create the zip builder.create_archive( Path(working_path), target=Path(output_file).expanduser(), interpreter=python or _interpreter_path(), main="_bootstrap:bootstrap", compressed=compressed, )
python
def main( output_file: str, entry_point: Optional[str], console_script: Optional[str], python: Optional[str], site_packages: Optional[str], compressed: bool, compile_pyc: bool, extend_pythonpath: bool, pip_args: List[str], ) -> None: """ Shiv is a command line utility for building fully self-contained Python zipapps as outlined in PEP 441, but with all their dependencies included! """ if not pip_args and not site_packages: sys.exit(NO_PIP_ARGS_OR_SITE_PACKAGES) if output_file is None: sys.exit(NO_OUTFILE) # check for disallowed pip arguments for disallowed in DISALLOWED_ARGS: for supplied_arg in pip_args: if supplied_arg in disallowed: sys.exit( DISALLOWED_PIP_ARGS.format( arg=supplied_arg, reason=DISALLOWED_ARGS[disallowed] ) ) with TemporaryDirectory() as working_path: tmp_site_packages = Path(working_path, "site-packages") if site_packages: shutil.copytree(site_packages, tmp_site_packages) if pip_args: # install deps into staged site-packages pip.install(["--target", str(tmp_site_packages)] + list(pip_args)) # if entry_point is a console script, get the callable if entry_point is None and console_script is not None: try: entry_point = find_entry_point(tmp_site_packages, console_script) except KeyError: if not Path(tmp_site_packages, "bin", console_script).exists(): sys.exit(NO_ENTRY_POINT.format(entry_point=console_script)) # create runtime environment metadata env = Environment( build_id=str(uuid.uuid4()), entry_point=entry_point, script=console_script, compile_pyc=compile_pyc, extend_pythonpath=extend_pythonpath, ) Path(working_path, "environment.json").write_text(env.to_json()) # create bootstrapping directory in working path bootstrap_target = Path(working_path, "_bootstrap") bootstrap_target.mkdir(parents=True, exist_ok=True) # copy bootstrap code copy_bootstrap(bootstrap_target) # create the zip builder.create_archive( Path(working_path), target=Path(output_file).expanduser(), interpreter=python or _interpreter_path(), main="_bootstrap:bootstrap", compressed=compressed, )
[ "def", "main", "(", "output_file", ":", "str", ",", "entry_point", ":", "Optional", "[", "str", "]", ",", "console_script", ":", "Optional", "[", "str", "]", ",", "python", ":", "Optional", "[", "str", "]", ",", "site_packages", ":", "Optional", "[", "str", "]", ",", "compressed", ":", "bool", ",", "compile_pyc", ":", "bool", ",", "extend_pythonpath", ":", "bool", ",", "pip_args", ":", "List", "[", "str", "]", ",", ")", "->", "None", ":", "if", "not", "pip_args", "and", "not", "site_packages", ":", "sys", ".", "exit", "(", "NO_PIP_ARGS_OR_SITE_PACKAGES", ")", "if", "output_file", "is", "None", ":", "sys", ".", "exit", "(", "NO_OUTFILE", ")", "# check for disallowed pip arguments", "for", "disallowed", "in", "DISALLOWED_ARGS", ":", "for", "supplied_arg", "in", "pip_args", ":", "if", "supplied_arg", "in", "disallowed", ":", "sys", ".", "exit", "(", "DISALLOWED_PIP_ARGS", ".", "format", "(", "arg", "=", "supplied_arg", ",", "reason", "=", "DISALLOWED_ARGS", "[", "disallowed", "]", ")", ")", "with", "TemporaryDirectory", "(", ")", "as", "working_path", ":", "tmp_site_packages", "=", "Path", "(", "working_path", ",", "\"site-packages\"", ")", "if", "site_packages", ":", "shutil", ".", "copytree", "(", "site_packages", ",", "tmp_site_packages", ")", "if", "pip_args", ":", "# install deps into staged site-packages", "pip", ".", "install", "(", "[", "\"--target\"", ",", "str", "(", "tmp_site_packages", ")", "]", "+", "list", "(", "pip_args", ")", ")", "# if entry_point is a console script, get the callable", "if", "entry_point", "is", "None", "and", "console_script", "is", "not", "None", ":", "try", ":", "entry_point", "=", "find_entry_point", "(", "tmp_site_packages", ",", "console_script", ")", "except", "KeyError", ":", "if", "not", "Path", "(", "tmp_site_packages", ",", "\"bin\"", ",", "console_script", ")", ".", "exists", "(", ")", ":", "sys", ".", "exit", "(", "NO_ENTRY_POINT", ".", "format", "(", "entry_point", "=", "console_script", ")", ")", "# create runtime environment metadata", "env", "=", "Environment", "(", "build_id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ",", "entry_point", "=", "entry_point", ",", "script", "=", "console_script", ",", "compile_pyc", "=", "compile_pyc", ",", "extend_pythonpath", "=", "extend_pythonpath", ",", ")", "Path", "(", "working_path", ",", "\"environment.json\"", ")", ".", "write_text", "(", "env", ".", "to_json", "(", ")", ")", "# create bootstrapping directory in working path", "bootstrap_target", "=", "Path", "(", "working_path", ",", "\"_bootstrap\"", ")", "bootstrap_target", ".", "mkdir", "(", "parents", "=", "True", ",", "exist_ok", "=", "True", ")", "# copy bootstrap code", "copy_bootstrap", "(", "bootstrap_target", ")", "# create the zip", "builder", ".", "create_archive", "(", "Path", "(", "working_path", ")", ",", "target", "=", "Path", "(", "output_file", ")", ".", "expanduser", "(", ")", ",", "interpreter", "=", "python", "or", "_interpreter_path", "(", ")", ",", "main", "=", "\"_bootstrap:bootstrap\"", ",", "compressed", "=", "compressed", ",", ")" ]
Shiv is a command line utility for building fully self-contained Python zipapps as outlined in PEP 441, but with all their dependencies included!
[ "Shiv", "is", "a", "command", "line", "utility", "for", "building", "fully", "self", "-", "contained", "Python", "zipapps", "as", "outlined", "in", "PEP", "441", "but", "with", "all", "their", "dependencies", "included!" ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/cli.py#L128-L204
8,486
aio-libs/aiobotocore
aiobotocore/session.py
get_session
def get_session(*, env_vars=None, loop=None): """ Return a new session object. """ loop = loop or asyncio.get_event_loop() return AioSession(session_vars=env_vars, loop=loop)
python
def get_session(*, env_vars=None, loop=None): """ Return a new session object. """ loop = loop or asyncio.get_event_loop() return AioSession(session_vars=env_vars, loop=loop)
[ "def", "get_session", "(", "*", ",", "env_vars", "=", "None", ",", "loop", "=", "None", ")", ":", "loop", "=", "loop", "or", "asyncio", ".", "get_event_loop", "(", ")", "return", "AioSession", "(", "session_vars", "=", "env_vars", ",", "loop", "=", "loop", ")" ]
Return a new session object.
[ "Return", "a", "new", "session", "object", "." ]
d0c0a8651a3738b6260efe962218a5738694dd2a
https://github.com/aio-libs/aiobotocore/blob/d0c0a8651a3738b6260efe962218a5738694dd2a/aiobotocore/session.py#L88-L93
8,487
aio-libs/aiobotocore
aiobotocore/response.py
StreamingBody.read
async def read(self, amt=None): """Read at most amt bytes from the stream. If the amt argument is omitted, read all data. """ # botocore to aiohttp mapping chunk = await self.__wrapped__.read(amt if amt is not None else -1) self._self_amount_read += len(chunk) if amt is None or (not chunk and amt > 0): # If the server sends empty contents or # we ask to read all of the contents, then we know # we need to verify the content length. self._verify_content_length() return chunk
python
async def read(self, amt=None): """Read at most amt bytes from the stream. If the amt argument is omitted, read all data. """ # botocore to aiohttp mapping chunk = await self.__wrapped__.read(amt if amt is not None else -1) self._self_amount_read += len(chunk) if amt is None or (not chunk and amt > 0): # If the server sends empty contents or # we ask to read all of the contents, then we know # we need to verify the content length. self._verify_content_length() return chunk
[ "async", "def", "read", "(", "self", ",", "amt", "=", "None", ")", ":", "# botocore to aiohttp mapping", "chunk", "=", "await", "self", ".", "__wrapped__", ".", "read", "(", "amt", "if", "amt", "is", "not", "None", "else", "-", "1", ")", "self", ".", "_self_amount_read", "+=", "len", "(", "chunk", ")", "if", "amt", "is", "None", "or", "(", "not", "chunk", "and", "amt", ">", "0", ")", ":", "# If the server sends empty contents or", "# we ask to read all of the contents, then we know", "# we need to verify the content length.", "self", ".", "_verify_content_length", "(", ")", "return", "chunk" ]
Read at most amt bytes from the stream. If the amt argument is omitted, read all data.
[ "Read", "at", "most", "amt", "bytes", "from", "the", "stream", "." ]
d0c0a8651a3738b6260efe962218a5738694dd2a
https://github.com/aio-libs/aiobotocore/blob/d0c0a8651a3738b6260efe962218a5738694dd2a/aiobotocore/response.py#L37-L50
8,488
aio-libs/aiobotocore
aiobotocore/response.py
StreamingBody.iter_lines
async def iter_lines(self, chunk_size=1024): """Return an iterator to yield lines from the raw stream. This is achieved by reading chunk of bytes (of size chunk_size) at a time from the raw stream, and then yielding lines from there. """ pending = b'' async for chunk in self.iter_chunks(chunk_size): lines = (pending + chunk).splitlines(True) for line in lines[:-1]: await yield_(line.splitlines()[0]) pending = lines[-1] if pending: await yield_(pending.splitlines()[0])
python
async def iter_lines(self, chunk_size=1024): """Return an iterator to yield lines from the raw stream. This is achieved by reading chunk of bytes (of size chunk_size) at a time from the raw stream, and then yielding lines from there. """ pending = b'' async for chunk in self.iter_chunks(chunk_size): lines = (pending + chunk).splitlines(True) for line in lines[:-1]: await yield_(line.splitlines()[0]) pending = lines[-1] if pending: await yield_(pending.splitlines()[0])
[ "async", "def", "iter_lines", "(", "self", ",", "chunk_size", "=", "1024", ")", ":", "pending", "=", "b''", "async", "for", "chunk", "in", "self", ".", "iter_chunks", "(", "chunk_size", ")", ":", "lines", "=", "(", "pending", "+", "chunk", ")", ".", "splitlines", "(", "True", ")", "for", "line", "in", "lines", "[", ":", "-", "1", "]", ":", "await", "yield_", "(", "line", ".", "splitlines", "(", ")", "[", "0", "]", ")", "pending", "=", "lines", "[", "-", "1", "]", "if", "pending", ":", "await", "yield_", "(", "pending", ".", "splitlines", "(", ")", "[", "0", "]", ")" ]
Return an iterator to yield lines from the raw stream. This is achieved by reading chunk of bytes (of size chunk_size) at a time from the raw stream, and then yielding lines from there.
[ "Return", "an", "iterator", "to", "yield", "lines", "from", "the", "raw", "stream", "." ]
d0c0a8651a3738b6260efe962218a5738694dd2a
https://github.com/aio-libs/aiobotocore/blob/d0c0a8651a3738b6260efe962218a5738694dd2a/aiobotocore/response.py#L68-L81
8,489
aio-libs/aiobotocore
aiobotocore/response.py
StreamingBody.iter_chunks
async def iter_chunks(self, chunk_size=_DEFAULT_CHUNK_SIZE): """Return an iterator to yield chunks of chunk_size bytes from the raw stream. """ while True: current_chunk = await self.read(chunk_size) if current_chunk == b"": break await yield_(current_chunk)
python
async def iter_chunks(self, chunk_size=_DEFAULT_CHUNK_SIZE): """Return an iterator to yield chunks of chunk_size bytes from the raw stream. """ while True: current_chunk = await self.read(chunk_size) if current_chunk == b"": break await yield_(current_chunk)
[ "async", "def", "iter_chunks", "(", "self", ",", "chunk_size", "=", "_DEFAULT_CHUNK_SIZE", ")", ":", "while", "True", ":", "current_chunk", "=", "await", "self", ".", "read", "(", "chunk_size", ")", "if", "current_chunk", "==", "b\"\"", ":", "break", "await", "yield_", "(", "current_chunk", ")" ]
Return an iterator to yield chunks of chunk_size bytes from the raw stream.
[ "Return", "an", "iterator", "to", "yield", "chunks", "of", "chunk_size", "bytes", "from", "the", "raw", "stream", "." ]
d0c0a8651a3738b6260efe962218a5738694dd2a
https://github.com/aio-libs/aiobotocore/blob/d0c0a8651a3738b6260efe962218a5738694dd2a/aiobotocore/response.py#L84-L92
8,490
aio-libs/aiobotocore
examples/dynamodb_batch_write.py
get_items
def get_items(start_num, num_items): """ Generate a sequence of dynamo items :param start_num: Start index :type start_num: int :param num_items: Number of items :type num_items: int :return: List of dictionaries :rtype: list of dict """ result = [] for i in range(start_num, start_num+num_items): result.append({'pk': {'S': 'item{0}'.format(i)}}) return result
python
def get_items(start_num, num_items): """ Generate a sequence of dynamo items :param start_num: Start index :type start_num: int :param num_items: Number of items :type num_items: int :return: List of dictionaries :rtype: list of dict """ result = [] for i in range(start_num, start_num+num_items): result.append({'pk': {'S': 'item{0}'.format(i)}}) return result
[ "def", "get_items", "(", "start_num", ",", "num_items", ")", ":", "result", "=", "[", "]", "for", "i", "in", "range", "(", "start_num", ",", "start_num", "+", "num_items", ")", ":", "result", ".", "append", "(", "{", "'pk'", ":", "{", "'S'", ":", "'item{0}'", ".", "format", "(", "i", ")", "}", "}", ")", "return", "result" ]
Generate a sequence of dynamo items :param start_num: Start index :type start_num: int :param num_items: Number of items :type num_items: int :return: List of dictionaries :rtype: list of dict
[ "Generate", "a", "sequence", "of", "dynamo", "items" ]
d0c0a8651a3738b6260efe962218a5738694dd2a
https://github.com/aio-libs/aiobotocore/blob/d0c0a8651a3738b6260efe962218a5738694dd2a/examples/dynamodb_batch_write.py#L7-L21
8,491
aio-libs/aiobotocore
examples/dynamodb_batch_write.py
create_batch_write_structure
def create_batch_write_structure(table_name, start_num, num_items): """ Create item structure for passing to batch_write_item :param table_name: DynamoDB table name :type table_name: str :param start_num: Start index :type start_num: int :param num_items: Number of items :type num_items: int :return: dictionary of tables to write to :rtype: dict """ return { table_name: [ {'PutRequest': {'Item': item}} for item in get_items(start_num, num_items) ] }
python
def create_batch_write_structure(table_name, start_num, num_items): """ Create item structure for passing to batch_write_item :param table_name: DynamoDB table name :type table_name: str :param start_num: Start index :type start_num: int :param num_items: Number of items :type num_items: int :return: dictionary of tables to write to :rtype: dict """ return { table_name: [ {'PutRequest': {'Item': item}} for item in get_items(start_num, num_items) ] }
[ "def", "create_batch_write_structure", "(", "table_name", ",", "start_num", ",", "num_items", ")", ":", "return", "{", "table_name", ":", "[", "{", "'PutRequest'", ":", "{", "'Item'", ":", "item", "}", "}", "for", "item", "in", "get_items", "(", "start_num", ",", "num_items", ")", "]", "}" ]
Create item structure for passing to batch_write_item :param table_name: DynamoDB table name :type table_name: str :param start_num: Start index :type start_num: int :param num_items: Number of items :type num_items: int :return: dictionary of tables to write to :rtype: dict
[ "Create", "item", "structure", "for", "passing", "to", "batch_write_item" ]
d0c0a8651a3738b6260efe962218a5738694dd2a
https://github.com/aio-libs/aiobotocore/blob/d0c0a8651a3738b6260efe962218a5738694dd2a/examples/dynamodb_batch_write.py#L24-L42
8,492
aio-libs/aiobotocore
aiobotocore/client.py
AioBaseClient.get_paginator
def get_paginator(self, operation_name): """Create a paginator for an operation. :type operation_name: string :param operation_name: The operation name. This is the same name as the method name on the client. For example, if the method name is ``create_foo``, and you'd normally invoke the operation as ``client.create_foo(**kwargs)``, if the ``create_foo`` operation can be paginated, you can use the call ``client.get_paginator("create_foo")``. :raise OperationNotPageableError: Raised if the operation is not pageable. You can use the ``client.can_paginate`` method to check if an operation is pageable. :rtype: L{botocore.paginate.Paginator} :return: A paginator object. """ if not self.can_paginate(operation_name): raise OperationNotPageableError(operation_name=operation_name) else: # substitute iterator with async one Paginator.PAGE_ITERATOR_CLS = AioPageIterator actual_operation_name = self._PY_TO_OP_NAME[operation_name] # Create a new paginate method that will serve as a proxy to # the underlying Paginator.paginate method. This is needed to # attach a docstring to the method. def paginate(self, **kwargs): return Paginator.paginate(self, **kwargs) paginator_config = self._cache['page_config'][ actual_operation_name] # Rename the paginator class based on the type of paginator. paginator_class_name = str('%s.Paginator.%s' % ( get_service_module_name(self.meta.service_model), actual_operation_name)) # Create the new paginator class documented_paginator_cls = type( paginator_class_name, (Paginator,), {'paginate': paginate}) operation_model = self._service_model.\ operation_model(actual_operation_name) paginator = documented_paginator_cls( getattr(self, operation_name), paginator_config, operation_model) return paginator
python
def get_paginator(self, operation_name): """Create a paginator for an operation. :type operation_name: string :param operation_name: The operation name. This is the same name as the method name on the client. For example, if the method name is ``create_foo``, and you'd normally invoke the operation as ``client.create_foo(**kwargs)``, if the ``create_foo`` operation can be paginated, you can use the call ``client.get_paginator("create_foo")``. :raise OperationNotPageableError: Raised if the operation is not pageable. You can use the ``client.can_paginate`` method to check if an operation is pageable. :rtype: L{botocore.paginate.Paginator} :return: A paginator object. """ if not self.can_paginate(operation_name): raise OperationNotPageableError(operation_name=operation_name) else: # substitute iterator with async one Paginator.PAGE_ITERATOR_CLS = AioPageIterator actual_operation_name = self._PY_TO_OP_NAME[operation_name] # Create a new paginate method that will serve as a proxy to # the underlying Paginator.paginate method. This is needed to # attach a docstring to the method. def paginate(self, **kwargs): return Paginator.paginate(self, **kwargs) paginator_config = self._cache['page_config'][ actual_operation_name] # Rename the paginator class based on the type of paginator. paginator_class_name = str('%s.Paginator.%s' % ( get_service_module_name(self.meta.service_model), actual_operation_name)) # Create the new paginator class documented_paginator_cls = type( paginator_class_name, (Paginator,), {'paginate': paginate}) operation_model = self._service_model.\ operation_model(actual_operation_name) paginator = documented_paginator_cls( getattr(self, operation_name), paginator_config, operation_model) return paginator
[ "def", "get_paginator", "(", "self", ",", "operation_name", ")", ":", "if", "not", "self", ".", "can_paginate", "(", "operation_name", ")", ":", "raise", "OperationNotPageableError", "(", "operation_name", "=", "operation_name", ")", "else", ":", "# substitute iterator with async one", "Paginator", ".", "PAGE_ITERATOR_CLS", "=", "AioPageIterator", "actual_operation_name", "=", "self", ".", "_PY_TO_OP_NAME", "[", "operation_name", "]", "# Create a new paginate method that will serve as a proxy to", "# the underlying Paginator.paginate method. This is needed to", "# attach a docstring to the method.", "def", "paginate", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "Paginator", ".", "paginate", "(", "self", ",", "*", "*", "kwargs", ")", "paginator_config", "=", "self", ".", "_cache", "[", "'page_config'", "]", "[", "actual_operation_name", "]", "# Rename the paginator class based on the type of paginator.", "paginator_class_name", "=", "str", "(", "'%s.Paginator.%s'", "%", "(", "get_service_module_name", "(", "self", ".", "meta", ".", "service_model", ")", ",", "actual_operation_name", ")", ")", "# Create the new paginator class", "documented_paginator_cls", "=", "type", "(", "paginator_class_name", ",", "(", "Paginator", ",", ")", ",", "{", "'paginate'", ":", "paginate", "}", ")", "operation_model", "=", "self", ".", "_service_model", ".", "operation_model", "(", "actual_operation_name", ")", "paginator", "=", "documented_paginator_cls", "(", "getattr", "(", "self", ",", "operation_name", ")", ",", "paginator_config", ",", "operation_model", ")", "return", "paginator" ]
Create a paginator for an operation. :type operation_name: string :param operation_name: The operation name. This is the same name as the method name on the client. For example, if the method name is ``create_foo``, and you'd normally invoke the operation as ``client.create_foo(**kwargs)``, if the ``create_foo`` operation can be paginated, you can use the call ``client.get_paginator("create_foo")``. :raise OperationNotPageableError: Raised if the operation is not pageable. You can use the ``client.can_paginate`` method to check if an operation is pageable. :rtype: L{botocore.paginate.Paginator} :return: A paginator object.
[ "Create", "a", "paginator", "for", "an", "operation", "." ]
d0c0a8651a3738b6260efe962218a5738694dd2a
https://github.com/aio-libs/aiobotocore/blob/d0c0a8651a3738b6260efe962218a5738694dd2a/aiobotocore/client.py#L124-L176
8,493
aio-libs/aiobotocore
aiobotocore/client.py
AioBaseClient.get_waiter
def get_waiter(self, waiter_name): """Returns an object that can wait for some condition. :type waiter_name: str :param waiter_name: The name of the waiter to get. See the waiters section of the service docs for a list of available waiters. :returns: The specified waiter object. :rtype: botocore.waiter.Waiter """ config = self._get_waiter_config() if not config: raise ValueError("Waiter does not exist: %s" % waiter_name) model = waiter.WaiterModel(config) mapping = {} for name in model.waiter_names: mapping[xform_name(name)] = name if waiter_name not in mapping: raise ValueError("Waiter does not exist: %s" % waiter_name) return waiter.create_waiter_with_client( mapping[waiter_name], model, self, loop=self._loop)
python
def get_waiter(self, waiter_name): """Returns an object that can wait for some condition. :type waiter_name: str :param waiter_name: The name of the waiter to get. See the waiters section of the service docs for a list of available waiters. :returns: The specified waiter object. :rtype: botocore.waiter.Waiter """ config = self._get_waiter_config() if not config: raise ValueError("Waiter does not exist: %s" % waiter_name) model = waiter.WaiterModel(config) mapping = {} for name in model.waiter_names: mapping[xform_name(name)] = name if waiter_name not in mapping: raise ValueError("Waiter does not exist: %s" % waiter_name) return waiter.create_waiter_with_client( mapping[waiter_name], model, self, loop=self._loop)
[ "def", "get_waiter", "(", "self", ",", "waiter_name", ")", ":", "config", "=", "self", ".", "_get_waiter_config", "(", ")", "if", "not", "config", ":", "raise", "ValueError", "(", "\"Waiter does not exist: %s\"", "%", "waiter_name", ")", "model", "=", "waiter", ".", "WaiterModel", "(", "config", ")", "mapping", "=", "{", "}", "for", "name", "in", "model", ".", "waiter_names", ":", "mapping", "[", "xform_name", "(", "name", ")", "]", "=", "name", "if", "waiter_name", "not", "in", "mapping", ":", "raise", "ValueError", "(", "\"Waiter does not exist: %s\"", "%", "waiter_name", ")", "return", "waiter", ".", "create_waiter_with_client", "(", "mapping", "[", "waiter_name", "]", ",", "model", ",", "self", ",", "loop", "=", "self", ".", "_loop", ")" ]
Returns an object that can wait for some condition. :type waiter_name: str :param waiter_name: The name of the waiter to get. See the waiters section of the service docs for a list of available waiters. :returns: The specified waiter object. :rtype: botocore.waiter.Waiter
[ "Returns", "an", "object", "that", "can", "wait", "for", "some", "condition", "." ]
d0c0a8651a3738b6260efe962218a5738694dd2a
https://github.com/aio-libs/aiobotocore/blob/d0c0a8651a3738b6260efe962218a5738694dd2a/aiobotocore/client.py#L178-L199
8,494
gabrielfalcao/HTTPretty
httpretty/core.py
url_fix
def url_fix(s, charset=None): """escapes special characters """ if charset: warnings.warn("{}.url_fix() charset argument is deprecated".format(__name__), DeprecationWarning) scheme, netloc, path, querystring, fragment = urlsplit(s) path = quote(path, b'/%') querystring = quote_plus(querystring, b':&=') return urlunsplit((scheme, netloc, path, querystring, fragment))
python
def url_fix(s, charset=None): """escapes special characters """ if charset: warnings.warn("{}.url_fix() charset argument is deprecated".format(__name__), DeprecationWarning) scheme, netloc, path, querystring, fragment = urlsplit(s) path = quote(path, b'/%') querystring = quote_plus(querystring, b':&=') return urlunsplit((scheme, netloc, path, querystring, fragment))
[ "def", "url_fix", "(", "s", ",", "charset", "=", "None", ")", ":", "if", "charset", ":", "warnings", ".", "warn", "(", "\"{}.url_fix() charset argument is deprecated\"", ".", "format", "(", "__name__", ")", ",", "DeprecationWarning", ")", "scheme", ",", "netloc", ",", "path", ",", "querystring", ",", "fragment", "=", "urlsplit", "(", "s", ")", "path", "=", "quote", "(", "path", ",", "b'/%'", ")", "querystring", "=", "quote_plus", "(", "querystring", ",", "b':&='", ")", "return", "urlunsplit", "(", "(", "scheme", ",", "netloc", ",", "path", ",", "querystring", ",", "fragment", ")", ")" ]
escapes special characters
[ "escapes", "special", "characters" ]
91dab803011d190c4602cf4c2a07a19835a092e3
https://github.com/gabrielfalcao/HTTPretty/blob/91dab803011d190c4602cf4c2a07a19835a092e3/httpretty/core.py#L831-L840
8,495
gabrielfalcao/HTTPretty
httpretty/core.py
httprettified
def httprettified(test=None, allow_net_connect=True): """decorator for test functions .. tip:: Also available under the alias :py:func:`httpretty.activate` :param test: a callable example usage with `nosetests <https://nose.readthedocs.io/en/latest/>`_ .. testcode:: import sure from httpretty import httprettified @httprettified def test_using_nosetests(): httpretty.register_uri( httpretty.GET, 'https://httpbin.org/ip' ) response = requests.get('https://httpbin.org/ip') response.json().should.equal({ "message": "HTTPretty :)" }) example usage with `unittest module <https://docs.python.org/3/library/unittest.html>`_ .. testcode:: import unittest from sure import expect from httpretty import httprettified @httprettified class TestWithPyUnit(unittest.TestCase): def test_httpbin(self): httpretty.register_uri(httpretty.GET, 'https://httpbin.org/ip') response = requests.get('https://httpbin.org/ip') expect(response.json()).to.equal({ "message": "HTTPretty :)" }) """ def decorate_unittest_TestCase_setUp(klass): # Prefer addCleanup (added in python 2.7), but fall back # to using tearDown if it isn't available use_addCleanup = hasattr(klass, 'addCleanup') original_setUp = (klass.setUp if hasattr(klass, 'setUp') else None) def new_setUp(self): httpretty.reset() httpretty.enable(allow_net_connect) if use_addCleanup: self.addCleanup(httpretty.disable) if original_setUp: original_setUp(self) klass.setUp = new_setUp if not use_addCleanup: original_tearDown = (klass.setUp if hasattr(klass, 'tearDown') else None) def new_tearDown(self): httpretty.disable() httpretty.reset() if original_tearDown: original_tearDown(self) klass.tearDown = new_tearDown return klass def decorate_test_methods(klass): for attr in dir(klass): if not attr.startswith('test_'): continue attr_value = getattr(klass, attr) if not hasattr(attr_value, "__call__"): continue setattr(klass, attr, decorate_callable(attr_value)) return klass def is_unittest_TestCase(klass): try: import unittest return issubclass(klass, unittest.TestCase) except ImportError: return False "A decorator for tests that use HTTPretty" def decorate_class(klass): if is_unittest_TestCase(klass): return decorate_unittest_TestCase_setUp(klass) return decorate_test_methods(klass) def decorate_callable(test): @functools.wraps(test) def wrapper(*args, **kw): with httprettized(allow_net_connect): return test(*args, **kw) return wrapper if isinstance(test, ClassTypes): return decorate_class(test) elif callable(test): return decorate_callable(test) return decorate_callable
python
def httprettified(test=None, allow_net_connect=True): """decorator for test functions .. tip:: Also available under the alias :py:func:`httpretty.activate` :param test: a callable example usage with `nosetests <https://nose.readthedocs.io/en/latest/>`_ .. testcode:: import sure from httpretty import httprettified @httprettified def test_using_nosetests(): httpretty.register_uri( httpretty.GET, 'https://httpbin.org/ip' ) response = requests.get('https://httpbin.org/ip') response.json().should.equal({ "message": "HTTPretty :)" }) example usage with `unittest module <https://docs.python.org/3/library/unittest.html>`_ .. testcode:: import unittest from sure import expect from httpretty import httprettified @httprettified class TestWithPyUnit(unittest.TestCase): def test_httpbin(self): httpretty.register_uri(httpretty.GET, 'https://httpbin.org/ip') response = requests.get('https://httpbin.org/ip') expect(response.json()).to.equal({ "message": "HTTPretty :)" }) """ def decorate_unittest_TestCase_setUp(klass): # Prefer addCleanup (added in python 2.7), but fall back # to using tearDown if it isn't available use_addCleanup = hasattr(klass, 'addCleanup') original_setUp = (klass.setUp if hasattr(klass, 'setUp') else None) def new_setUp(self): httpretty.reset() httpretty.enable(allow_net_connect) if use_addCleanup: self.addCleanup(httpretty.disable) if original_setUp: original_setUp(self) klass.setUp = new_setUp if not use_addCleanup: original_tearDown = (klass.setUp if hasattr(klass, 'tearDown') else None) def new_tearDown(self): httpretty.disable() httpretty.reset() if original_tearDown: original_tearDown(self) klass.tearDown = new_tearDown return klass def decorate_test_methods(klass): for attr in dir(klass): if not attr.startswith('test_'): continue attr_value = getattr(klass, attr) if not hasattr(attr_value, "__call__"): continue setattr(klass, attr, decorate_callable(attr_value)) return klass def is_unittest_TestCase(klass): try: import unittest return issubclass(klass, unittest.TestCase) except ImportError: return False "A decorator for tests that use HTTPretty" def decorate_class(klass): if is_unittest_TestCase(klass): return decorate_unittest_TestCase_setUp(klass) return decorate_test_methods(klass) def decorate_callable(test): @functools.wraps(test) def wrapper(*args, **kw): with httprettized(allow_net_connect): return test(*args, **kw) return wrapper if isinstance(test, ClassTypes): return decorate_class(test) elif callable(test): return decorate_callable(test) return decorate_callable
[ "def", "httprettified", "(", "test", "=", "None", ",", "allow_net_connect", "=", "True", ")", ":", "def", "decorate_unittest_TestCase_setUp", "(", "klass", ")", ":", "# Prefer addCleanup (added in python 2.7), but fall back", "# to using tearDown if it isn't available", "use_addCleanup", "=", "hasattr", "(", "klass", ",", "'addCleanup'", ")", "original_setUp", "=", "(", "klass", ".", "setUp", "if", "hasattr", "(", "klass", ",", "'setUp'", ")", "else", "None", ")", "def", "new_setUp", "(", "self", ")", ":", "httpretty", ".", "reset", "(", ")", "httpretty", ".", "enable", "(", "allow_net_connect", ")", "if", "use_addCleanup", ":", "self", ".", "addCleanup", "(", "httpretty", ".", "disable", ")", "if", "original_setUp", ":", "original_setUp", "(", "self", ")", "klass", ".", "setUp", "=", "new_setUp", "if", "not", "use_addCleanup", ":", "original_tearDown", "=", "(", "klass", ".", "setUp", "if", "hasattr", "(", "klass", ",", "'tearDown'", ")", "else", "None", ")", "def", "new_tearDown", "(", "self", ")", ":", "httpretty", ".", "disable", "(", ")", "httpretty", ".", "reset", "(", ")", "if", "original_tearDown", ":", "original_tearDown", "(", "self", ")", "klass", ".", "tearDown", "=", "new_tearDown", "return", "klass", "def", "decorate_test_methods", "(", "klass", ")", ":", "for", "attr", "in", "dir", "(", "klass", ")", ":", "if", "not", "attr", ".", "startswith", "(", "'test_'", ")", ":", "continue", "attr_value", "=", "getattr", "(", "klass", ",", "attr", ")", "if", "not", "hasattr", "(", "attr_value", ",", "\"__call__\"", ")", ":", "continue", "setattr", "(", "klass", ",", "attr", ",", "decorate_callable", "(", "attr_value", ")", ")", "return", "klass", "def", "is_unittest_TestCase", "(", "klass", ")", ":", "try", ":", "import", "unittest", "return", "issubclass", "(", "klass", ",", "unittest", ".", "TestCase", ")", "except", "ImportError", ":", "return", "False", "\"A decorator for tests that use HTTPretty\"", "def", "decorate_class", "(", "klass", ")", ":", "if", "is_unittest_TestCase", "(", "klass", ")", ":", "return", "decorate_unittest_TestCase_setUp", "(", "klass", ")", "return", "decorate_test_methods", "(", "klass", ")", "def", "decorate_callable", "(", "test", ")", ":", "@", "functools", ".", "wraps", "(", "test", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "with", "httprettized", "(", "allow_net_connect", ")", ":", "return", "test", "(", "*", "args", ",", "*", "*", "kw", ")", "return", "wrapper", "if", "isinstance", "(", "test", ",", "ClassTypes", ")", ":", "return", "decorate_class", "(", "test", ")", "elif", "callable", "(", "test", ")", ":", "return", "decorate_callable", "(", "test", ")", "return", "decorate_callable" ]
decorator for test functions .. tip:: Also available under the alias :py:func:`httpretty.activate` :param test: a callable example usage with `nosetests <https://nose.readthedocs.io/en/latest/>`_ .. testcode:: import sure from httpretty import httprettified @httprettified def test_using_nosetests(): httpretty.register_uri( httpretty.GET, 'https://httpbin.org/ip' ) response = requests.get('https://httpbin.org/ip') response.json().should.equal({ "message": "HTTPretty :)" }) example usage with `unittest module <https://docs.python.org/3/library/unittest.html>`_ .. testcode:: import unittest from sure import expect from httpretty import httprettified @httprettified class TestWithPyUnit(unittest.TestCase): def test_httpbin(self): httpretty.register_uri(httpretty.GET, 'https://httpbin.org/ip') response = requests.get('https://httpbin.org/ip') expect(response.json()).to.equal({ "message": "HTTPretty :)" })
[ "decorator", "for", "test", "functions" ]
91dab803011d190c4602cf4c2a07a19835a092e3
https://github.com/gabrielfalcao/HTTPretty/blob/91dab803011d190c4602cf4c2a07a19835a092e3/httpretty/core.py#L1594-L1709
8,496
gabrielfalcao/HTTPretty
httpretty/core.py
HTTPrettyRequest.parse_request_body
def parse_request_body(self, body): """Attempt to parse the post based on the content-type passed. Return the regular body if not :param body: string :returns: a python object such as dict or list in case the deserialization suceeded. Else returns the given param ``body`` """ PARSING_FUNCTIONS = { 'application/json': json.loads, 'text/json': json.loads, 'application/x-www-form-urlencoded': self.parse_querystring, } content_type = self.headers.get('content-type', '') do_parse = PARSING_FUNCTIONS.get(content_type, FALLBACK_FUNCTION) try: body = decode_utf8(body) return do_parse(body) except (Exception, BaseException): return body
python
def parse_request_body(self, body): """Attempt to parse the post based on the content-type passed. Return the regular body if not :param body: string :returns: a python object such as dict or list in case the deserialization suceeded. Else returns the given param ``body`` """ PARSING_FUNCTIONS = { 'application/json': json.loads, 'text/json': json.loads, 'application/x-www-form-urlencoded': self.parse_querystring, } content_type = self.headers.get('content-type', '') do_parse = PARSING_FUNCTIONS.get(content_type, FALLBACK_FUNCTION) try: body = decode_utf8(body) return do_parse(body) except (Exception, BaseException): return body
[ "def", "parse_request_body", "(", "self", ",", "body", ")", ":", "PARSING_FUNCTIONS", "=", "{", "'application/json'", ":", "json", ".", "loads", ",", "'text/json'", ":", "json", ".", "loads", ",", "'application/x-www-form-urlencoded'", ":", "self", ".", "parse_querystring", ",", "}", "content_type", "=", "self", ".", "headers", ".", "get", "(", "'content-type'", ",", "''", ")", "do_parse", "=", "PARSING_FUNCTIONS", ".", "get", "(", "content_type", ",", "FALLBACK_FUNCTION", ")", "try", ":", "body", "=", "decode_utf8", "(", "body", ")", "return", "do_parse", "(", "body", ")", "except", "(", "Exception", ",", "BaseException", ")", ":", "return", "body" ]
Attempt to parse the post based on the content-type passed. Return the regular body if not :param body: string :returns: a python object such as dict or list in case the deserialization suceeded. Else returns the given param ``body``
[ "Attempt", "to", "parse", "the", "post", "based", "on", "the", "content", "-", "type", "passed", ".", "Return", "the", "regular", "body", "if", "not" ]
91dab803011d190c4602cf4c2a07a19835a092e3
https://github.com/gabrielfalcao/HTTPretty/blob/91dab803011d190c4602cf4c2a07a19835a092e3/httpretty/core.py#L256-L277
8,497
gabrielfalcao/HTTPretty
httpretty/core.py
Entry.fill_filekind
def fill_filekind(self, fk): """writes HTTP Response data to a file descriptor :parm fk: a file-like object .. warning:: **side-effect:** this method moves the cursor of the given file object to zero """ now = datetime.utcnow() headers = { 'status': self.status, 'date': now.strftime('%a, %d %b %Y %H:%M:%S GMT'), 'server': 'Python/HTTPretty', 'connection': 'close', } if self.forcing_headers: headers = self.forcing_headers if self.adding_headers: headers.update( self.normalize_headers( self.adding_headers)) headers = self.normalize_headers(headers) status = headers.get('status', self.status) if self.body_is_callable: status, headers, self.body = self.callable_body(self.request, self.info.full_url(), headers) headers = self.normalize_headers(headers) # TODO: document this behavior: if 'content-length' not in headers: headers.update({ 'content-length': len(self.body) }) string_list = [ 'HTTP/1.1 %d %s' % (status, STATUSES[status]), ] if 'date' in headers: string_list.append('date: %s' % headers.pop('date')) if not self.forcing_headers: content_type = headers.pop('content-type', 'text/plain; charset=utf-8') content_length = headers.pop('content-length', self.body_length) string_list.append('content-type: %s' % content_type) if not self.streaming: string_list.append('content-length: %s' % content_length) server = headers.pop('server', None) if server: string_list.append('server: %s' % server) for k, v in headers.items(): string_list.append( '{}: {}'.format(k, v), ) for item in string_list: fk.write(utf8(item) + b'\n') fk.write(b'\r\n') if self.streaming: self.body, body = itertools.tee(self.body) for chunk in body: fk.write(utf8(chunk)) else: fk.write(utf8(self.body)) fk.seek(0)
python
def fill_filekind(self, fk): """writes HTTP Response data to a file descriptor :parm fk: a file-like object .. warning:: **side-effect:** this method moves the cursor of the given file object to zero """ now = datetime.utcnow() headers = { 'status': self.status, 'date': now.strftime('%a, %d %b %Y %H:%M:%S GMT'), 'server': 'Python/HTTPretty', 'connection': 'close', } if self.forcing_headers: headers = self.forcing_headers if self.adding_headers: headers.update( self.normalize_headers( self.adding_headers)) headers = self.normalize_headers(headers) status = headers.get('status', self.status) if self.body_is_callable: status, headers, self.body = self.callable_body(self.request, self.info.full_url(), headers) headers = self.normalize_headers(headers) # TODO: document this behavior: if 'content-length' not in headers: headers.update({ 'content-length': len(self.body) }) string_list = [ 'HTTP/1.1 %d %s' % (status, STATUSES[status]), ] if 'date' in headers: string_list.append('date: %s' % headers.pop('date')) if not self.forcing_headers: content_type = headers.pop('content-type', 'text/plain; charset=utf-8') content_length = headers.pop('content-length', self.body_length) string_list.append('content-type: %s' % content_type) if not self.streaming: string_list.append('content-length: %s' % content_length) server = headers.pop('server', None) if server: string_list.append('server: %s' % server) for k, v in headers.items(): string_list.append( '{}: {}'.format(k, v), ) for item in string_list: fk.write(utf8(item) + b'\n') fk.write(b'\r\n') if self.streaming: self.body, body = itertools.tee(self.body) for chunk in body: fk.write(utf8(chunk)) else: fk.write(utf8(self.body)) fk.seek(0)
[ "def", "fill_filekind", "(", "self", ",", "fk", ")", ":", "now", "=", "datetime", ".", "utcnow", "(", ")", "headers", "=", "{", "'status'", ":", "self", ".", "status", ",", "'date'", ":", "now", ".", "strftime", "(", "'%a, %d %b %Y %H:%M:%S GMT'", ")", ",", "'server'", ":", "'Python/HTTPretty'", ",", "'connection'", ":", "'close'", ",", "}", "if", "self", ".", "forcing_headers", ":", "headers", "=", "self", ".", "forcing_headers", "if", "self", ".", "adding_headers", ":", "headers", ".", "update", "(", "self", ".", "normalize_headers", "(", "self", ".", "adding_headers", ")", ")", "headers", "=", "self", ".", "normalize_headers", "(", "headers", ")", "status", "=", "headers", ".", "get", "(", "'status'", ",", "self", ".", "status", ")", "if", "self", ".", "body_is_callable", ":", "status", ",", "headers", ",", "self", ".", "body", "=", "self", ".", "callable_body", "(", "self", ".", "request", ",", "self", ".", "info", ".", "full_url", "(", ")", ",", "headers", ")", "headers", "=", "self", ".", "normalize_headers", "(", "headers", ")", "# TODO: document this behavior:", "if", "'content-length'", "not", "in", "headers", ":", "headers", ".", "update", "(", "{", "'content-length'", ":", "len", "(", "self", ".", "body", ")", "}", ")", "string_list", "=", "[", "'HTTP/1.1 %d %s'", "%", "(", "status", ",", "STATUSES", "[", "status", "]", ")", ",", "]", "if", "'date'", "in", "headers", ":", "string_list", ".", "append", "(", "'date: %s'", "%", "headers", ".", "pop", "(", "'date'", ")", ")", "if", "not", "self", ".", "forcing_headers", ":", "content_type", "=", "headers", ".", "pop", "(", "'content-type'", ",", "'text/plain; charset=utf-8'", ")", "content_length", "=", "headers", ".", "pop", "(", "'content-length'", ",", "self", ".", "body_length", ")", "string_list", ".", "append", "(", "'content-type: %s'", "%", "content_type", ")", "if", "not", "self", ".", "streaming", ":", "string_list", ".", "append", "(", "'content-length: %s'", "%", "content_length", ")", "server", "=", "headers", ".", "pop", "(", "'server'", ",", "None", ")", "if", "server", ":", "string_list", ".", "append", "(", "'server: %s'", "%", "server", ")", "for", "k", ",", "v", "in", "headers", ".", "items", "(", ")", ":", "string_list", ".", "append", "(", "'{}: {}'", ".", "format", "(", "k", ",", "v", ")", ",", ")", "for", "item", "in", "string_list", ":", "fk", ".", "write", "(", "utf8", "(", "item", ")", "+", "b'\\n'", ")", "fk", ".", "write", "(", "b'\\r\\n'", ")", "if", "self", ".", "streaming", ":", "self", ".", "body", ",", "body", "=", "itertools", ".", "tee", "(", "self", ".", "body", ")", "for", "chunk", "in", "body", ":", "fk", ".", "write", "(", "utf8", "(", "chunk", ")", ")", "else", ":", "fk", ".", "write", "(", "utf8", "(", "self", ".", "body", ")", ")", "fk", ".", "seek", "(", "0", ")" ]
writes HTTP Response data to a file descriptor :parm fk: a file-like object .. warning:: **side-effect:** this method moves the cursor of the given file object to zero
[ "writes", "HTTP", "Response", "data", "to", "a", "file", "descriptor" ]
91dab803011d190c4602cf4c2a07a19835a092e3
https://github.com/gabrielfalcao/HTTPretty/blob/91dab803011d190c4602cf4c2a07a19835a092e3/httpretty/core.py#L754-L828
8,498
trehn/termdown
termdown.py
draw_text
def draw_text(stdscr, text, color=0, fallback=None, title=None): """ Draws text in the given color. Duh. """ if fallback is None: fallback = text y, x = stdscr.getmaxyx() if title: title = pad_to_size(title, x, 1) if "\n" in title.rstrip("\n"): # hack to get more spacing between title and body for figlet title += "\n" * 5 text = title + "\n" + pad_to_size(text, x, len(text.split("\n"))) lines = pad_to_size(text, x, y).rstrip("\n").split("\n") try: for i, line in enumerate(lines): stdscr.insstr(i, 0, line, curses.color_pair(color)) except: lines = pad_to_size(fallback, x, y).rstrip("\n").split("\n") try: for i, line in enumerate(lines[:]): stdscr.insstr(i, 0, line, curses.color_pair(color)) except: pass stdscr.refresh()
python
def draw_text(stdscr, text, color=0, fallback=None, title=None): """ Draws text in the given color. Duh. """ if fallback is None: fallback = text y, x = stdscr.getmaxyx() if title: title = pad_to_size(title, x, 1) if "\n" in title.rstrip("\n"): # hack to get more spacing between title and body for figlet title += "\n" * 5 text = title + "\n" + pad_to_size(text, x, len(text.split("\n"))) lines = pad_to_size(text, x, y).rstrip("\n").split("\n") try: for i, line in enumerate(lines): stdscr.insstr(i, 0, line, curses.color_pair(color)) except: lines = pad_to_size(fallback, x, y).rstrip("\n").split("\n") try: for i, line in enumerate(lines[:]): stdscr.insstr(i, 0, line, curses.color_pair(color)) except: pass stdscr.refresh()
[ "def", "draw_text", "(", "stdscr", ",", "text", ",", "color", "=", "0", ",", "fallback", "=", "None", ",", "title", "=", "None", ")", ":", "if", "fallback", "is", "None", ":", "fallback", "=", "text", "y", ",", "x", "=", "stdscr", ".", "getmaxyx", "(", ")", "if", "title", ":", "title", "=", "pad_to_size", "(", "title", ",", "x", ",", "1", ")", "if", "\"\\n\"", "in", "title", ".", "rstrip", "(", "\"\\n\"", ")", ":", "# hack to get more spacing between title and body for figlet", "title", "+=", "\"\\n\"", "*", "5", "text", "=", "title", "+", "\"\\n\"", "+", "pad_to_size", "(", "text", ",", "x", ",", "len", "(", "text", ".", "split", "(", "\"\\n\"", ")", ")", ")", "lines", "=", "pad_to_size", "(", "text", ",", "x", ",", "y", ")", ".", "rstrip", "(", "\"\\n\"", ")", ".", "split", "(", "\"\\n\"", ")", "try", ":", "for", "i", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "stdscr", ".", "insstr", "(", "i", ",", "0", ",", "line", ",", "curses", ".", "color_pair", "(", "color", ")", ")", "except", ":", "lines", "=", "pad_to_size", "(", "fallback", ",", "x", ",", "y", ")", ".", "rstrip", "(", "\"\\n\"", ")", ".", "split", "(", "\"\\n\"", ")", "try", ":", "for", "i", ",", "line", "in", "enumerate", "(", "lines", "[", ":", "]", ")", ":", "stdscr", ".", "insstr", "(", "i", ",", "0", ",", "line", ",", "curses", ".", "color_pair", "(", "color", ")", ")", "except", ":", "pass", "stdscr", ".", "refresh", "(", ")" ]
Draws text in the given color. Duh.
[ "Draws", "text", "in", "the", "given", "color", ".", "Duh", "." ]
aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2
https://github.com/trehn/termdown/blob/aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2/termdown.py#L70-L95
8,499
trehn/termdown
termdown.py
format_seconds
def format_seconds(seconds, hide_seconds=False): """ Returns a human-readable string representation of the given amount of seconds. """ if seconds <= 60: return str(seconds) output = "" for period, period_seconds in ( ('y', 31557600), ('d', 86400), ('h', 3600), ('m', 60), ('s', 1), ): if seconds >= period_seconds and not (hide_seconds and period == 's'): output += str(int(seconds / period_seconds)) output += period output += " " seconds = seconds % period_seconds return output.strip()
python
def format_seconds(seconds, hide_seconds=False): """ Returns a human-readable string representation of the given amount of seconds. """ if seconds <= 60: return str(seconds) output = "" for period, period_seconds in ( ('y', 31557600), ('d', 86400), ('h', 3600), ('m', 60), ('s', 1), ): if seconds >= period_seconds and not (hide_seconds and period == 's'): output += str(int(seconds / period_seconds)) output += period output += " " seconds = seconds % period_seconds return output.strip()
[ "def", "format_seconds", "(", "seconds", ",", "hide_seconds", "=", "False", ")", ":", "if", "seconds", "<=", "60", ":", "return", "str", "(", "seconds", ")", "output", "=", "\"\"", "for", "period", ",", "period_seconds", "in", "(", "(", "'y'", ",", "31557600", ")", ",", "(", "'d'", ",", "86400", ")", ",", "(", "'h'", ",", "3600", ")", ",", "(", "'m'", ",", "60", ")", ",", "(", "'s'", ",", "1", ")", ",", ")", ":", "if", "seconds", ">=", "period_seconds", "and", "not", "(", "hide_seconds", "and", "period", "==", "'s'", ")", ":", "output", "+=", "str", "(", "int", "(", "seconds", "/", "period_seconds", ")", ")", "output", "+=", "period", "output", "+=", "\" \"", "seconds", "=", "seconds", "%", "period_seconds", "return", "output", ".", "strip", "(", ")" ]
Returns a human-readable string representation of the given amount of seconds.
[ "Returns", "a", "human", "-", "readable", "string", "representation", "of", "the", "given", "amount", "of", "seconds", "." ]
aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2
https://github.com/trehn/termdown/blob/aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2/termdown.py#L98-L118