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
225,700
sosreport/sos
sos/plugins/origin.py
OpenShiftOrigin.is_static_etcd
def is_static_etcd(self): '''Determine if we are on a node running etcd''' return os.path.exists(os.path.join(self.static_pod_dir, "etcd.yaml"))
python
def is_static_etcd(self): '''Determine if we are on a node running etcd''' return os.path.exists(os.path.join(self.static_pod_dir, "etcd.yaml"))
[ "def", "is_static_etcd", "(", "self", ")", ":", "return", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "self", ".", "static_pod_dir", ",", "\"etcd.yaml\"", ")", ")" ]
Determine if we are on a node running etcd
[ "Determine", "if", "we", "are", "on", "a", "node", "running", "etcd" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/origin.py#L78-L80
225,701
sosreport/sos
sos/plugins/networking.py
Networking.get_ip_netns
def get_ip_netns(self, ip_netns_file): """Returns a list for which items are namespaces in the output of ip netns stored in the ip_netns_file. """ out = [] try: ip_netns_out = open(ip_netns_file).read() except IOError: return out for line in ip_netns_out.splitlines(): # If there's no namespaces, no need to continue if line.startswith("Object \"netns\" is unknown") \ or line.isspace() \ or line[:1].isspace(): return out out.append(line.partition(' ')[0]) return out
python
def get_ip_netns(self, ip_netns_file): """Returns a list for which items are namespaces in the output of ip netns stored in the ip_netns_file. """ out = [] try: ip_netns_out = open(ip_netns_file).read() except IOError: return out for line in ip_netns_out.splitlines(): # If there's no namespaces, no need to continue if line.startswith("Object \"netns\" is unknown") \ or line.isspace() \ or line[:1].isspace(): return out out.append(line.partition(' ')[0]) return out
[ "def", "get_ip_netns", "(", "self", ",", "ip_netns_file", ")", ":", "out", "=", "[", "]", "try", ":", "ip_netns_out", "=", "open", "(", "ip_netns_file", ")", ".", "read", "(", ")", "except", "IOError", ":", "return", "out", "for", "line", "in", "ip_net...
Returns a list for which items are namespaces in the output of ip netns stored in the ip_netns_file.
[ "Returns", "a", "list", "for", "which", "items", "are", "namespaces", "in", "the", "output", "of", "ip", "netns", "stored", "in", "the", "ip_netns_file", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/networking.py#L28-L44
225,702
sosreport/sos
sos/plugins/networking.py
Networking.collect_iptable
def collect_iptable(self, tablename): """ When running the iptables command, it unfortunately auto-loads the modules before trying to get output. Some people explicitly don't want this, so check if the modules are loaded before running the command. If they aren't loaded, there can't possibly be any relevant rules in that table """ modname = "iptable_"+tablename if self.check_ext_prog("grep -q %s /proc/modules" % modname): cmd = "iptables -t "+tablename+" -nvL" self.add_cmd_output(cmd)
python
def collect_iptable(self, tablename): """ When running the iptables command, it unfortunately auto-loads the modules before trying to get output. Some people explicitly don't want this, so check if the modules are loaded before running the command. If they aren't loaded, there can't possibly be any relevant rules in that table """ modname = "iptable_"+tablename if self.check_ext_prog("grep -q %s /proc/modules" % modname): cmd = "iptables -t "+tablename+" -nvL" self.add_cmd_output(cmd)
[ "def", "collect_iptable", "(", "self", ",", "tablename", ")", ":", "modname", "=", "\"iptable_\"", "+", "tablename", "if", "self", ".", "check_ext_prog", "(", "\"grep -q %s /proc/modules\"", "%", "modname", ")", ":", "cmd", "=", "\"iptables -t \"", "+", "tablena...
When running the iptables command, it unfortunately auto-loads the modules before trying to get output. Some people explicitly don't want this, so check if the modules are loaded before running the command. If they aren't loaded, there can't possibly be any relevant rules in that table
[ "When", "running", "the", "iptables", "command", "it", "unfortunately", "auto", "-", "loads", "the", "modules", "before", "trying", "to", "get", "output", ".", "Some", "people", "explicitly", "don", "t", "want", "this", "so", "check", "if", "the", "modules",...
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/networking.py#L46-L56
225,703
sosreport/sos
sos/plugins/networking.py
Networking.collect_ip6table
def collect_ip6table(self, tablename): """ Same as function above, but for ipv6 """ modname = "ip6table_"+tablename if self.check_ext_prog("grep -q %s /proc/modules" % modname): cmd = "ip6tables -t "+tablename+" -nvL" self.add_cmd_output(cmd)
python
def collect_ip6table(self, tablename): """ Same as function above, but for ipv6 """ modname = "ip6table_"+tablename if self.check_ext_prog("grep -q %s /proc/modules" % modname): cmd = "ip6tables -t "+tablename+" -nvL" self.add_cmd_output(cmd)
[ "def", "collect_ip6table", "(", "self", ",", "tablename", ")", ":", "modname", "=", "\"ip6table_\"", "+", "tablename", "if", "self", ".", "check_ext_prog", "(", "\"grep -q %s /proc/modules\"", "%", "modname", ")", ":", "cmd", "=", "\"ip6tables -t \"", "+", "tabl...
Same as function above, but for ipv6
[ "Same", "as", "function", "above", "but", "for", "ipv6" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/networking.py#L58-L64
225,704
sosreport/sos
sos/plugins/ovirt.py
Ovirt.postproc
def postproc(self): """ Obfuscate sensitive keys. """ self.do_file_sub( "/etc/ovirt-engine/engine-config/engine-config.properties", r"Password.type=(.*)", r"Password.type=********" ) self.do_file_sub( "/etc/rhevm/rhevm-config/rhevm-config.properties", r"Password.type=(.*)", r"Password.type=********" ) engine_files = ( 'ovirt-engine.xml', 'ovirt-engine_history/current/ovirt-engine.v1.xml', 'ovirt-engine_history/ovirt-engine.boot.xml', 'ovirt-engine_history/ovirt-engine.initial.xml', 'ovirt-engine_history/ovirt-engine.last.xml', ) for filename in engine_files: self.do_file_sub( "/var/tmp/ovirt-engine/config/%s" % filename, r"<password>(.*)</password>", r"<password>********</password>" ) self.do_file_sub( "/etc/ovirt-engine/redhatsupportplugin.conf", r"proxyPassword=(.*)", r"proxyPassword=********" ) passwd_files = [ "logcollector.conf", "imageuploader.conf", "isouploader.conf" ] for conf_file in passwd_files: conf_path = os.path.join("/etc/ovirt-engine", conf_file) self.do_file_sub( conf_path, r"passwd=(.*)", r"passwd=********" ) self.do_file_sub( conf_path, r"pg-pass=(.*)", r"pg-pass=********" ) sensitive_keys = self.DEFAULT_SENSITIVE_KEYS # Handle --alloptions case which set this to True. keys_opt = self.get_option('sensitive_keys') if keys_opt and keys_opt is not True: sensitive_keys = keys_opt key_list = [x for x in sensitive_keys.split(':') if x] for key in key_list: self.do_path_regex_sub( self.DB_PASS_FILES, r'{key}=(.*)'.format(key=key), r'{key}=********'.format(key=key) ) # Answer files contain passwords for key in ( 'OVESETUP_CONFIG/adminPassword', 'OVESETUP_CONFIG/remoteEngineHostRootPassword', 'OVESETUP_DWH_DB/password', 'OVESETUP_DB/password', 'OVESETUP_REPORTS_CONFIG/adminPassword', 'OVESETUP_REPORTS_DB/password', ): self.do_path_regex_sub( r'/var/lib/ovirt-engine/setup/answers/.*', r'{key}=(.*)'.format(key=key), r'{key}=********'.format(key=key) ) # aaa profiles contain passwords protect_keys = [ "vars.password", "pool.default.auth.simple.password", "pool.default.ssl.truststore.password", "config.datasource.dbpassword" ] regexp = r"((?m)^\s*#*(%s)\s*=\s*)(.*)" % "|".join(protect_keys) self.do_path_regex_sub(r"/etc/ovirt-engine/aaa/.*\.properties", regexp, r"\1*********")
python
def postproc(self): """ Obfuscate sensitive keys. """ self.do_file_sub( "/etc/ovirt-engine/engine-config/engine-config.properties", r"Password.type=(.*)", r"Password.type=********" ) self.do_file_sub( "/etc/rhevm/rhevm-config/rhevm-config.properties", r"Password.type=(.*)", r"Password.type=********" ) engine_files = ( 'ovirt-engine.xml', 'ovirt-engine_history/current/ovirt-engine.v1.xml', 'ovirt-engine_history/ovirt-engine.boot.xml', 'ovirt-engine_history/ovirt-engine.initial.xml', 'ovirt-engine_history/ovirt-engine.last.xml', ) for filename in engine_files: self.do_file_sub( "/var/tmp/ovirt-engine/config/%s" % filename, r"<password>(.*)</password>", r"<password>********</password>" ) self.do_file_sub( "/etc/ovirt-engine/redhatsupportplugin.conf", r"proxyPassword=(.*)", r"proxyPassword=********" ) passwd_files = [ "logcollector.conf", "imageuploader.conf", "isouploader.conf" ] for conf_file in passwd_files: conf_path = os.path.join("/etc/ovirt-engine", conf_file) self.do_file_sub( conf_path, r"passwd=(.*)", r"passwd=********" ) self.do_file_sub( conf_path, r"pg-pass=(.*)", r"pg-pass=********" ) sensitive_keys = self.DEFAULT_SENSITIVE_KEYS # Handle --alloptions case which set this to True. keys_opt = self.get_option('sensitive_keys') if keys_opt and keys_opt is not True: sensitive_keys = keys_opt key_list = [x for x in sensitive_keys.split(':') if x] for key in key_list: self.do_path_regex_sub( self.DB_PASS_FILES, r'{key}=(.*)'.format(key=key), r'{key}=********'.format(key=key) ) # Answer files contain passwords for key in ( 'OVESETUP_CONFIG/adminPassword', 'OVESETUP_CONFIG/remoteEngineHostRootPassword', 'OVESETUP_DWH_DB/password', 'OVESETUP_DB/password', 'OVESETUP_REPORTS_CONFIG/adminPassword', 'OVESETUP_REPORTS_DB/password', ): self.do_path_regex_sub( r'/var/lib/ovirt-engine/setup/answers/.*', r'{key}=(.*)'.format(key=key), r'{key}=********'.format(key=key) ) # aaa profiles contain passwords protect_keys = [ "vars.password", "pool.default.auth.simple.password", "pool.default.ssl.truststore.password", "config.datasource.dbpassword" ] regexp = r"((?m)^\s*#*(%s)\s*=\s*)(.*)" % "|".join(protect_keys) self.do_path_regex_sub(r"/etc/ovirt-engine/aaa/.*\.properties", regexp, r"\1*********")
[ "def", "postproc", "(", "self", ")", ":", "self", ".", "do_file_sub", "(", "\"/etc/ovirt-engine/engine-config/engine-config.properties\"", ",", "r\"Password.type=(.*)\"", ",", "r\"Password.type=********\"", ")", "self", ".", "do_file_sub", "(", "\"/etc/rhevm/rhevm-config/rhev...
Obfuscate sensitive keys.
[ "Obfuscate", "sensitive", "keys", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/ovirt.py#L135-L226
225,705
sosreport/sos
sos/plugins/watchdog.py
Watchdog.get_log_dir
def get_log_dir(self, conf_file): """Get watchdog log directory. Get watchdog log directory path configured in ``conf_file``. :returns: The watchdog log directory path. :returntype: str. :raises: IOError if ``conf_file`` is not readable. """ log_dir = None with open(conf_file, 'r') as conf_f: for line in conf_f: line = line.split('#')[0].strip() try: (key, value) = line.split('=', 1) if key.strip() == 'log-dir': log_dir = value.strip() except ValueError: pass return log_dir
python
def get_log_dir(self, conf_file): """Get watchdog log directory. Get watchdog log directory path configured in ``conf_file``. :returns: The watchdog log directory path. :returntype: str. :raises: IOError if ``conf_file`` is not readable. """ log_dir = None with open(conf_file, 'r') as conf_f: for line in conf_f: line = line.split('#')[0].strip() try: (key, value) = line.split('=', 1) if key.strip() == 'log-dir': log_dir = value.strip() except ValueError: pass return log_dir
[ "def", "get_log_dir", "(", "self", ",", "conf_file", ")", ":", "log_dir", "=", "None", "with", "open", "(", "conf_file", ",", "'r'", ")", "as", "conf_f", ":", "for", "line", "in", "conf_f", ":", "line", "=", "line", ".", "split", "(", "'#'", ")", "...
Get watchdog log directory. Get watchdog log directory path configured in ``conf_file``. :returns: The watchdog log directory path. :returntype: str. :raises: IOError if ``conf_file`` is not readable.
[ "Get", "watchdog", "log", "directory", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/watchdog.py#L27-L49
225,706
sosreport/sos
sos/plugins/watchdog.py
Watchdog.setup
def setup(self): """Collect watchdog information. Collect configuration files, custom executables for test-binary and repair-binary, and stdout/stderr logs. """ conf_file = self.get_option('conf_file') log_dir = '/var/log/watchdog' # Get service configuration and sysconfig files self.add_copy_spec([ conf_file, '/etc/sysconfig/watchdog', ]) # Get custom executables self.add_copy_spec([ '/etc/watchdog.d', '/usr/libexec/watchdog/scripts', ]) # Get logs try: res = self.get_log_dir(conf_file) if res: log_dir = res except IOError as ex: self._log_warn("Could not read %s: %s" % (conf_file, ex)) if self.get_option('all_logs'): log_files = glob(os.path.join(log_dir, '*')) else: log_files = (glob(os.path.join(log_dir, '*.stdout')) + glob(os.path.join(log_dir, '*.stderr'))) self.add_copy_spec(log_files) # Get output of "wdctl <device>" for each /dev/watchdog* for dev in glob('/dev/watchdog*'): self.add_cmd_output("wdctl %s" % dev)
python
def setup(self): """Collect watchdog information. Collect configuration files, custom executables for test-binary and repair-binary, and stdout/stderr logs. """ conf_file = self.get_option('conf_file') log_dir = '/var/log/watchdog' # Get service configuration and sysconfig files self.add_copy_spec([ conf_file, '/etc/sysconfig/watchdog', ]) # Get custom executables self.add_copy_spec([ '/etc/watchdog.d', '/usr/libexec/watchdog/scripts', ]) # Get logs try: res = self.get_log_dir(conf_file) if res: log_dir = res except IOError as ex: self._log_warn("Could not read %s: %s" % (conf_file, ex)) if self.get_option('all_logs'): log_files = glob(os.path.join(log_dir, '*')) else: log_files = (glob(os.path.join(log_dir, '*.stdout')) + glob(os.path.join(log_dir, '*.stderr'))) self.add_copy_spec(log_files) # Get output of "wdctl <device>" for each /dev/watchdog* for dev in glob('/dev/watchdog*'): self.add_cmd_output("wdctl %s" % dev)
[ "def", "setup", "(", "self", ")", ":", "conf_file", "=", "self", ".", "get_option", "(", "'conf_file'", ")", "log_dir", "=", "'/var/log/watchdog'", "# Get service configuration and sysconfig files", "self", ".", "add_copy_spec", "(", "[", "conf_file", ",", "'/etc/sy...
Collect watchdog information. Collect configuration files, custom executables for test-binary and repair-binary, and stdout/stderr logs.
[ "Collect", "watchdog", "information", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/watchdog.py#L51-L90
225,707
sosreport/sos
sos/plugins/gluster.py
Gluster.get_volume_names
def get_volume_names(self, volume_file): """Return a dictionary for which key are volume names according to the output of gluster volume info stored in volume_file. """ out = [] fp = open(volume_file, 'r') for line in fp.readlines(): if not line.startswith("Volume Name:"): continue volname = line[12:-1] out.append(volname) fp.close() return out
python
def get_volume_names(self, volume_file): """Return a dictionary for which key are volume names according to the output of gluster volume info stored in volume_file. """ out = [] fp = open(volume_file, 'r') for line in fp.readlines(): if not line.startswith("Volume Name:"): continue volname = line[12:-1] out.append(volname) fp.close() return out
[ "def", "get_volume_names", "(", "self", ",", "volume_file", ")", ":", "out", "=", "[", "]", "fp", "=", "open", "(", "volume_file", ",", "'r'", ")", "for", "line", "in", "fp", ".", "readlines", "(", ")", ":", "if", "not", "line", ".", "startswith", ...
Return a dictionary for which key are volume names according to the output of gluster volume info stored in volume_file.
[ "Return", "a", "dictionary", "for", "which", "key", "are", "volume", "names", "according", "to", "the", "output", "of", "gluster", "volume", "info", "stored", "in", "volume_file", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/gluster.py#L29-L41
225,708
sosreport/sos
sos/policies/ubuntu.py
UbuntuPolicy.dist_version
def dist_version(self): """ Returns the version stated in DISTRIB_RELEASE """ try: with open('/etc/lsb-release', 'r') as fp: lines = fp.readlines() for line in lines: if "DISTRIB_RELEASE" in line: return line.split("=")[1].strip() return False except IOError: return False
python
def dist_version(self): """ Returns the version stated in DISTRIB_RELEASE """ try: with open('/etc/lsb-release', 'r') as fp: lines = fp.readlines() for line in lines: if "DISTRIB_RELEASE" in line: return line.split("=")[1].strip() return False except IOError: return False
[ "def", "dist_version", "(", "self", ")", ":", "try", ":", "with", "open", "(", "'/etc/lsb-release'", ",", "'r'", ")", "as", "fp", ":", "lines", "=", "fp", ".", "readlines", "(", ")", "for", "line", "in", "lines", ":", "if", "\"DISTRIB_RELEASE\"", "in",...
Returns the version stated in DISTRIB_RELEASE
[ "Returns", "the", "version", "stated", "in", "DISTRIB_RELEASE" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/ubuntu.py#L26-L37
225,709
sosreport/sos
sos/archive.py
FileCacheArchive._make_leading_paths
def _make_leading_paths(self, src, mode=0o700): """Create leading path components The standard python `os.makedirs` is insufficient for our needs: it will only create directories, and ignores the fact that some path components may be symbolic links. :param src: The source path in the host file system for which leading components should be created, or the path to an sos_* virtual directory inside the archive. Host paths must be absolute (initial '/'), and sos_* directory paths must be a path relative to the root of the archive. :param mode: An optional mode to be used when creating path components. :returns: A rewritten destination path in the case that one or more symbolic links in intermediate components of the path have altered the path destination. """ self.log_debug("Making leading paths for %s" % src) root = self._archive_root dest = src def in_archive(path): """Test whether path ``path`` is inside the archive. """ return path.startswith(os.path.join(root, "")) if not src.startswith("/"): # Sos archive path (sos_commands, sos_logs etc.) src_dir = src else: # Host file path src_dir = src if os.path.isdir(src) else os.path.split(src)[0] # Build a list of path components in root-to-leaf order. path = src_dir path_comps = [] while path != '/' and path != '': head, tail = os.path.split(path) path_comps.append(tail) path = head path_comps.reverse() abs_path = root src_path = "/" # Check and create components as needed for comp in path_comps: abs_path = os.path.join(abs_path, comp) # Do not create components that are above the archive root. if not in_archive(abs_path): continue src_path = os.path.join(src_path, comp) if not os.path.exists(abs_path): self.log_debug("Making path %s" % abs_path) if os.path.islink(src_path) and os.path.isdir(src_path): target = os.readlink(src_path) # The directory containing the source in the host fs, # adjusted for the current level of path creation. target_dir = os.path.split(src_path)[0] # The source path of the target in the host fs to be # recursively copied. target_src = os.path.join(target_dir, target) # Recursively create leading components of target dest = self._make_leading_paths(target_src, mode=mode) dest = os.path.normpath(dest) self.log_debug("Making symlink '%s' -> '%s'" % (abs_path, target)) os.symlink(target, abs_path) else: self.log_debug("Making directory %s" % abs_path) os.mkdir(abs_path, mode) dest = src_path return dest
python
def _make_leading_paths(self, src, mode=0o700): """Create leading path components The standard python `os.makedirs` is insufficient for our needs: it will only create directories, and ignores the fact that some path components may be symbolic links. :param src: The source path in the host file system for which leading components should be created, or the path to an sos_* virtual directory inside the archive. Host paths must be absolute (initial '/'), and sos_* directory paths must be a path relative to the root of the archive. :param mode: An optional mode to be used when creating path components. :returns: A rewritten destination path in the case that one or more symbolic links in intermediate components of the path have altered the path destination. """ self.log_debug("Making leading paths for %s" % src) root = self._archive_root dest = src def in_archive(path): """Test whether path ``path`` is inside the archive. """ return path.startswith(os.path.join(root, "")) if not src.startswith("/"): # Sos archive path (sos_commands, sos_logs etc.) src_dir = src else: # Host file path src_dir = src if os.path.isdir(src) else os.path.split(src)[0] # Build a list of path components in root-to-leaf order. path = src_dir path_comps = [] while path != '/' and path != '': head, tail = os.path.split(path) path_comps.append(tail) path = head path_comps.reverse() abs_path = root src_path = "/" # Check and create components as needed for comp in path_comps: abs_path = os.path.join(abs_path, comp) # Do not create components that are above the archive root. if not in_archive(abs_path): continue src_path = os.path.join(src_path, comp) if not os.path.exists(abs_path): self.log_debug("Making path %s" % abs_path) if os.path.islink(src_path) and os.path.isdir(src_path): target = os.readlink(src_path) # The directory containing the source in the host fs, # adjusted for the current level of path creation. target_dir = os.path.split(src_path)[0] # The source path of the target in the host fs to be # recursively copied. target_src = os.path.join(target_dir, target) # Recursively create leading components of target dest = self._make_leading_paths(target_src, mode=mode) dest = os.path.normpath(dest) self.log_debug("Making symlink '%s' -> '%s'" % (abs_path, target)) os.symlink(target, abs_path) else: self.log_debug("Making directory %s" % abs_path) os.mkdir(abs_path, mode) dest = src_path return dest
[ "def", "_make_leading_paths", "(", "self", ",", "src", ",", "mode", "=", "0o700", ")", ":", "self", ".", "log_debug", "(", "\"Making leading paths for %s\"", "%", "src", ")", "root", "=", "self", ".", "_archive_root", "dest", "=", "src", "def", "in_archive",...
Create leading path components The standard python `os.makedirs` is insufficient for our needs: it will only create directories, and ignores the fact that some path components may be symbolic links. :param src: The source path in the host file system for which leading components should be created, or the path to an sos_* virtual directory inside the archive. Host paths must be absolute (initial '/'), and sos_* directory paths must be a path relative to the root of the archive. :param mode: An optional mode to be used when creating path components. :returns: A rewritten destination path in the case that one or more symbolic links in intermediate components of the path have altered the path destination.
[ "Create", "leading", "path", "components" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/archive.py#L159-L243
225,710
sosreport/sos
sos/archive.py
FileCacheArchive._check_path
def _check_path(self, src, path_type, dest=None, force=False): """Check a new destination path in the archive. Since it is possible for multiple plugins to collect the same paths, and since plugins can now run concurrently, it is possible for two threads to race in archive methods: historically the archive class only needed to test for the actual presence of a path, since it was impossible for another `Archive` client to enter the class while another method invocation was being dispatched. Deal with this by implementing a locking scheme for operations that modify the path structure of the archive, and by testing explicitly for conflicts with any existing content at the specified destination path. It is not an error to attempt to create a path that already exists in the archive so long as the type of the object to be added matches the type of object already found at the path. It is an error to attempt to re-create an existing path with a different path type (for example, creating a symbolic link at a path already occupied by a regular file). :param src: the source path to be copied to the archive :param path_type: the type of object to be copied :param dest: an optional destination path :param force: force file creation even if the path exists :returns: An absolute destination path if the path should be copied now or `None` otherwise """ dest = dest or self.dest_path(src) if path_type == P_DIR: dest_dir = dest else: dest_dir = os.path.split(dest)[0] if not dest_dir: return dest # Check containing directory presence and path type if os.path.exists(dest_dir) and not os.path.isdir(dest_dir): raise ValueError("path '%s' exists and is not a directory" % dest_dir) elif not os.path.exists(dest_dir): src_dir = src if path_type == P_DIR else os.path.split(src)[0] self._make_leading_paths(src_dir) def is_special(mode): return any([ stat.S_ISBLK(mode), stat.S_ISCHR(mode), stat.S_ISFIFO(mode), stat.S_ISSOCK(mode) ]) if force: return dest # Check destination path presence and type if os.path.exists(dest): # Use lstat: we care about the current object, not the referent. st = os.lstat(dest) ve_msg = "path '%s' exists and is not a %s" if path_type == P_FILE and not stat.S_ISREG(st.st_mode): raise ValueError(ve_msg % (dest, "regular file")) if path_type == P_LINK and not stat.S_ISLNK(st.st_mode): raise ValueError(ve_msg % (dest, "symbolic link")) if path_type == P_NODE and not is_special(st.st_mode): raise ValueError(ve_msg % (dest, "special file")) if path_type == P_DIR and not stat.S_ISDIR(st.st_mode): raise ValueError(ve_msg % (dest, "directory")) # Path has already been copied: skip return None return dest
python
def _check_path(self, src, path_type, dest=None, force=False): """Check a new destination path in the archive. Since it is possible for multiple plugins to collect the same paths, and since plugins can now run concurrently, it is possible for two threads to race in archive methods: historically the archive class only needed to test for the actual presence of a path, since it was impossible for another `Archive` client to enter the class while another method invocation was being dispatched. Deal with this by implementing a locking scheme for operations that modify the path structure of the archive, and by testing explicitly for conflicts with any existing content at the specified destination path. It is not an error to attempt to create a path that already exists in the archive so long as the type of the object to be added matches the type of object already found at the path. It is an error to attempt to re-create an existing path with a different path type (for example, creating a symbolic link at a path already occupied by a regular file). :param src: the source path to be copied to the archive :param path_type: the type of object to be copied :param dest: an optional destination path :param force: force file creation even if the path exists :returns: An absolute destination path if the path should be copied now or `None` otherwise """ dest = dest or self.dest_path(src) if path_type == P_DIR: dest_dir = dest else: dest_dir = os.path.split(dest)[0] if not dest_dir: return dest # Check containing directory presence and path type if os.path.exists(dest_dir) and not os.path.isdir(dest_dir): raise ValueError("path '%s' exists and is not a directory" % dest_dir) elif not os.path.exists(dest_dir): src_dir = src if path_type == P_DIR else os.path.split(src)[0] self._make_leading_paths(src_dir) def is_special(mode): return any([ stat.S_ISBLK(mode), stat.S_ISCHR(mode), stat.S_ISFIFO(mode), stat.S_ISSOCK(mode) ]) if force: return dest # Check destination path presence and type if os.path.exists(dest): # Use lstat: we care about the current object, not the referent. st = os.lstat(dest) ve_msg = "path '%s' exists and is not a %s" if path_type == P_FILE and not stat.S_ISREG(st.st_mode): raise ValueError(ve_msg % (dest, "regular file")) if path_type == P_LINK and not stat.S_ISLNK(st.st_mode): raise ValueError(ve_msg % (dest, "symbolic link")) if path_type == P_NODE and not is_special(st.st_mode): raise ValueError(ve_msg % (dest, "special file")) if path_type == P_DIR and not stat.S_ISDIR(st.st_mode): raise ValueError(ve_msg % (dest, "directory")) # Path has already been copied: skip return None return dest
[ "def", "_check_path", "(", "self", ",", "src", ",", "path_type", ",", "dest", "=", "None", ",", "force", "=", "False", ")", ":", "dest", "=", "dest", "or", "self", ".", "dest_path", "(", "src", ")", "if", "path_type", "==", "P_DIR", ":", "dest_dir", ...
Check a new destination path in the archive. Since it is possible for multiple plugins to collect the same paths, and since plugins can now run concurrently, it is possible for two threads to race in archive methods: historically the archive class only needed to test for the actual presence of a path, since it was impossible for another `Archive` client to enter the class while another method invocation was being dispatched. Deal with this by implementing a locking scheme for operations that modify the path structure of the archive, and by testing explicitly for conflicts with any existing content at the specified destination path. It is not an error to attempt to create a path that already exists in the archive so long as the type of the object to be added matches the type of object already found at the path. It is an error to attempt to re-create an existing path with a different path type (for example, creating a symbolic link at a path already occupied by a regular file). :param src: the source path to be copied to the archive :param path_type: the type of object to be copied :param dest: an optional destination path :param force: force file creation even if the path exists :returns: An absolute destination path if the path should be copied now or `None` otherwise
[ "Check", "a", "new", "destination", "path", "in", "the", "archive", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/archive.py#L245-L318
225,711
sosreport/sos
sos/archive.py
FileCacheArchive.makedirs
def makedirs(self, path, mode=0o700): """Create path, including leading components. Used by sos.sosreport to set up sos_* directories. """ os.makedirs(os.path.join(self._archive_root, path), mode=mode) self.log_debug("created directory at '%s' in FileCacheArchive '%s'" % (path, self._archive_root))
python
def makedirs(self, path, mode=0o700): """Create path, including leading components. Used by sos.sosreport to set up sos_* directories. """ os.makedirs(os.path.join(self._archive_root, path), mode=mode) self.log_debug("created directory at '%s' in FileCacheArchive '%s'" % (path, self._archive_root))
[ "def", "makedirs", "(", "self", ",", "path", ",", "mode", "=", "0o700", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_archive_root", ",", "path", ")", ",", "mode", "=", "mode", ")", "self", ".", "log_de...
Create path, including leading components. Used by sos.sosreport to set up sos_* directories.
[ "Create", "path", "including", "leading", "components", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/archive.py#L510-L517
225,712
sosreport/sos
sos/archive.py
FileCacheArchive._encrypt
def _encrypt(self, archive): """Encrypts the compressed archive using GPG. If encryption fails for any reason, it should be logged by sos but not cause execution to stop. The assumption is that the unencrypted archive would still be of use to the user, and/or that the end user has another means of securing the archive. Returns the name of the encrypted archive, or raises an exception to signal that encryption failed and the unencrypted archive name should be used. """ arc_name = archive.replace("sosreport-", "secured-sosreport-") arc_name += ".gpg" enc_cmd = "gpg --batch -o %s " % arc_name env = None if self.enc_opts["key"]: # need to assume a trusted key here to be able to encrypt the # archive non-interactively enc_cmd += "--trust-model always -e -r %s " % self.enc_opts["key"] enc_cmd += archive if self.enc_opts["password"]: # prevent change of gpg options using a long password, but also # prevent the addition of quote characters to the passphrase passwd = "%s" % self.enc_opts["password"].replace('\'"', '') env = {"sos_gpg": passwd} enc_cmd += "-c --passphrase-fd 0 " enc_cmd = "/bin/bash -c \"echo $sos_gpg | %s\"" % enc_cmd enc_cmd += archive r = sos_get_command_output(enc_cmd, timeout=0, env=env) if r["status"] == 0: return arc_name elif r["status"] == 2: if self.enc_opts["key"]: msg = "Specified key not in keyring" else: msg = "Could not read passphrase" else: # TODO: report the actual error from gpg. Currently, we cannot as # sos_get_command_output() does not capture stderr msg = "gpg exited with code %s" % r["status"] raise Exception(msg)
python
def _encrypt(self, archive): """Encrypts the compressed archive using GPG. If encryption fails for any reason, it should be logged by sos but not cause execution to stop. The assumption is that the unencrypted archive would still be of use to the user, and/or that the end user has another means of securing the archive. Returns the name of the encrypted archive, or raises an exception to signal that encryption failed and the unencrypted archive name should be used. """ arc_name = archive.replace("sosreport-", "secured-sosreport-") arc_name += ".gpg" enc_cmd = "gpg --batch -o %s " % arc_name env = None if self.enc_opts["key"]: # need to assume a trusted key here to be able to encrypt the # archive non-interactively enc_cmd += "--trust-model always -e -r %s " % self.enc_opts["key"] enc_cmd += archive if self.enc_opts["password"]: # prevent change of gpg options using a long password, but also # prevent the addition of quote characters to the passphrase passwd = "%s" % self.enc_opts["password"].replace('\'"', '') env = {"sos_gpg": passwd} enc_cmd += "-c --passphrase-fd 0 " enc_cmd = "/bin/bash -c \"echo $sos_gpg | %s\"" % enc_cmd enc_cmd += archive r = sos_get_command_output(enc_cmd, timeout=0, env=env) if r["status"] == 0: return arc_name elif r["status"] == 2: if self.enc_opts["key"]: msg = "Specified key not in keyring" else: msg = "Could not read passphrase" else: # TODO: report the actual error from gpg. Currently, we cannot as # sos_get_command_output() does not capture stderr msg = "gpg exited with code %s" % r["status"] raise Exception(msg)
[ "def", "_encrypt", "(", "self", ",", "archive", ")", ":", "arc_name", "=", "archive", ".", "replace", "(", "\"sosreport-\"", ",", "\"secured-sosreport-\"", ")", "arc_name", "+=", "\".gpg\"", "enc_cmd", "=", "\"gpg --batch -o %s \"", "%", "arc_name", "env", "=", ...
Encrypts the compressed archive using GPG. If encryption fails for any reason, it should be logged by sos but not cause execution to stop. The assumption is that the unencrypted archive would still be of use to the user, and/or that the end user has another means of securing the archive. Returns the name of the encrypted archive, or raises an exception to signal that encryption failed and the unencrypted archive name should be used.
[ "Encrypts", "the", "compressed", "archive", "using", "GPG", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/archive.py#L552-L593
225,713
sosreport/sos
sos/utilities.py
tail
def tail(filename, number_of_bytes): """Returns the last number_of_bytes of filename""" with open(filename, "rb") as f: if os.stat(filename).st_size > number_of_bytes: f.seek(-number_of_bytes, 2) return f.read()
python
def tail(filename, number_of_bytes): """Returns the last number_of_bytes of filename""" with open(filename, "rb") as f: if os.stat(filename).st_size > number_of_bytes: f.seek(-number_of_bytes, 2) return f.read()
[ "def", "tail", "(", "filename", ",", "number_of_bytes", ")", ":", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "f", ":", "if", "os", ".", "stat", "(", "filename", ")", ".", "st_size", ">", "number_of_bytes", ":", "f", ".", "seek", "(", ...
Returns the last number_of_bytes of filename
[ "Returns", "the", "last", "number_of_bytes", "of", "filename" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L29-L34
225,714
sosreport/sos
sos/utilities.py
fileobj
def fileobj(path_or_file, mode='r'): """Returns a file-like object that can be used as a context manager""" if isinstance(path_or_file, six.string_types): try: return open(path_or_file, mode) except IOError: log = logging.getLogger('sos') log.debug("fileobj: %s could not be opened" % path_or_file) return closing(six.StringIO()) else: return closing(path_or_file)
python
def fileobj(path_or_file, mode='r'): """Returns a file-like object that can be used as a context manager""" if isinstance(path_or_file, six.string_types): try: return open(path_or_file, mode) except IOError: log = logging.getLogger('sos') log.debug("fileobj: %s could not be opened" % path_or_file) return closing(six.StringIO()) else: return closing(path_or_file)
[ "def", "fileobj", "(", "path_or_file", ",", "mode", "=", "'r'", ")", ":", "if", "isinstance", "(", "path_or_file", ",", "six", ".", "string_types", ")", ":", "try", ":", "return", "open", "(", "path_or_file", ",", "mode", ")", "except", "IOError", ":", ...
Returns a file-like object that can be used as a context manager
[ "Returns", "a", "file", "-", "like", "object", "that", "can", "be", "used", "as", "a", "context", "manager" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L37-L47
225,715
sosreport/sos
sos/utilities.py
convert_bytes
def convert_bytes(bytes_, K=1 << 10, M=1 << 20, G=1 << 30, T=1 << 40): """Converts a number of bytes to a shorter, more human friendly format""" fn = float(bytes_) if bytes_ >= T: return '%.1fT' % (fn / T) elif bytes_ >= G: return '%.1fG' % (fn / G) elif bytes_ >= M: return '%.1fM' % (fn / M) elif bytes_ >= K: return '%.1fK' % (fn / K) else: return '%d' % bytes_
python
def convert_bytes(bytes_, K=1 << 10, M=1 << 20, G=1 << 30, T=1 << 40): """Converts a number of bytes to a shorter, more human friendly format""" fn = float(bytes_) if bytes_ >= T: return '%.1fT' % (fn / T) elif bytes_ >= G: return '%.1fG' % (fn / G) elif bytes_ >= M: return '%.1fM' % (fn / M) elif bytes_ >= K: return '%.1fK' % (fn / K) else: return '%d' % bytes_
[ "def", "convert_bytes", "(", "bytes_", ",", "K", "=", "1", "<<", "10", ",", "M", "=", "1", "<<", "20", ",", "G", "=", "1", "<<", "30", ",", "T", "=", "1", "<<", "40", ")", ":", "fn", "=", "float", "(", "bytes_", ")", "if", "bytes_", ">=", ...
Converts a number of bytes to a shorter, more human friendly format
[ "Converts", "a", "number", "of", "bytes", "to", "a", "shorter", "more", "human", "friendly", "format" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L50-L62
225,716
sosreport/sos
sos/utilities.py
grep
def grep(pattern, *files_or_paths): """Returns lines matched in fnames, where fnames can either be pathnames to files to grep through or open file objects to grep through line by line""" matches = [] for fop in files_or_paths: with fileobj(fop) as fo: matches.extend((line for line in fo if re.match(pattern, line))) return matches
python
def grep(pattern, *files_or_paths): """Returns lines matched in fnames, where fnames can either be pathnames to files to grep through or open file objects to grep through line by line""" matches = [] for fop in files_or_paths: with fileobj(fop) as fo: matches.extend((line for line in fo if re.match(pattern, line))) return matches
[ "def", "grep", "(", "pattern", ",", "*", "files_or_paths", ")", ":", "matches", "=", "[", "]", "for", "fop", "in", "files_or_paths", ":", "with", "fileobj", "(", "fop", ")", "as", "fo", ":", "matches", ".", "extend", "(", "(", "line", "for", "line", ...
Returns lines matched in fnames, where fnames can either be pathnames to files to grep through or open file objects to grep through line by line
[ "Returns", "lines", "matched", "in", "fnames", "where", "fnames", "can", "either", "be", "pathnames", "to", "files", "to", "grep", "through", "or", "open", "file", "objects", "to", "grep", "through", "line", "by", "line" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L87-L96
225,717
sosreport/sos
sos/utilities.py
is_executable
def is_executable(command): """Returns if a command matches an executable on the PATH""" paths = os.environ.get("PATH", "").split(os.path.pathsep) candidates = [command] + [os.path.join(p, command) for p in paths] return any(os.access(path, os.X_OK) for path in candidates)
python
def is_executable(command): """Returns if a command matches an executable on the PATH""" paths = os.environ.get("PATH", "").split(os.path.pathsep) candidates = [command] + [os.path.join(p, command) for p in paths] return any(os.access(path, os.X_OK) for path in candidates)
[ "def", "is_executable", "(", "command", ")", ":", "paths", "=", "os", ".", "environ", ".", "get", "(", "\"PATH\"", ",", "\"\"", ")", ".", "split", "(", "os", ".", "path", ".", "pathsep", ")", "candidates", "=", "[", "command", "]", "+", "[", "os", ...
Returns if a command matches an executable on the PATH
[ "Returns", "if", "a", "command", "matches", "an", "executable", "on", "the", "PATH" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L99-L104
225,718
sosreport/sos
sos/utilities.py
sos_get_command_output
def sos_get_command_output(command, timeout=300, stderr=False, chroot=None, chdir=None, env=None, binary=False, sizelimit=None, poller=None): """Execute a command and return a dictionary of status and output, optionally changing root or current working directory before executing command. """ # Change root or cwd for child only. Exceptions in the prexec_fn # closure are caught in the parent (chroot and chdir are bound from # the enclosing scope). def _child_prep_fn(): if (chroot): os.chroot(chroot) if (chdir): os.chdir(chdir) cmd_env = os.environ.copy() # ensure consistent locale for collected command output cmd_env['LC_ALL'] = 'C' # optionally add an environment change for the command if env: for key, value in env.items(): if value: cmd_env[key] = value else: cmd_env.pop(key, None) # use /usr/bin/timeout to implement a timeout if timeout and is_executable("timeout"): command = "timeout %ds %s" % (timeout, command) # shlex.split() reacts badly to unicode on older python runtimes. if not six.PY3: command = command.encode('utf-8', 'ignore') args = shlex.split(command) # Expand arguments that are wildcard paths. expanded_args = [] for arg in args: expanded_arg = glob.glob(arg) if expanded_arg: expanded_args.extend(expanded_arg) else: expanded_args.append(arg) try: p = Popen(expanded_args, shell=False, stdout=PIPE, stderr=STDOUT if stderr else PIPE, bufsize=-1, env=cmd_env, close_fds=True, preexec_fn=_child_prep_fn) reader = AsyncReader(p.stdout, sizelimit, binary) if poller: while reader.running: if poller(): p.terminate() raise SoSTimeoutError stdout = reader.get_contents() while p.poll() is None: pass except OSError as e: if e.errno == errno.ENOENT: return {'status': 127, 'output': ""} else: raise e if p.returncode == 126 or p.returncode == 127: stdout = six.binary_type(b"") return { 'status': p.returncode, 'output': stdout }
python
def sos_get_command_output(command, timeout=300, stderr=False, chroot=None, chdir=None, env=None, binary=False, sizelimit=None, poller=None): """Execute a command and return a dictionary of status and output, optionally changing root or current working directory before executing command. """ # Change root or cwd for child only. Exceptions in the prexec_fn # closure are caught in the parent (chroot and chdir are bound from # the enclosing scope). def _child_prep_fn(): if (chroot): os.chroot(chroot) if (chdir): os.chdir(chdir) cmd_env = os.environ.copy() # ensure consistent locale for collected command output cmd_env['LC_ALL'] = 'C' # optionally add an environment change for the command if env: for key, value in env.items(): if value: cmd_env[key] = value else: cmd_env.pop(key, None) # use /usr/bin/timeout to implement a timeout if timeout and is_executable("timeout"): command = "timeout %ds %s" % (timeout, command) # shlex.split() reacts badly to unicode on older python runtimes. if not six.PY3: command = command.encode('utf-8', 'ignore') args = shlex.split(command) # Expand arguments that are wildcard paths. expanded_args = [] for arg in args: expanded_arg = glob.glob(arg) if expanded_arg: expanded_args.extend(expanded_arg) else: expanded_args.append(arg) try: p = Popen(expanded_args, shell=False, stdout=PIPE, stderr=STDOUT if stderr else PIPE, bufsize=-1, env=cmd_env, close_fds=True, preexec_fn=_child_prep_fn) reader = AsyncReader(p.stdout, sizelimit, binary) if poller: while reader.running: if poller(): p.terminate() raise SoSTimeoutError stdout = reader.get_contents() while p.poll() is None: pass except OSError as e: if e.errno == errno.ENOENT: return {'status': 127, 'output': ""} else: raise e if p.returncode == 126 or p.returncode == 127: stdout = six.binary_type(b"") return { 'status': p.returncode, 'output': stdout }
[ "def", "sos_get_command_output", "(", "command", ",", "timeout", "=", "300", ",", "stderr", "=", "False", ",", "chroot", "=", "None", ",", "chdir", "=", "None", ",", "env", "=", "None", ",", "binary", "=", "False", ",", "sizelimit", "=", "None", ",", ...
Execute a command and return a dictionary of status and output, optionally changing root or current working directory before executing command.
[ "Execute", "a", "command", "and", "return", "a", "dictionary", "of", "status", "and", "output", "optionally", "changing", "root", "or", "current", "working", "directory", "before", "executing", "command", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L107-L177
225,719
sosreport/sos
sos/utilities.py
import_module
def import_module(module_fqname, superclasses=None): """Imports the module module_fqname and returns a list of defined classes from that module. If superclasses is defined then the classes returned will be subclasses of the specified superclass or superclasses. If superclasses is plural it must be a tuple of classes.""" module_name = module_fqname.rpartition(".")[-1] module = __import__(module_fqname, globals(), locals(), [module_name]) modules = [class_ for cname, class_ in inspect.getmembers(module, inspect.isclass) if class_.__module__ == module_fqname] if superclasses: modules = [m for m in modules if issubclass(m, superclasses)] return modules
python
def import_module(module_fqname, superclasses=None): """Imports the module module_fqname and returns a list of defined classes from that module. If superclasses is defined then the classes returned will be subclasses of the specified superclass or superclasses. If superclasses is plural it must be a tuple of classes.""" module_name = module_fqname.rpartition(".")[-1] module = __import__(module_fqname, globals(), locals(), [module_name]) modules = [class_ for cname, class_ in inspect.getmembers(module, inspect.isclass) if class_.__module__ == module_fqname] if superclasses: modules = [m for m in modules if issubclass(m, superclasses)] return modules
[ "def", "import_module", "(", "module_fqname", ",", "superclasses", "=", "None", ")", ":", "module_name", "=", "module_fqname", ".", "rpartition", "(", "\".\"", ")", "[", "-", "1", "]", "module", "=", "__import__", "(", "module_fqname", ",", "globals", "(", ...
Imports the module module_fqname and returns a list of defined classes from that module. If superclasses is defined then the classes returned will be subclasses of the specified superclass or superclasses. If superclasses is plural it must be a tuple of classes.
[ "Imports", "the", "module", "module_fqname", "and", "returns", "a", "list", "of", "defined", "classes", "from", "that", "module", ".", "If", "superclasses", "is", "defined", "then", "the", "classes", "returned", "will", "be", "subclasses", "of", "the", "specif...
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L180-L193
225,720
sosreport/sos
sos/utilities.py
shell_out
def shell_out(cmd, timeout=30, chroot=None, runat=None): """Shell out to an external command and return the output or the empty string in case of error. """ return sos_get_command_output(cmd, timeout=timeout, chroot=chroot, chdir=runat)['output']
python
def shell_out(cmd, timeout=30, chroot=None, runat=None): """Shell out to an external command and return the output or the empty string in case of error. """ return sos_get_command_output(cmd, timeout=timeout, chroot=chroot, chdir=runat)['output']
[ "def", "shell_out", "(", "cmd", ",", "timeout", "=", "30", ",", "chroot", "=", "None", ",", "runat", "=", "None", ")", ":", "return", "sos_get_command_output", "(", "cmd", ",", "timeout", "=", "timeout", ",", "chroot", "=", "chroot", ",", "chdir", "=",...
Shell out to an external command and return the output or the empty string in case of error.
[ "Shell", "out", "to", "an", "external", "command", "and", "return", "the", "output", "or", "the", "empty", "string", "in", "case", "of", "error", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L196-L201
225,721
sosreport/sos
sos/utilities.py
AsyncReader.get_contents
def get_contents(self): '''Returns the contents of the deque as a string''' # block until command completes or timesout (separate from the plugin # hitting a timeout) while self.running: pass if not self.binary: return ''.join(ln.decode('utf-8', 'ignore') for ln in self.deque) else: return b''.join(ln for ln in self.deque)
python
def get_contents(self): '''Returns the contents of the deque as a string''' # block until command completes or timesout (separate from the plugin # hitting a timeout) while self.running: pass if not self.binary: return ''.join(ln.decode('utf-8', 'ignore') for ln in self.deque) else: return b''.join(ln for ln in self.deque)
[ "def", "get_contents", "(", "self", ")", ":", "# block until command completes or timesout (separate from the plugin", "# hitting a timeout)", "while", "self", ".", "running", ":", "pass", "if", "not", "self", ".", "binary", ":", "return", "''", ".", "join", "(", "l...
Returns the contents of the deque as a string
[ "Returns", "the", "contents", "of", "the", "deque", "as", "a", "string" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L246-L255
225,722
sosreport/sos
sos/utilities.py
ImporterHelper._plugin_name
def _plugin_name(self, path): "Returns the plugin module name given the path" base = os.path.basename(path) name, ext = os.path.splitext(base) return name
python
def _plugin_name(self, path): "Returns the plugin module name given the path" base = os.path.basename(path) name, ext = os.path.splitext(base) return name
[ "def", "_plugin_name", "(", "self", ",", "path", ")", ":", "base", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "name", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "base", ")", "return", "name" ]
Returns the plugin module name given the path
[ "Returns", "the", "plugin", "module", "name", "given", "the", "path" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L270-L274
225,723
sosreport/sos
sos/utilities.py
ImporterHelper.get_modules
def get_modules(self): """Returns the list of importable modules in the configured python package. """ plugins = [] for path in self.package.__path__: if os.path.isdir(path): plugins.extend(self._find_plugins_in_dir(path)) return plugins
python
def get_modules(self): """Returns the list of importable modules in the configured python package. """ plugins = [] for path in self.package.__path__: if os.path.isdir(path): plugins.extend(self._find_plugins_in_dir(path)) return plugins
[ "def", "get_modules", "(", "self", ")", ":", "plugins", "=", "[", "]", "for", "path", "in", "self", ".", "package", ".", "__path__", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "plugins", ".", "extend", "(", "self", ".", "_...
Returns the list of importable modules in the configured python package.
[ "Returns", "the", "list", "of", "importable", "modules", "in", "the", "configured", "python", "package", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L292-L300
225,724
sosreport/sos
sos/policies/redhat.py
RedHatPolicy.check_usrmove
def check_usrmove(self, pkgs): """Test whether the running system implements UsrMove. If the 'filesystem' package is present, it will check that the version is greater than 3. If the package is not present the '/bin' and '/sbin' paths are checked and UsrMove is assumed if both are symbolic links. :param pkgs: a packages dictionary """ if 'filesystem' not in pkgs: return os.path.islink('/bin') and os.path.islink('/sbin') else: filesys_version = pkgs['filesystem']['version'] return True if filesys_version[0] == '3' else False
python
def check_usrmove(self, pkgs): """Test whether the running system implements UsrMove. If the 'filesystem' package is present, it will check that the version is greater than 3. If the package is not present the '/bin' and '/sbin' paths are checked and UsrMove is assumed if both are symbolic links. :param pkgs: a packages dictionary """ if 'filesystem' not in pkgs: return os.path.islink('/bin') and os.path.islink('/sbin') else: filesys_version = pkgs['filesystem']['version'] return True if filesys_version[0] == '3' else False
[ "def", "check_usrmove", "(", "self", ",", "pkgs", ")", ":", "if", "'filesystem'", "not", "in", "pkgs", ":", "return", "os", ".", "path", ".", "islink", "(", "'/bin'", ")", "and", "os", ".", "path", ".", "islink", "(", "'/sbin'", ")", "else", ":", "...
Test whether the running system implements UsrMove. If the 'filesystem' package is present, it will check that the version is greater than 3. If the package is not present the '/bin' and '/sbin' paths are checked and UsrMove is assumed if both are symbolic links. :param pkgs: a packages dictionary
[ "Test", "whether", "the", "running", "system", "implements", "UsrMove", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/redhat.py#L100-L114
225,725
sosreport/sos
sos/policies/redhat.py
RedHatPolicy.mangle_package_path
def mangle_package_path(self, files): """Mangle paths for post-UsrMove systems. If the system implements UsrMove, all files will be in '/usr/[s]bin'. This method substitutes all the /[s]bin references in the 'files' list with '/usr/[s]bin'. :param files: the list of package managed files """ paths = [] def transform_path(path): # Some packages actually own paths in /bin: in this case, # duplicate the path as both the / and /usr version. skip_paths = ["/bin/rpm", "/bin/mailx"] if path in skip_paths: return (path, os.path.join("/usr", path[1:])) return (re.sub(r'(^)(/s?bin)', r'\1/usr\2', path),) if self.usrmove: for f in files: paths.extend(transform_path(f)) return paths else: return files
python
def mangle_package_path(self, files): """Mangle paths for post-UsrMove systems. If the system implements UsrMove, all files will be in '/usr/[s]bin'. This method substitutes all the /[s]bin references in the 'files' list with '/usr/[s]bin'. :param files: the list of package managed files """ paths = [] def transform_path(path): # Some packages actually own paths in /bin: in this case, # duplicate the path as both the / and /usr version. skip_paths = ["/bin/rpm", "/bin/mailx"] if path in skip_paths: return (path, os.path.join("/usr", path[1:])) return (re.sub(r'(^)(/s?bin)', r'\1/usr\2', path),) if self.usrmove: for f in files: paths.extend(transform_path(f)) return paths else: return files
[ "def", "mangle_package_path", "(", "self", ",", "files", ")", ":", "paths", "=", "[", "]", "def", "transform_path", "(", "path", ")", ":", "# Some packages actually own paths in /bin: in this case,", "# duplicate the path as both the / and /usr version.", "skip_paths", "=",...
Mangle paths for post-UsrMove systems. If the system implements UsrMove, all files will be in '/usr/[s]bin'. This method substitutes all the /[s]bin references in the 'files' list with '/usr/[s]bin'. :param files: the list of package managed files
[ "Mangle", "paths", "for", "post", "-", "UsrMove", "systems", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/redhat.py#L116-L140
225,726
sosreport/sos
sos/policies/redhat.py
RedHatPolicy._container_init
def _container_init(self): """Check if sos is running in a container and perform container specific initialisation based on ENV_HOST_SYSROOT. """ if ENV_CONTAINER in os.environ: if os.environ[ENV_CONTAINER] in ['docker', 'oci']: self._in_container = True if ENV_HOST_SYSROOT in os.environ: self._host_sysroot = os.environ[ENV_HOST_SYSROOT] use_sysroot = self._in_container and self._host_sysroot != '/' if use_sysroot: host_tmp_dir = os.path.abspath(self._host_sysroot + self._tmp_dir) self._tmp_dir = host_tmp_dir return self._host_sysroot if use_sysroot else None
python
def _container_init(self): """Check if sos is running in a container and perform container specific initialisation based on ENV_HOST_SYSROOT. """ if ENV_CONTAINER in os.environ: if os.environ[ENV_CONTAINER] in ['docker', 'oci']: self._in_container = True if ENV_HOST_SYSROOT in os.environ: self._host_sysroot = os.environ[ENV_HOST_SYSROOT] use_sysroot = self._in_container and self._host_sysroot != '/' if use_sysroot: host_tmp_dir = os.path.abspath(self._host_sysroot + self._tmp_dir) self._tmp_dir = host_tmp_dir return self._host_sysroot if use_sysroot else None
[ "def", "_container_init", "(", "self", ")", ":", "if", "ENV_CONTAINER", "in", "os", ".", "environ", ":", "if", "os", ".", "environ", "[", "ENV_CONTAINER", "]", "in", "[", "'docker'", ",", "'oci'", "]", ":", "self", ".", "_in_container", "=", "True", "i...
Check if sos is running in a container and perform container specific initialisation based on ENV_HOST_SYSROOT.
[ "Check", "if", "sos", "is", "running", "in", "a", "container", "and", "perform", "container", "specific", "initialisation", "based", "on", "ENV_HOST_SYSROOT", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/redhat.py#L142-L155
225,727
sosreport/sos
sos/policies/redhat.py
RHELPolicy.check
def check(cls): """Test to see if the running host is a RHEL installation. Checks for the presence of the "Red Hat Enterprise Linux" release string at the beginning of the NAME field in the `/etc/os-release` file and returns ``True`` if it is found, and ``False`` otherwise. :returns: ``True`` if the host is running RHEL or ``False`` otherwise. """ if not os.path.exists(OS_RELEASE): return False with open(OS_RELEASE, "r") as f: for line in f: if line.startswith("NAME"): (name, value) = line.split("=") value = value.strip("\"'") if value.startswith(cls.distro): return True return False
python
def check(cls): """Test to see if the running host is a RHEL installation. Checks for the presence of the "Red Hat Enterprise Linux" release string at the beginning of the NAME field in the `/etc/os-release` file and returns ``True`` if it is found, and ``False`` otherwise. :returns: ``True`` if the host is running RHEL or ``False`` otherwise. """ if not os.path.exists(OS_RELEASE): return False with open(OS_RELEASE, "r") as f: for line in f: if line.startswith("NAME"): (name, value) = line.split("=") value = value.strip("\"'") if value.startswith(cls.distro): return True return False
[ "def", "check", "(", "cls", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "OS_RELEASE", ")", ":", "return", "False", "with", "open", "(", "OS_RELEASE", ",", "\"r\"", ")", "as", "f", ":", "for", "line", "in", "f", ":", "if", "line"...
Test to see if the running host is a RHEL installation. Checks for the presence of the "Red Hat Enterprise Linux" release string at the beginning of the NAME field in the `/etc/os-release` file and returns ``True`` if it is found, and ``False`` otherwise. :returns: ``True`` if the host is running RHEL or ``False`` otherwise.
[ "Test", "to", "see", "if", "the", "running", "host", "is", "a", "RHEL", "installation", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/redhat.py#L274-L295
225,728
sosreport/sos
sos/plugins/lustre.py
Lustre.get_params
def get_params(self, name, param_list): '''Use lctl get_param to collect a selection of parameters into a file. ''' self.add_cmd_output("lctl get_param %s" % " ".join(param_list), suggest_filename="params-%s" % name, stderr=False)
python
def get_params(self, name, param_list): '''Use lctl get_param to collect a selection of parameters into a file. ''' self.add_cmd_output("lctl get_param %s" % " ".join(param_list), suggest_filename="params-%s" % name, stderr=False)
[ "def", "get_params", "(", "self", ",", "name", ",", "param_list", ")", ":", "self", ".", "add_cmd_output", "(", "\"lctl get_param %s\"", "%", "\" \"", ".", "join", "(", "param_list", ")", ",", "suggest_filename", "=", "\"params-%s\"", "%", "name", ",", "stde...
Use lctl get_param to collect a selection of parameters into a file.
[ "Use", "lctl", "get_param", "to", "collect", "a", "selection", "of", "parameters", "into", "a", "file", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/lustre.py#L19-L26
225,729
sosreport/sos
sos/plugins/qpid_dispatch.py
QpidDispatch.setup
def setup(self): """ performs data collection for qpid dispatch router """ options = "" if self.get_option("port"): options = (options + " -b " + gethostname() + ":%s" % (self.get_option("port"))) # gethostname() is due to DISPATCH-156 # for either present option, add --option=value to 'options' variable for option in ["ssl-certificate", "ssl-key", "ssl-trustfile"]: if self.get_option(option): options = (options + " --%s=" % (option) + self.get_option(option)) self.add_cmd_output([ "qdstat -a" + options, # Show Router Addresses "qdstat -n" + options, # Show Router Nodes "qdstat -c" + options, # Show Connections "qdstat -m" + options # Show Broker Memory Stats ]) self.add_copy_spec([ "/etc/qpid-dispatch/qdrouterd.conf" ])
python
def setup(self): """ performs data collection for qpid dispatch router """ options = "" if self.get_option("port"): options = (options + " -b " + gethostname() + ":%s" % (self.get_option("port"))) # gethostname() is due to DISPATCH-156 # for either present option, add --option=value to 'options' variable for option in ["ssl-certificate", "ssl-key", "ssl-trustfile"]: if self.get_option(option): options = (options + " --%s=" % (option) + self.get_option(option)) self.add_cmd_output([ "qdstat -a" + options, # Show Router Addresses "qdstat -n" + options, # Show Router Nodes "qdstat -c" + options, # Show Connections "qdstat -m" + options # Show Broker Memory Stats ]) self.add_copy_spec([ "/etc/qpid-dispatch/qdrouterd.conf" ])
[ "def", "setup", "(", "self", ")", ":", "options", "=", "\"\"", "if", "self", ".", "get_option", "(", "\"port\"", ")", ":", "options", "=", "(", "options", "+", "\" -b \"", "+", "gethostname", "(", ")", "+", "\":%s\"", "%", "(", "self", ".", "get_opti...
performs data collection for qpid dispatch router
[ "performs", "data", "collection", "for", "qpid", "dispatch", "router" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/qpid_dispatch.py#L30-L53
225,730
sosreport/sos
sos/plugins/__init__.py
SoSPredicate.__str
def __str(self, quote=False, prefix="", suffix=""): """Return a string representation of this SoSPredicate with optional prefix, suffix and value quoting. """ quotes = '"%s"' pstr = "dry_run=%s, " % self._dry_run kmods = self._kmods kmods = [quotes % k for k in kmods] if quote else kmods pstr += "kmods=[%s], " % (",".join(kmods)) services = self._services services = [quotes % s for s in services] if quote else services pstr += "services=[%s]" % (",".join(services)) return prefix + pstr + suffix
python
def __str(self, quote=False, prefix="", suffix=""): """Return a string representation of this SoSPredicate with optional prefix, suffix and value quoting. """ quotes = '"%s"' pstr = "dry_run=%s, " % self._dry_run kmods = self._kmods kmods = [quotes % k for k in kmods] if quote else kmods pstr += "kmods=[%s], " % (",".join(kmods)) services = self._services services = [quotes % s for s in services] if quote else services pstr += "services=[%s]" % (",".join(services)) return prefix + pstr + suffix
[ "def", "__str", "(", "self", ",", "quote", "=", "False", ",", "prefix", "=", "\"\"", ",", "suffix", "=", "\"\"", ")", ":", "quotes", "=", "'\"%s\"'", "pstr", "=", "\"dry_run=%s, \"", "%", "self", ".", "_dry_run", "kmods", "=", "self", ".", "_kmods", ...
Return a string representation of this SoSPredicate with optional prefix, suffix and value quoting.
[ "Return", "a", "string", "representation", "of", "this", "SoSPredicate", "with", "optional", "prefix", "suffix", "and", "value", "quoting", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L117-L132
225,731
sosreport/sos
sos/plugins/__init__.py
Plugin.do_file_sub
def do_file_sub(self, srcpath, regexp, subst): '''Apply a regexp substitution to a file archived by sosreport. srcpath is the path in the archive where the file can be found. regexp can be a regexp string or a compiled re object. subst is a string to replace each occurance of regexp in the content of srcpath. This function returns the number of replacements made. ''' try: path = self._get_dest_for_srcpath(srcpath) self._log_debug("substituting scrpath '%s'" % srcpath) self._log_debug("substituting '%s' for '%s' in '%s'" % (subst, regexp, path)) if not path: return 0 readable = self.archive.open_file(path) content = readable.read() if not isinstance(content, six.string_types): content = content.decode('utf8', 'ignore') result, replacements = re.subn(regexp, subst, content) if replacements: self.archive.add_string(result, srcpath) else: replacements = 0 except (OSError, IOError) as e: # if trying to regexp a nonexisting file, dont log it as an # error to stdout if e.errno == errno.ENOENT: msg = "file '%s' not collected, substitution skipped" self._log_debug(msg % path) else: msg = "regex substitution failed for '%s' with: '%s'" self._log_error(msg % (path, e)) replacements = 0 return replacements
python
def do_file_sub(self, srcpath, regexp, subst): '''Apply a regexp substitution to a file archived by sosreport. srcpath is the path in the archive where the file can be found. regexp can be a regexp string or a compiled re object. subst is a string to replace each occurance of regexp in the content of srcpath. This function returns the number of replacements made. ''' try: path = self._get_dest_for_srcpath(srcpath) self._log_debug("substituting scrpath '%s'" % srcpath) self._log_debug("substituting '%s' for '%s' in '%s'" % (subst, regexp, path)) if not path: return 0 readable = self.archive.open_file(path) content = readable.read() if not isinstance(content, six.string_types): content = content.decode('utf8', 'ignore') result, replacements = re.subn(regexp, subst, content) if replacements: self.archive.add_string(result, srcpath) else: replacements = 0 except (OSError, IOError) as e: # if trying to regexp a nonexisting file, dont log it as an # error to stdout if e.errno == errno.ENOENT: msg = "file '%s' not collected, substitution skipped" self._log_debug(msg % path) else: msg = "regex substitution failed for '%s' with: '%s'" self._log_error(msg % (path, e)) replacements = 0 return replacements
[ "def", "do_file_sub", "(", "self", ",", "srcpath", ",", "regexp", ",", "subst", ")", ":", "try", ":", "path", "=", "self", ".", "_get_dest_for_srcpath", "(", "srcpath", ")", "self", ".", "_log_debug", "(", "\"substituting scrpath '%s'\"", "%", "srcpath", ")"...
Apply a regexp substitution to a file archived by sosreport. srcpath is the path in the archive where the file can be found. regexp can be a regexp string or a compiled re object. subst is a string to replace each occurance of regexp in the content of srcpath. This function returns the number of replacements made.
[ "Apply", "a", "regexp", "substitution", "to", "a", "file", "archived", "by", "sosreport", ".", "srcpath", "is", "the", "path", "in", "the", "archive", "where", "the", "file", "can", "be", "found", ".", "regexp", "can", "be", "a", "regexp", "string", "or"...
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L482-L516
225,732
sosreport/sos
sos/plugins/__init__.py
Plugin.do_path_regex_sub
def do_path_regex_sub(self, pathexp, regexp, subst): '''Apply a regexp substituation to a set of files archived by sos. The set of files to be substituted is generated by matching collected file pathnames against pathexp which may be a regular expression string or compiled re object. The portion of the file to be replaced is specified via regexp and the replacement string is passed in subst.''' if not hasattr(pathexp, "match"): pathexp = re.compile(pathexp) match = pathexp.match file_list = [f for f in self.copied_files if match(f['srcpath'])] for file in file_list: self.do_file_sub(file['srcpath'], regexp, subst)
python
def do_path_regex_sub(self, pathexp, regexp, subst): '''Apply a regexp substituation to a set of files archived by sos. The set of files to be substituted is generated by matching collected file pathnames against pathexp which may be a regular expression string or compiled re object. The portion of the file to be replaced is specified via regexp and the replacement string is passed in subst.''' if not hasattr(pathexp, "match"): pathexp = re.compile(pathexp) match = pathexp.match file_list = [f for f in self.copied_files if match(f['srcpath'])] for file in file_list: self.do_file_sub(file['srcpath'], regexp, subst)
[ "def", "do_path_regex_sub", "(", "self", ",", "pathexp", ",", "regexp", ",", "subst", ")", ":", "if", "not", "hasattr", "(", "pathexp", ",", "\"match\"", ")", ":", "pathexp", "=", "re", ".", "compile", "(", "pathexp", ")", "match", "=", "pathexp", ".",...
Apply a regexp substituation to a set of files archived by sos. The set of files to be substituted is generated by matching collected file pathnames against pathexp which may be a regular expression string or compiled re object. The portion of the file to be replaced is specified via regexp and the replacement string is passed in subst.
[ "Apply", "a", "regexp", "substituation", "to", "a", "set", "of", "files", "archived", "by", "sos", ".", "The", "set", "of", "files", "to", "be", "substituted", "is", "generated", "by", "matching", "collected", "file", "pathnames", "against", "pathexp", "whic...
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L518-L530
225,733
sosreport/sos
sos/plugins/__init__.py
Plugin._do_copy_path
def _do_copy_path(self, srcpath, dest=None): '''Copy file or directory to the destination tree. If a directory, then everything below it is recursively copied. A list of copied files are saved for use later in preparing a report. ''' if self._is_forbidden_path(srcpath): self._log_debug("skipping forbidden path '%s'" % srcpath) return '' if not dest: dest = srcpath if self.use_sysroot(): dest = self.strip_sysroot(dest) try: st = os.lstat(srcpath) except (OSError, IOError): self._log_info("failed to stat '%s'" % srcpath) return if stat.S_ISLNK(st.st_mode): self._copy_symlink(srcpath) return else: if stat.S_ISDIR(st.st_mode) and os.access(srcpath, os.R_OK): self._copy_dir(srcpath) return # handle special nodes (block, char, fifo, socket) if not (stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode)): ntype = _node_type(st) self._log_debug("creating %s node at archive:'%s'" % (ntype, dest)) self._copy_node(srcpath, st) return # if we get here, it's definitely a regular file (not a symlink or dir) self._log_debug("copying path '%s' to archive:'%s'" % (srcpath, dest)) # if not readable(srcpath) if not st.st_mode & 0o444: # FIXME: reflect permissions in archive self.archive.add_string("", dest) else: self.archive.add_file(srcpath, dest) self.copied_files.append({ 'srcpath': srcpath, 'dstpath': dest, 'symlink': "no" })
python
def _do_copy_path(self, srcpath, dest=None): '''Copy file or directory to the destination tree. If a directory, then everything below it is recursively copied. A list of copied files are saved for use later in preparing a report. ''' if self._is_forbidden_path(srcpath): self._log_debug("skipping forbidden path '%s'" % srcpath) return '' if not dest: dest = srcpath if self.use_sysroot(): dest = self.strip_sysroot(dest) try: st = os.lstat(srcpath) except (OSError, IOError): self._log_info("failed to stat '%s'" % srcpath) return if stat.S_ISLNK(st.st_mode): self._copy_symlink(srcpath) return else: if stat.S_ISDIR(st.st_mode) and os.access(srcpath, os.R_OK): self._copy_dir(srcpath) return # handle special nodes (block, char, fifo, socket) if not (stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode)): ntype = _node_type(st) self._log_debug("creating %s node at archive:'%s'" % (ntype, dest)) self._copy_node(srcpath, st) return # if we get here, it's definitely a regular file (not a symlink or dir) self._log_debug("copying path '%s' to archive:'%s'" % (srcpath, dest)) # if not readable(srcpath) if not st.st_mode & 0o444: # FIXME: reflect permissions in archive self.archive.add_string("", dest) else: self.archive.add_file(srcpath, dest) self.copied_files.append({ 'srcpath': srcpath, 'dstpath': dest, 'symlink': "no" })
[ "def", "_do_copy_path", "(", "self", ",", "srcpath", ",", "dest", "=", "None", ")", ":", "if", "self", ".", "_is_forbidden_path", "(", "srcpath", ")", ":", "self", ".", "_log_debug", "(", "\"skipping forbidden path '%s'\"", "%", "srcpath", ")", "return", "''...
Copy file or directory to the destination tree. If a directory, then everything below it is recursively copied. A list of copied files are saved for use later in preparing a report.
[ "Copy", "file", "or", "directory", "to", "the", "destination", "tree", ".", "If", "a", "directory", "then", "everything", "below", "it", "is", "recursively", "copied", ".", "A", "list", "of", "copied", "files", "are", "saved", "for", "use", "later", "in", ...
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L627-L678
225,734
sosreport/sos
sos/plugins/__init__.py
Plugin.set_option
def set_option(self, optionname, value): """Set the named option to value. Ensure the original type of the option value is preserved. """ for name, parms in zip(self.opt_names, self.opt_parms): if name == optionname: # FIXME: ensure that the resulting type of the set option # matches that of the default value. This prevents a string # option from being coerced to int simply because it holds # a numeric value (e.g. a password). # See PR #1526 and Issue #1597 defaulttype = type(parms['enabled']) if defaulttype != type(value) and defaulttype != type(None): value = (defaulttype)(value) parms['enabled'] = value return True else: return False
python
def set_option(self, optionname, value): """Set the named option to value. Ensure the original type of the option value is preserved. """ for name, parms in zip(self.opt_names, self.opt_parms): if name == optionname: # FIXME: ensure that the resulting type of the set option # matches that of the default value. This prevents a string # option from being coerced to int simply because it holds # a numeric value (e.g. a password). # See PR #1526 and Issue #1597 defaulttype = type(parms['enabled']) if defaulttype != type(value) and defaulttype != type(None): value = (defaulttype)(value) parms['enabled'] = value return True else: return False
[ "def", "set_option", "(", "self", ",", "optionname", ",", "value", ")", ":", "for", "name", ",", "parms", "in", "zip", "(", "self", ".", "opt_names", ",", "self", ".", "opt_parms", ")", ":", "if", "name", "==", "optionname", ":", "# FIXME: ensure that th...
Set the named option to value. Ensure the original type of the option value is preserved.
[ "Set", "the", "named", "option", "to", "value", ".", "Ensure", "the", "original", "type", "of", "the", "option", "value", "is", "preserved", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L699-L716
225,735
sosreport/sos
sos/plugins/__init__.py
Plugin.get_option
def get_option(self, optionname, default=0): """Returns the first value that matches 'optionname' in parameters passed in via the command line or set via set_option or via the global_plugin_options dictionary, in that order. optionaname may be iterable, in which case the first option that matches any of the option names is returned. """ global_options = ('verify', 'all_logs', 'log_size', 'plugin_timeout') if optionname in global_options: return getattr(self.commons['cmdlineopts'], optionname) for name, parms in zip(self.opt_names, self.opt_parms): if name == optionname: val = parms['enabled'] if val is not None: return val return default
python
def get_option(self, optionname, default=0): """Returns the first value that matches 'optionname' in parameters passed in via the command line or set via set_option or via the global_plugin_options dictionary, in that order. optionaname may be iterable, in which case the first option that matches any of the option names is returned. """ global_options = ('verify', 'all_logs', 'log_size', 'plugin_timeout') if optionname in global_options: return getattr(self.commons['cmdlineopts'], optionname) for name, parms in zip(self.opt_names, self.opt_parms): if name == optionname: val = parms['enabled'] if val is not None: return val return default
[ "def", "get_option", "(", "self", ",", "optionname", ",", "default", "=", "0", ")", ":", "global_options", "=", "(", "'verify'", ",", "'all_logs'", ",", "'log_size'", ",", "'plugin_timeout'", ")", "if", "optionname", "in", "global_options", ":", "return", "g...
Returns the first value that matches 'optionname' in parameters passed in via the command line or set via set_option or via the global_plugin_options dictionary, in that order. optionaname may be iterable, in which case the first option that matches any of the option names is returned.
[ "Returns", "the", "first", "value", "that", "matches", "optionname", "in", "parameters", "passed", "in", "via", "the", "command", "line", "or", "set", "via", "set_option", "or", "via", "the", "global_plugin_options", "dictionary", "in", "that", "order", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L718-L738
225,736
sosreport/sos
sos/plugins/__init__.py
Plugin.get_option_as_list
def get_option_as_list(self, optionname, delimiter=",", default=None): '''Will try to return the option as a list separated by the delimiter. ''' option = self.get_option(optionname) try: opt_list = [opt.strip() for opt in option.split(delimiter)] return list(filter(None, opt_list)) except Exception: return default
python
def get_option_as_list(self, optionname, delimiter=",", default=None): '''Will try to return the option as a list separated by the delimiter. ''' option = self.get_option(optionname) try: opt_list = [opt.strip() for opt in option.split(delimiter)] return list(filter(None, opt_list)) except Exception: return default
[ "def", "get_option_as_list", "(", "self", ",", "optionname", ",", "delimiter", "=", "\",\"", ",", "default", "=", "None", ")", ":", "option", "=", "self", ".", "get_option", "(", "optionname", ")", "try", ":", "opt_list", "=", "[", "opt", ".", "strip", ...
Will try to return the option as a list separated by the delimiter.
[ "Will", "try", "to", "return", "the", "option", "as", "a", "list", "separated", "by", "the", "delimiter", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L740-L749
225,737
sosreport/sos
sos/plugins/__init__.py
Plugin.add_copy_spec
def add_copy_spec(self, copyspecs, sizelimit=None, tailit=True, pred=None): """Add a file or glob but limit it to sizelimit megabytes. If fname is a single file the file will be tailed to meet sizelimit. If the first file in a glob is too large it will be tailed to meet the sizelimit. """ if not self.test_predicate(pred=pred): self._log_info("skipped copy spec '%s' due to predicate (%s)" % (copyspecs, self.get_predicate(pred=pred))) return if sizelimit is None: sizelimit = self.get_option("log_size") if self.get_option('all_logs'): sizelimit = None if sizelimit: sizelimit *= 1024 * 1024 # in MB if not copyspecs: return False if isinstance(copyspecs, six.string_types): copyspecs = [copyspecs] for copyspec in copyspecs: if not (copyspec and len(copyspec)): return False if self.use_sysroot(): copyspec = self.join_sysroot(copyspec) files = self._expand_copy_spec(copyspec) if len(files) == 0: continue # Files hould be sorted in most-recently-modified order, so that # we collect the newest data first before reaching the limit. def getmtime(path): try: return os.path.getmtime(path) except OSError: return 0 files.sort(key=getmtime, reverse=True) current_size = 0 limit_reached = False _file = None for _file in files: if self._is_forbidden_path(_file): self._log_debug("skipping forbidden path '%s'" % _file) continue try: current_size += os.stat(_file)[stat.ST_SIZE] except OSError: self._log_info("failed to stat '%s'" % _file) if sizelimit and current_size > sizelimit: limit_reached = True break self._add_copy_paths([_file]) if limit_reached and tailit and not _file_is_compressed(_file): file_name = _file if file_name[0] == os.sep: file_name = file_name.lstrip(os.sep) strfile = file_name.replace(os.path.sep, ".") + ".tailed" self.add_string_as_file(tail(_file, sizelimit), strfile) rel_path = os.path.relpath('/', os.path.dirname(_file)) link_path = os.path.join(rel_path, 'sos_strings', self.name(), strfile) self.archive.add_link(link_path, _file)
python
def add_copy_spec(self, copyspecs, sizelimit=None, tailit=True, pred=None): """Add a file or glob but limit it to sizelimit megabytes. If fname is a single file the file will be tailed to meet sizelimit. If the first file in a glob is too large it will be tailed to meet the sizelimit. """ if not self.test_predicate(pred=pred): self._log_info("skipped copy spec '%s' due to predicate (%s)" % (copyspecs, self.get_predicate(pred=pred))) return if sizelimit is None: sizelimit = self.get_option("log_size") if self.get_option('all_logs'): sizelimit = None if sizelimit: sizelimit *= 1024 * 1024 # in MB if not copyspecs: return False if isinstance(copyspecs, six.string_types): copyspecs = [copyspecs] for copyspec in copyspecs: if not (copyspec and len(copyspec)): return False if self.use_sysroot(): copyspec = self.join_sysroot(copyspec) files = self._expand_copy_spec(copyspec) if len(files) == 0: continue # Files hould be sorted in most-recently-modified order, so that # we collect the newest data first before reaching the limit. def getmtime(path): try: return os.path.getmtime(path) except OSError: return 0 files.sort(key=getmtime, reverse=True) current_size = 0 limit_reached = False _file = None for _file in files: if self._is_forbidden_path(_file): self._log_debug("skipping forbidden path '%s'" % _file) continue try: current_size += os.stat(_file)[stat.ST_SIZE] except OSError: self._log_info("failed to stat '%s'" % _file) if sizelimit and current_size > sizelimit: limit_reached = True break self._add_copy_paths([_file]) if limit_reached and tailit and not _file_is_compressed(_file): file_name = _file if file_name[0] == os.sep: file_name = file_name.lstrip(os.sep) strfile = file_name.replace(os.path.sep, ".") + ".tailed" self.add_string_as_file(tail(_file, sizelimit), strfile) rel_path = os.path.relpath('/', os.path.dirname(_file)) link_path = os.path.join(rel_path, 'sos_strings', self.name(), strfile) self.archive.add_link(link_path, _file)
[ "def", "add_copy_spec", "(", "self", ",", "copyspecs", ",", "sizelimit", "=", "None", ",", "tailit", "=", "True", ",", "pred", "=", "None", ")", ":", "if", "not", "self", ".", "test_predicate", "(", "pred", "=", "pred", ")", ":", "self", ".", "_log_i...
Add a file or glob but limit it to sizelimit megabytes. If fname is a single file the file will be tailed to meet sizelimit. If the first file in a glob is too large it will be tailed to meet the sizelimit.
[ "Add", "a", "file", "or", "glob", "but", "limit", "it", "to", "sizelimit", "megabytes", ".", "If", "fname", "is", "a", "single", "file", "the", "file", "will", "be", "tailed", "to", "meet", "sizelimit", ".", "If", "the", "first", "file", "in", "a", "...
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L754-L827
225,738
sosreport/sos
sos/plugins/__init__.py
Plugin.call_ext_prog
def call_ext_prog(self, prog, timeout=300, stderr=True, chroot=True, runat=None): """Execute a command independantly of the output gathering part of sosreport. """ return self.get_command_output(prog, timeout=timeout, stderr=stderr, chroot=chroot, runat=runat)
python
def call_ext_prog(self, prog, timeout=300, stderr=True, chroot=True, runat=None): """Execute a command independantly of the output gathering part of sosreport. """ return self.get_command_output(prog, timeout=timeout, stderr=stderr, chroot=chroot, runat=runat)
[ "def", "call_ext_prog", "(", "self", ",", "prog", ",", "timeout", "=", "300", ",", "stderr", "=", "True", ",", "chroot", "=", "True", ",", "runat", "=", "None", ")", ":", "return", "self", ".", "get_command_output", "(", "prog", ",", "timeout", "=", ...
Execute a command independantly of the output gathering part of sosreport.
[ "Execute", "a", "command", "independantly", "of", "the", "output", "gathering", "part", "of", "sosreport", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L862-L868
225,739
sosreport/sos
sos/plugins/__init__.py
Plugin._add_cmd_output
def _add_cmd_output(self, cmd, suggest_filename=None, root_symlink=None, timeout=300, stderr=True, chroot=True, runat=None, env=None, binary=False, sizelimit=None, pred=None): """Internal helper to add a single command to the collection list.""" cmdt = ( cmd, suggest_filename, root_symlink, timeout, stderr, chroot, runat, env, binary, sizelimit ) _tuplefmt = ("('%s', '%s', '%s', %s, '%s', '%s', '%s', '%s', '%s', " "'%s')") _logstr = "packed command tuple: " + _tuplefmt self._log_debug(_logstr % cmdt) if self.test_predicate(cmd=True, pred=pred): self.collect_cmds.append(cmdt) self._log_info("added cmd output '%s'" % cmd) else: self._log_info("skipped cmd output '%s' due to predicate (%s)" % (cmd, self.get_predicate(cmd=True, pred=pred)))
python
def _add_cmd_output(self, cmd, suggest_filename=None, root_symlink=None, timeout=300, stderr=True, chroot=True, runat=None, env=None, binary=False, sizelimit=None, pred=None): """Internal helper to add a single command to the collection list.""" cmdt = ( cmd, suggest_filename, root_symlink, timeout, stderr, chroot, runat, env, binary, sizelimit ) _tuplefmt = ("('%s', '%s', '%s', %s, '%s', '%s', '%s', '%s', '%s', " "'%s')") _logstr = "packed command tuple: " + _tuplefmt self._log_debug(_logstr % cmdt) if self.test_predicate(cmd=True, pred=pred): self.collect_cmds.append(cmdt) self._log_info("added cmd output '%s'" % cmd) else: self._log_info("skipped cmd output '%s' due to predicate (%s)" % (cmd, self.get_predicate(cmd=True, pred=pred)))
[ "def", "_add_cmd_output", "(", "self", ",", "cmd", ",", "suggest_filename", "=", "None", ",", "root_symlink", "=", "None", ",", "timeout", "=", "300", ",", "stderr", "=", "True", ",", "chroot", "=", "True", ",", "runat", "=", "None", ",", "env", "=", ...
Internal helper to add a single command to the collection list.
[ "Internal", "helper", "to", "add", "a", "single", "command", "to", "the", "collection", "list", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L877-L896
225,740
sosreport/sos
sos/plugins/__init__.py
Plugin.add_cmd_output
def add_cmd_output(self, cmds, suggest_filename=None, root_symlink=None, timeout=300, stderr=True, chroot=True, runat=None, env=None, binary=False, sizelimit=None, pred=None): """Run a program or a list of programs and collect the output""" if isinstance(cmds, six.string_types): cmds = [cmds] if len(cmds) > 1 and (suggest_filename or root_symlink): self._log_warn("ambiguous filename or symlink for command list") if sizelimit is None: sizelimit = self.get_option("log_size") for cmd in cmds: self._add_cmd_output(cmd, suggest_filename=suggest_filename, root_symlink=root_symlink, timeout=timeout, stderr=stderr, chroot=chroot, runat=runat, env=env, binary=binary, sizelimit=sizelimit, pred=pred)
python
def add_cmd_output(self, cmds, suggest_filename=None, root_symlink=None, timeout=300, stderr=True, chroot=True, runat=None, env=None, binary=False, sizelimit=None, pred=None): """Run a program or a list of programs and collect the output""" if isinstance(cmds, six.string_types): cmds = [cmds] if len(cmds) > 1 and (suggest_filename or root_symlink): self._log_warn("ambiguous filename or symlink for command list") if sizelimit is None: sizelimit = self.get_option("log_size") for cmd in cmds: self._add_cmd_output(cmd, suggest_filename=suggest_filename, root_symlink=root_symlink, timeout=timeout, stderr=stderr, chroot=chroot, runat=runat, env=env, binary=binary, sizelimit=sizelimit, pred=pred)
[ "def", "add_cmd_output", "(", "self", ",", "cmds", ",", "suggest_filename", "=", "None", ",", "root_symlink", "=", "None", ",", "timeout", "=", "300", ",", "stderr", "=", "True", ",", "chroot", "=", "True", ",", "runat", "=", "None", ",", "env", "=", ...
Run a program or a list of programs and collect the output
[ "Run", "a", "program", "or", "a", "list", "of", "programs", "and", "collect", "the", "output" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L898-L914
225,741
sosreport/sos
sos/plugins/__init__.py
Plugin.get_cmd_output_path
def get_cmd_output_path(self, name=None, make=True): """Return a path into which this module should store collected command output """ cmd_output_path = os.path.join(self.archive.get_tmp_dir(), 'sos_commands', self.name()) if name: cmd_output_path = os.path.join(cmd_output_path, name) if make: os.makedirs(cmd_output_path) return cmd_output_path
python
def get_cmd_output_path(self, name=None, make=True): """Return a path into which this module should store collected command output """ cmd_output_path = os.path.join(self.archive.get_tmp_dir(), 'sos_commands', self.name()) if name: cmd_output_path = os.path.join(cmd_output_path, name) if make: os.makedirs(cmd_output_path) return cmd_output_path
[ "def", "get_cmd_output_path", "(", "self", ",", "name", "=", "None", ",", "make", "=", "True", ")", ":", "cmd_output_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "archive", ".", "get_tmp_dir", "(", ")", ",", "'sos_commands'", ",", "sel...
Return a path into which this module should store collected command output
[ "Return", "a", "path", "into", "which", "this", "module", "should", "store", "collected", "command", "output" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L916-L927
225,742
sosreport/sos
sos/plugins/__init__.py
Plugin._make_command_filename
def _make_command_filename(self, exe): """The internal function to build up a filename based on a command.""" outfn = os.path.join(self.commons['cmddir'], self.name(), self._mangle_command(exe)) # check for collisions if os.path.exists(outfn): inc = 2 while True: newfn = "%s_%d" % (outfn, inc) if not os.path.exists(newfn): outfn = newfn break inc += 1 return outfn
python
def _make_command_filename(self, exe): """The internal function to build up a filename based on a command.""" outfn = os.path.join(self.commons['cmddir'], self.name(), self._mangle_command(exe)) # check for collisions if os.path.exists(outfn): inc = 2 while True: newfn = "%s_%d" % (outfn, inc) if not os.path.exists(newfn): outfn = newfn break inc += 1 return outfn
[ "def", "_make_command_filename", "(", "self", ",", "exe", ")", ":", "outfn", "=", "os", ".", "path", ".", "join", "(", "self", ".", "commons", "[", "'cmddir'", "]", ",", "self", ".", "name", "(", ")", ",", "self", ".", "_mangle_command", "(", "exe", ...
The internal function to build up a filename based on a command.
[ "The", "internal", "function", "to", "build", "up", "a", "filename", "based", "on", "a", "command", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L940-L956
225,743
sosreport/sos
sos/plugins/__init__.py
Plugin.add_string_as_file
def add_string_as_file(self, content, filename, pred=None): """Add a string to the archive as a file named `filename`""" # Generate summary string for logging summary = content.splitlines()[0] if content else '' if not isinstance(summary, six.string_types): summary = content.decode('utf8', 'ignore') if not self.test_predicate(cmd=False, pred=pred): self._log_info("skipped string ...'%s' due to predicate (%s)" % (summary, self.get_predicate(pred=pred))) return self.copy_strings.append((content, filename)) self._log_debug("added string ...'%s' as '%s'" % (summary, filename))
python
def add_string_as_file(self, content, filename, pred=None): """Add a string to the archive as a file named `filename`""" # Generate summary string for logging summary = content.splitlines()[0] if content else '' if not isinstance(summary, six.string_types): summary = content.decode('utf8', 'ignore') if not self.test_predicate(cmd=False, pred=pred): self._log_info("skipped string ...'%s' due to predicate (%s)" % (summary, self.get_predicate(pred=pred))) return self.copy_strings.append((content, filename)) self._log_debug("added string ...'%s' as '%s'" % (summary, filename))
[ "def", "add_string_as_file", "(", "self", ",", "content", ",", "filename", ",", "pred", "=", "None", ")", ":", "# Generate summary string for logging", "summary", "=", "content", ".", "splitlines", "(", ")", "[", "0", "]", "if", "content", "else", "''", "if"...
Add a string to the archive as a file named `filename`
[ "Add", "a", "string", "to", "the", "archive", "as", "a", "file", "named", "filename" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L958-L972
225,744
sosreport/sos
sos/plugins/__init__.py
Plugin.add_journal
def add_journal(self, units=None, boot=None, since=None, until=None, lines=None, allfields=False, output=None, timeout=None, identifier=None, catalog=None, sizelimit=None, pred=None): """Collect journald logs from one of more units. :param units: A string, or list of strings specifying the systemd units for which journal entries will be collected. :param boot: A string selecting a boot index using the journalctl syntax. The special values 'this' and 'last' are also accepted. :param since: A string representation of the start time for journal messages. :param until: A string representation of the end time for journal messages. :param lines: The maximum number of lines to be collected. :param allfields: A bool. Include all journal fields regardless of size or non-printable characters. :param output: A journalctl output control string, for example "verbose". :param timeout: An optional timeout in seconds. :param identifier: An optional message identifier. :param catalog: Bool. If True, augment lines with descriptions from the system catalog. :param sizelimit: Limit to the size of output returned in MB. Defaults to the value of --log-size. """ journal_cmd = "journalctl --no-pager " unit_opt = " --unit %s" boot_opt = " --boot %s" since_opt = " --since %s" until_opt = " --until %s" lines_opt = " --lines %s" output_opt = " --output %s" identifier_opt = " --identifier %s" catalog_opt = " --catalog" journal_size = 100 all_logs = self.get_option("all_logs") log_size = sizelimit or self.get_option("log_size") log_size = max(log_size, journal_size) if not all_logs else 0 if isinstance(units, six.string_types): units = [units] if units: for unit in units: journal_cmd += unit_opt % unit if identifier: journal_cmd += identifier_opt % identifier if catalog: journal_cmd += catalog_opt if allfields: journal_cmd += " --all" if boot: if boot == "this": boot = "" if boot == "last": boot = "-1" journal_cmd += boot_opt % boot if since: journal_cmd += since_opt % since if until: journal_cmd += until_opt % until if lines: journal_cmd += lines_opt % lines if output: journal_cmd += output_opt % output self._log_debug("collecting journal: %s" % journal_cmd) self._add_cmd_output(journal_cmd, timeout=timeout, sizelimit=log_size, pred=pred)
python
def add_journal(self, units=None, boot=None, since=None, until=None, lines=None, allfields=False, output=None, timeout=None, identifier=None, catalog=None, sizelimit=None, pred=None): """Collect journald logs from one of more units. :param units: A string, or list of strings specifying the systemd units for which journal entries will be collected. :param boot: A string selecting a boot index using the journalctl syntax. The special values 'this' and 'last' are also accepted. :param since: A string representation of the start time for journal messages. :param until: A string representation of the end time for journal messages. :param lines: The maximum number of lines to be collected. :param allfields: A bool. Include all journal fields regardless of size or non-printable characters. :param output: A journalctl output control string, for example "verbose". :param timeout: An optional timeout in seconds. :param identifier: An optional message identifier. :param catalog: Bool. If True, augment lines with descriptions from the system catalog. :param sizelimit: Limit to the size of output returned in MB. Defaults to the value of --log-size. """ journal_cmd = "journalctl --no-pager " unit_opt = " --unit %s" boot_opt = " --boot %s" since_opt = " --since %s" until_opt = " --until %s" lines_opt = " --lines %s" output_opt = " --output %s" identifier_opt = " --identifier %s" catalog_opt = " --catalog" journal_size = 100 all_logs = self.get_option("all_logs") log_size = sizelimit or self.get_option("log_size") log_size = max(log_size, journal_size) if not all_logs else 0 if isinstance(units, six.string_types): units = [units] if units: for unit in units: journal_cmd += unit_opt % unit if identifier: journal_cmd += identifier_opt % identifier if catalog: journal_cmd += catalog_opt if allfields: journal_cmd += " --all" if boot: if boot == "this": boot = "" if boot == "last": boot = "-1" journal_cmd += boot_opt % boot if since: journal_cmd += since_opt % since if until: journal_cmd += until_opt % until if lines: journal_cmd += lines_opt % lines if output: journal_cmd += output_opt % output self._log_debug("collecting journal: %s" % journal_cmd) self._add_cmd_output(journal_cmd, timeout=timeout, sizelimit=log_size, pred=pred)
[ "def", "add_journal", "(", "self", ",", "units", "=", "None", ",", "boot", "=", "None", ",", "since", "=", "None", ",", "until", "=", "None", ",", "lines", "=", "None", ",", "allfields", "=", "False", ",", "output", "=", "None", ",", "timeout", "="...
Collect journald logs from one of more units. :param units: A string, or list of strings specifying the systemd units for which journal entries will be collected. :param boot: A string selecting a boot index using the journalctl syntax. The special values 'this' and 'last' are also accepted. :param since: A string representation of the start time for journal messages. :param until: A string representation of the end time for journal messages. :param lines: The maximum number of lines to be collected. :param allfields: A bool. Include all journal fields regardless of size or non-printable characters. :param output: A journalctl output control string, for example "verbose". :param timeout: An optional timeout in seconds. :param identifier: An optional message identifier. :param catalog: Bool. If True, augment lines with descriptions from the system catalog. :param sizelimit: Limit to the size of output returned in MB. Defaults to the value of --log-size.
[ "Collect", "journald", "logs", "from", "one", "of", "more", "units", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1046-L1133
225,745
sosreport/sos
sos/plugins/__init__.py
Plugin.add_udev_info
def add_udev_info(self, device, attrs=False): """Collect udevadm info output for a given device :param device: A string or list of strings of device names or sysfs paths. E.G. either '/sys/class/scsi_host/host0' or '/dev/sda' is valid. :param attrs: If True, run udevadm with the --attribute-walk option. """ udev_cmd = 'udevadm info' if attrs: udev_cmd += ' -a' if isinstance(device, six.string_types): device = [device] for dev in device: self._log_debug("collecting udev info for: %s" % dev) self._add_cmd_output('%s %s' % (udev_cmd, dev))
python
def add_udev_info(self, device, attrs=False): """Collect udevadm info output for a given device :param device: A string or list of strings of device names or sysfs paths. E.G. either '/sys/class/scsi_host/host0' or '/dev/sda' is valid. :param attrs: If True, run udevadm with the --attribute-walk option. """ udev_cmd = 'udevadm info' if attrs: udev_cmd += ' -a' if isinstance(device, six.string_types): device = [device] for dev in device: self._log_debug("collecting udev info for: %s" % dev) self._add_cmd_output('%s %s' % (udev_cmd, dev))
[ "def", "add_udev_info", "(", "self", ",", "device", ",", "attrs", "=", "False", ")", ":", "udev_cmd", "=", "'udevadm info'", "if", "attrs", ":", "udev_cmd", "+=", "' -a'", "if", "isinstance", "(", "device", ",", "six", ".", "string_types", ")", ":", "dev...
Collect udevadm info output for a given device :param device: A string or list of strings of device names or sysfs paths. E.G. either '/sys/class/scsi_host/host0' or '/dev/sda' is valid. :param attrs: If True, run udevadm with the --attribute-walk option.
[ "Collect", "udevadm", "info", "output", "for", "a", "given", "device" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1135-L1152
225,746
sosreport/sos
sos/plugins/__init__.py
Plugin.collect
def collect(self): """Collect the data for a plugin.""" start = time() self._collect_copy_specs() self._collect_cmd_output() self._collect_strings() fields = (self.name(), time() - start) self._log_debug("collected plugin '%s' in %s" % fields)
python
def collect(self): """Collect the data for a plugin.""" start = time() self._collect_copy_specs() self._collect_cmd_output() self._collect_strings() fields = (self.name(), time() - start) self._log_debug("collected plugin '%s' in %s" % fields)
[ "def", "collect", "(", "self", ")", ":", "start", "=", "time", "(", ")", "self", ".", "_collect_copy_specs", "(", ")", "self", ".", "_collect_cmd_output", "(", ")", "self", ".", "_collect_strings", "(", ")", "fields", "=", "(", "self", ".", "name", "("...
Collect the data for a plugin.
[ "Collect", "the", "data", "for", "a", "plugin", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1202-L1209
225,747
sosreport/sos
sos/plugins/__init__.py
Plugin.get_description
def get_description(self): """ This function will return the description for the plugin""" try: if hasattr(self, '__doc__') and self.__doc__: return self.__doc__.strip() return super(self.__class__, self).__doc__.strip() except Exception: return "<no description available>"
python
def get_description(self): """ This function will return the description for the plugin""" try: if hasattr(self, '__doc__') and self.__doc__: return self.__doc__.strip() return super(self.__class__, self).__doc__.strip() except Exception: return "<no description available>"
[ "def", "get_description", "(", "self", ")", ":", "try", ":", "if", "hasattr", "(", "self", ",", "'__doc__'", ")", "and", "self", ".", "__doc__", ":", "return", "self", ".", "__doc__", ".", "strip", "(", ")", "return", "super", "(", "self", ".", "__cl...
This function will return the description for the plugin
[ "This", "function", "will", "return", "the", "description", "for", "the", "plugin" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1211-L1218
225,748
sosreport/sos
sos/plugins/__init__.py
Plugin.check_enabled
def check_enabled(self): """This method will be used to verify that a plugin should execute given the condition of the underlying environment. The default implementation will return True if none of class.files, class.packages, nor class.commands is specified. If any of these is specified the plugin will check for the existence of any of the corresponding paths, packages or commands and return True if any are present. For SCLPlugin subclasses, it will check whether the plugin can be run for any of installed SCLs. If so, it will store names of these SCLs on the plugin class in addition to returning True. For plugins with more complex enablement checks this method may be overridden. """ # some files or packages have been specified for this package if any([self.files, self.packages, self.commands, self.kernel_mods, self.services]): if isinstance(self.files, six.string_types): self.files = [self.files] if isinstance(self.packages, six.string_types): self.packages = [self.packages] if isinstance(self.commands, six.string_types): self.commands = [self.commands] if isinstance(self.kernel_mods, six.string_types): self.kernel_mods = [self.kernel_mods] if isinstance(self.services, six.string_types): self.services = [self.services] if isinstance(self, SCLPlugin): # save SCLs that match files or packages type(self)._scls_matched = [] for scl in self._get_scls(): files = [f % {"scl_name": scl} for f in self.files] packages = [p % {"scl_name": scl} for p in self.packages] commands = [c % {"scl_name": scl} for c in self.commands] services = [s % {"scl_name": scl} for s in self.services] if self._check_plugin_triggers(files, packages, commands, services): type(self)._scls_matched.append(scl) return len(type(self)._scls_matched) > 0 return self._check_plugin_triggers(self.files, self.packages, self.commands, self.services) if isinstance(self, SCLPlugin): # if files and packages weren't specified, we take all SCLs type(self)._scls_matched = self._get_scls() return True
python
def check_enabled(self): """This method will be used to verify that a plugin should execute given the condition of the underlying environment. The default implementation will return True if none of class.files, class.packages, nor class.commands is specified. If any of these is specified the plugin will check for the existence of any of the corresponding paths, packages or commands and return True if any are present. For SCLPlugin subclasses, it will check whether the plugin can be run for any of installed SCLs. If so, it will store names of these SCLs on the plugin class in addition to returning True. For plugins with more complex enablement checks this method may be overridden. """ # some files or packages have been specified for this package if any([self.files, self.packages, self.commands, self.kernel_mods, self.services]): if isinstance(self.files, six.string_types): self.files = [self.files] if isinstance(self.packages, six.string_types): self.packages = [self.packages] if isinstance(self.commands, six.string_types): self.commands = [self.commands] if isinstance(self.kernel_mods, six.string_types): self.kernel_mods = [self.kernel_mods] if isinstance(self.services, six.string_types): self.services = [self.services] if isinstance(self, SCLPlugin): # save SCLs that match files or packages type(self)._scls_matched = [] for scl in self._get_scls(): files = [f % {"scl_name": scl} for f in self.files] packages = [p % {"scl_name": scl} for p in self.packages] commands = [c % {"scl_name": scl} for c in self.commands] services = [s % {"scl_name": scl} for s in self.services] if self._check_plugin_triggers(files, packages, commands, services): type(self)._scls_matched.append(scl) return len(type(self)._scls_matched) > 0 return self._check_plugin_triggers(self.files, self.packages, self.commands, self.services) if isinstance(self, SCLPlugin): # if files and packages weren't specified, we take all SCLs type(self)._scls_matched = self._get_scls() return True
[ "def", "check_enabled", "(", "self", ")", ":", "# some files or packages have been specified for this package", "if", "any", "(", "[", "self", ".", "files", ",", "self", ".", "packages", ",", "self", ".", "commands", ",", "self", ".", "kernel_mods", ",", "self",...
This method will be used to verify that a plugin should execute given the condition of the underlying environment. The default implementation will return True if none of class.files, class.packages, nor class.commands is specified. If any of these is specified the plugin will check for the existence of any of the corresponding paths, packages or commands and return True if any are present. For SCLPlugin subclasses, it will check whether the plugin can be run for any of installed SCLs. If so, it will store names of these SCLs on the plugin class in addition to returning True. For plugins with more complex enablement checks this method may be overridden.
[ "This", "method", "will", "be", "used", "to", "verify", "that", "a", "plugin", "should", "execute", "given", "the", "condition", "of", "the", "underlying", "environment", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1220-L1279
225,749
sosreport/sos
sos/plugins/__init__.py
Plugin.report
def report(self): """ Present all information that was gathered in an html file that allows browsing the results. """ # make this prettier html = u'<hr/><a name="%s"></a>\n' % self.name() # Intro html = html + "<h2> Plugin <em>" + self.name() + "</em></h2>\n" # Files if len(self.copied_files): html = html + "<p>Files copied:<br><ul>\n" for afile in self.copied_files: html = html + '<li><a href="%s">%s</a>' % \ (u'..' + _to_u(afile['dstpath']), _to_u(afile['srcpath'])) if afile['symlink'] == "yes": html = html + " (symlink to %s)" % _to_u(afile['pointsto']) html = html + '</li>\n' html = html + "</ul></p>\n" # Command Output if len(self.executed_commands): html = html + "<p>Commands Executed:<br><ul>\n" # convert file name to relative path from our root # don't use relpath - these are HTML paths not OS paths. for cmd in self.executed_commands: if cmd["file"] and len(cmd["file"]): cmd_rel_path = u"../" + _to_u(self.commons['cmddir']) \ + "/" + _to_u(cmd['file']) html = html + '<li><a href="%s">%s</a></li>\n' % \ (cmd_rel_path, _to_u(cmd['exe'])) else: html = html + '<li>%s</li>\n' % (_to_u(cmd['exe'])) html = html + "</ul></p>\n" # Alerts if len(self.alerts): html = html + "<p>Alerts:<br><ul>\n" for alert in self.alerts: html = html + '<li>%s</li>\n' % _to_u(alert) html = html + "</ul></p>\n" # Custom Text if self.custom_text != "": html = html + "<p>Additional Information:<br>\n" html = html + _to_u(self.custom_text) + "</p>\n" if six.PY2: return html.encode('utf8') else: return html
python
def report(self): """ Present all information that was gathered in an html file that allows browsing the results. """ # make this prettier html = u'<hr/><a name="%s"></a>\n' % self.name() # Intro html = html + "<h2> Plugin <em>" + self.name() + "</em></h2>\n" # Files if len(self.copied_files): html = html + "<p>Files copied:<br><ul>\n" for afile in self.copied_files: html = html + '<li><a href="%s">%s</a>' % \ (u'..' + _to_u(afile['dstpath']), _to_u(afile['srcpath'])) if afile['symlink'] == "yes": html = html + " (symlink to %s)" % _to_u(afile['pointsto']) html = html + '</li>\n' html = html + "</ul></p>\n" # Command Output if len(self.executed_commands): html = html + "<p>Commands Executed:<br><ul>\n" # convert file name to relative path from our root # don't use relpath - these are HTML paths not OS paths. for cmd in self.executed_commands: if cmd["file"] and len(cmd["file"]): cmd_rel_path = u"../" + _to_u(self.commons['cmddir']) \ + "/" + _to_u(cmd['file']) html = html + '<li><a href="%s">%s</a></li>\n' % \ (cmd_rel_path, _to_u(cmd['exe'])) else: html = html + '<li>%s</li>\n' % (_to_u(cmd['exe'])) html = html + "</ul></p>\n" # Alerts if len(self.alerts): html = html + "<p>Alerts:<br><ul>\n" for alert in self.alerts: html = html + '<li>%s</li>\n' % _to_u(alert) html = html + "</ul></p>\n" # Custom Text if self.custom_text != "": html = html + "<p>Additional Information:<br>\n" html = html + _to_u(self.custom_text) + "</p>\n" if six.PY2: return html.encode('utf8') else: return html
[ "def", "report", "(", "self", ")", ":", "# make this prettier", "html", "=", "u'<hr/><a name=\"%s\"></a>\\n'", "%", "self", ".", "name", "(", ")", "# Intro", "html", "=", "html", "+", "\"<h2> Plugin <em>\"", "+", "self", ".", "name", "(", ")", "+", "\"</em><...
Present all information that was gathered in an html file that allows browsing the results.
[ "Present", "all", "information", "that", "was", "gathered", "in", "an", "html", "file", "that", "allows", "browsing", "the", "results", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1323-L1374
225,750
sosreport/sos
sos/plugins/__init__.py
Plugin.get_process_pids
def get_process_pids(self, process): """Returns PIDs of all processes with process name. If the process doesn't exist, returns an empty list""" pids = [] cmd_line_glob = "/proc/[0-9]*/cmdline" cmd_line_paths = glob.glob(cmd_line_glob) for path in cmd_line_paths: try: with open(path, 'r') as f: cmd_line = f.read().strip() if process in cmd_line: pids.append(path.split("/")[2]) except IOError as e: continue return pids
python
def get_process_pids(self, process): """Returns PIDs of all processes with process name. If the process doesn't exist, returns an empty list""" pids = [] cmd_line_glob = "/proc/[0-9]*/cmdline" cmd_line_paths = glob.glob(cmd_line_glob) for path in cmd_line_paths: try: with open(path, 'r') as f: cmd_line = f.read().strip() if process in cmd_line: pids.append(path.split("/")[2]) except IOError as e: continue return pids
[ "def", "get_process_pids", "(", "self", ",", "process", ")", ":", "pids", "=", "[", "]", "cmd_line_glob", "=", "\"/proc/[0-9]*/cmdline\"", "cmd_line_paths", "=", "glob", ".", "glob", "(", "cmd_line_glob", ")", "for", "path", "in", "cmd_line_paths", ":", "try",...
Returns PIDs of all processes with process name. If the process doesn't exist, returns an empty list
[ "Returns", "PIDs", "of", "all", "processes", "with", "process", "name", ".", "If", "the", "process", "doesn", "t", "exist", "returns", "an", "empty", "list" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1392-L1406
225,751
sosreport/sos
sos/plugins/__init__.py
SCLPlugin.convert_cmd_scl
def convert_cmd_scl(self, scl, cmd): """wrapping command in "scl enable" call and adds proper PATH """ # load default SCL prefix to PATH prefix = self.policy.get_default_scl_prefix() # read prefix from /etc/scl/prefixes/${scl} and strip trailing '\n' try: prefix = open('/etc/scl/prefixes/%s' % scl, 'r').read()\ .rstrip('\n') except Exception as e: self._log_error("Failed to find prefix for SCL %s, using %s" % (scl, prefix)) # expand PATH by equivalent prefixes under the SCL tree path = os.environ["PATH"] for p in path.split(':'): path = '%s/%s%s:%s' % (prefix, scl, p, path) scl_cmd = "scl enable %s \"PATH=%s %s\"" % (scl, path, cmd) return scl_cmd
python
def convert_cmd_scl(self, scl, cmd): """wrapping command in "scl enable" call and adds proper PATH """ # load default SCL prefix to PATH prefix = self.policy.get_default_scl_prefix() # read prefix from /etc/scl/prefixes/${scl} and strip trailing '\n' try: prefix = open('/etc/scl/prefixes/%s' % scl, 'r').read()\ .rstrip('\n') except Exception as e: self._log_error("Failed to find prefix for SCL %s, using %s" % (scl, prefix)) # expand PATH by equivalent prefixes under the SCL tree path = os.environ["PATH"] for p in path.split(':'): path = '%s/%s%s:%s' % (prefix, scl, p, path) scl_cmd = "scl enable %s \"PATH=%s %s\"" % (scl, path, cmd) return scl_cmd
[ "def", "convert_cmd_scl", "(", "self", ",", "scl", ",", "cmd", ")", ":", "# load default SCL prefix to PATH", "prefix", "=", "self", ".", "policy", ".", "get_default_scl_prefix", "(", ")", "# read prefix from /etc/scl/prefixes/${scl} and strip trailing '\\n'", "try", ":",...
wrapping command in "scl enable" call and adds proper PATH
[ "wrapping", "command", "in", "scl", "enable", "call", "and", "adds", "proper", "PATH" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1448-L1467
225,752
sosreport/sos
sos/plugins/__init__.py
SCLPlugin.add_cmd_output_scl
def add_cmd_output_scl(self, scl, cmds, **kwargs): """Same as add_cmd_output, except that it wraps command in "scl enable" call and sets proper PATH. """ if isinstance(cmds, six.string_types): cmds = [cmds] scl_cmds = [] for cmd in cmds: scl_cmds.append(self.convert_cmd_scl(scl, cmd)) self.add_cmd_output(scl_cmds, **kwargs)
python
def add_cmd_output_scl(self, scl, cmds, **kwargs): """Same as add_cmd_output, except that it wraps command in "scl enable" call and sets proper PATH. """ if isinstance(cmds, six.string_types): cmds = [cmds] scl_cmds = [] for cmd in cmds: scl_cmds.append(self.convert_cmd_scl(scl, cmd)) self.add_cmd_output(scl_cmds, **kwargs)
[ "def", "add_cmd_output_scl", "(", "self", ",", "scl", ",", "cmds", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "cmds", ",", "six", ".", "string_types", ")", ":", "cmds", "=", "[", "cmds", "]", "scl_cmds", "=", "[", "]", "for", "cmd"...
Same as add_cmd_output, except that it wraps command in "scl enable" call and sets proper PATH.
[ "Same", "as", "add_cmd_output", "except", "that", "it", "wraps", "command", "in", "scl", "enable", "call", "and", "sets", "proper", "PATH", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1469-L1478
225,753
sosreport/sos
sos/plugins/__init__.py
SCLPlugin.add_copy_spec_scl
def add_copy_spec_scl(self, scl, copyspecs): """Same as add_copy_spec, except that it prepends path to SCL root to "copyspecs". """ if isinstance(copyspecs, six.string_types): copyspecs = [copyspecs] scl_copyspecs = [] for copyspec in copyspecs: scl_copyspecs.append(self.convert_copyspec_scl(scl, copyspec)) self.add_copy_spec(scl_copyspecs)
python
def add_copy_spec_scl(self, scl, copyspecs): """Same as add_copy_spec, except that it prepends path to SCL root to "copyspecs". """ if isinstance(copyspecs, six.string_types): copyspecs = [copyspecs] scl_copyspecs = [] for copyspec in copyspecs: scl_copyspecs.append(self.convert_copyspec_scl(scl, copyspec)) self.add_copy_spec(scl_copyspecs)
[ "def", "add_copy_spec_scl", "(", "self", ",", "scl", ",", "copyspecs", ")", ":", "if", "isinstance", "(", "copyspecs", ",", "six", ".", "string_types", ")", ":", "copyspecs", "=", "[", "copyspecs", "]", "scl_copyspecs", "=", "[", "]", "for", "copyspec", ...
Same as add_copy_spec, except that it prepends path to SCL root to "copyspecs".
[ "Same", "as", "add_copy_spec", "except", "that", "it", "prepends", "path", "to", "SCL", "root", "to", "copyspecs", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1492-L1501
225,754
sosreport/sos
sos/plugins/__init__.py
SCLPlugin.add_copy_spec_limit_scl
def add_copy_spec_limit_scl(self, scl, copyspec, **kwargs): """Same as add_copy_spec_limit, except that it prepends path to SCL root to "copyspec". """ self.add_copy_spec_limit( self.convert_copyspec_scl(scl, copyspec), **kwargs )
python
def add_copy_spec_limit_scl(self, scl, copyspec, **kwargs): """Same as add_copy_spec_limit, except that it prepends path to SCL root to "copyspec". """ self.add_copy_spec_limit( self.convert_copyspec_scl(scl, copyspec), **kwargs )
[ "def", "add_copy_spec_limit_scl", "(", "self", ",", "scl", ",", "copyspec", ",", "*", "*", "kwargs", ")", ":", "self", ".", "add_copy_spec_limit", "(", "self", ".", "convert_copyspec_scl", "(", "scl", ",", "copyspec", ")", ",", "*", "*", "kwargs", ")" ]
Same as add_copy_spec_limit, except that it prepends path to SCL root to "copyspec".
[ "Same", "as", "add_copy_spec_limit", "except", "that", "it", "prepends", "path", "to", "SCL", "root", "to", "copyspec", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1503-L1510
225,755
sosreport/sos
sos/plugins/veritas.py
Veritas.setup
def setup(self): """ interface with vrtsexplorer to capture veritas related data """ r = self.call_ext_prog(self.get_option("script")) if r['status'] == 0: tarfile = "" for line in r['output']: line = line.strip() tarfile = self.do_regex_find_all(r"ftp (.*tar.gz)", line) if len(tarfile) == 1: self.add_copy_spec(tarfile[0])
python
def setup(self): """ interface with vrtsexplorer to capture veritas related data """ r = self.call_ext_prog(self.get_option("script")) if r['status'] == 0: tarfile = "" for line in r['output']: line = line.strip() tarfile = self.do_regex_find_all(r"ftp (.*tar.gz)", line) if len(tarfile) == 1: self.add_copy_spec(tarfile[0])
[ "def", "setup", "(", "self", ")", ":", "r", "=", "self", ".", "call_ext_prog", "(", "self", ".", "get_option", "(", "\"script\"", ")", ")", "if", "r", "[", "'status'", "]", "==", "0", ":", "tarfile", "=", "\"\"", "for", "line", "in", "r", "[", "'...
interface with vrtsexplorer to capture veritas related data
[ "interface", "with", "vrtsexplorer", "to", "capture", "veritas", "related", "data" ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/veritas.py#L28-L37
225,756
sosreport/sos
sos/plugins/openstack_ansible.py
OpenStackAnsible.postproc
def postproc(self): """Remove sensitive keys and passwords from YAML files.""" secrets_files = [ "/etc/openstack_deploy/user_secrets.yml", "/etc/rpc_deploy/user_secrets.yml" ] regexp = r"(?m)^\s*#*([\w_]*:\s*).*" for secrets_file in secrets_files: self.do_path_regex_sub( secrets_file, regexp, r"\1*********")
python
def postproc(self): """Remove sensitive keys and passwords from YAML files.""" secrets_files = [ "/etc/openstack_deploy/user_secrets.yml", "/etc/rpc_deploy/user_secrets.yml" ] regexp = r"(?m)^\s*#*([\w_]*:\s*).*" for secrets_file in secrets_files: self.do_path_regex_sub( secrets_file, regexp, r"\1*********")
[ "def", "postproc", "(", "self", ")", ":", "secrets_files", "=", "[", "\"/etc/openstack_deploy/user_secrets.yml\"", ",", "\"/etc/rpc_deploy/user_secrets.yml\"", "]", "regexp", "=", "r\"(?m)^\\s*#*([\\w_]*:\\s*).*\"", "for", "secrets_file", "in", "secrets_files", ":", "self",...
Remove sensitive keys and passwords from YAML files.
[ "Remove", "sensitive", "keys", "and", "passwords", "from", "YAML", "files", "." ]
2ebc04da53dc871c8dd5243567afa4f8592dca29
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/openstack_ansible.py#L30-L41
225,757
timothycrosley/isort
isort/main.py
ISortCommand.finalize_options
def finalize_options(self) -> None: "Get options from config files." self.arguments = {} # type: Dict[str, Any] computed_settings = from_path(os.getcwd()) for key, value in computed_settings.items(): self.arguments[key] = value
python
def finalize_options(self) -> None: "Get options from config files." self.arguments = {} # type: Dict[str, Any] computed_settings = from_path(os.getcwd()) for key, value in computed_settings.items(): self.arguments[key] = value
[ "def", "finalize_options", "(", "self", ")", "->", "None", ":", "self", ".", "arguments", "=", "{", "}", "# type: Dict[str, Any]", "computed_settings", "=", "from_path", "(", "os", ".", "getcwd", "(", ")", ")", "for", "key", ",", "value", "in", "computed_s...
Get options from config files.
[ "Get", "options", "from", "config", "files", "." ]
493c02a1a000fe782cec56f1f43262bacb316381
https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/main.py#L131-L136
225,758
timothycrosley/isort
isort/main.py
ISortCommand.distribution_files
def distribution_files(self) -> Iterator[str]: """Find distribution packages.""" # This is verbatim from flake8 if self.distribution.packages: package_dirs = self.distribution.package_dir or {} for package in self.distribution.packages: pkg_dir = package if package in package_dirs: pkg_dir = package_dirs[package] elif '' in package_dirs: pkg_dir = package_dirs[''] + os.path.sep + pkg_dir yield pkg_dir.replace('.', os.path.sep) if self.distribution.py_modules: for filename in self.distribution.py_modules: yield "%s.py" % filename # Don't miss the setup.py file itself yield "setup.py"
python
def distribution_files(self) -> Iterator[str]: """Find distribution packages.""" # This is verbatim from flake8 if self.distribution.packages: package_dirs = self.distribution.package_dir or {} for package in self.distribution.packages: pkg_dir = package if package in package_dirs: pkg_dir = package_dirs[package] elif '' in package_dirs: pkg_dir = package_dirs[''] + os.path.sep + pkg_dir yield pkg_dir.replace('.', os.path.sep) if self.distribution.py_modules: for filename in self.distribution.py_modules: yield "%s.py" % filename # Don't miss the setup.py file itself yield "setup.py"
[ "def", "distribution_files", "(", "self", ")", "->", "Iterator", "[", "str", "]", ":", "# This is verbatim from flake8", "if", "self", ".", "distribution", ".", "packages", ":", "package_dirs", "=", "self", ".", "distribution", ".", "package_dir", "or", "{", "...
Find distribution packages.
[ "Find", "distribution", "packages", "." ]
493c02a1a000fe782cec56f1f43262bacb316381
https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/main.py#L138-L155
225,759
timothycrosley/isort
isort/utils.py
chdir
def chdir(path: str) -> Iterator[None]: """Context manager for changing dir and restoring previous workdir after exit. """ curdir = os.getcwd() os.chdir(path) try: yield finally: os.chdir(curdir)
python
def chdir(path: str) -> Iterator[None]: """Context manager for changing dir and restoring previous workdir after exit. """ curdir = os.getcwd() os.chdir(path) try: yield finally: os.chdir(curdir)
[ "def", "chdir", "(", "path", ":", "str", ")", "->", "Iterator", "[", "None", "]", ":", "curdir", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "path", ")", "try", ":", "yield", "finally", ":", "os", ".", "chdir", "(", "curdir", "...
Context manager for changing dir and restoring previous workdir after exit.
[ "Context", "manager", "for", "changing", "dir", "and", "restoring", "previous", "workdir", "after", "exit", "." ]
493c02a1a000fe782cec56f1f43262bacb316381
https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/utils.py#L23-L31
225,760
timothycrosley/isort
isort/utils.py
union
def union(a: Iterable[Any], b: Iterable[Any]) -> List[Any]: """ Return a list of items that are in `a` or `b` """ u = [] # type: List[Any] for item in a: if item not in u: u.append(item) for item in b: if item not in u: u.append(item) return u
python
def union(a: Iterable[Any], b: Iterable[Any]) -> List[Any]: """ Return a list of items that are in `a` or `b` """ u = [] # type: List[Any] for item in a: if item not in u: u.append(item) for item in b: if item not in u: u.append(item) return u
[ "def", "union", "(", "a", ":", "Iterable", "[", "Any", "]", ",", "b", ":", "Iterable", "[", "Any", "]", ")", "->", "List", "[", "Any", "]", ":", "u", "=", "[", "]", "# type: List[Any]", "for", "item", "in", "a", ":", "if", "item", "not", "in", ...
Return a list of items that are in `a` or `b`
[ "Return", "a", "list", "of", "items", "that", "are", "in", "a", "or", "b" ]
493c02a1a000fe782cec56f1f43262bacb316381
https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/utils.py#L34-L44
225,761
timothycrosley/isort
isort/utils.py
difference
def difference(a: Iterable[Any], b: Container[Any]) -> List[Any]: """ Return a list of items from `a` that are not in `b`. """ d = [] for item in a: if item not in b: d.append(item) return d
python
def difference(a: Iterable[Any], b: Container[Any]) -> List[Any]: """ Return a list of items from `a` that are not in `b`. """ d = [] for item in a: if item not in b: d.append(item) return d
[ "def", "difference", "(", "a", ":", "Iterable", "[", "Any", "]", ",", "b", ":", "Container", "[", "Any", "]", ")", "->", "List", "[", "Any", "]", ":", "d", "=", "[", "]", "for", "item", "in", "a", ":", "if", "item", "not", "in", "b", ":", "...
Return a list of items from `a` that are not in `b`.
[ "Return", "a", "list", "of", "items", "from", "a", "that", "are", "not", "in", "b", "." ]
493c02a1a000fe782cec56f1f43262bacb316381
https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/utils.py#L47-L54
225,762
timothycrosley/isort
kate_plugin/isort_plugin.py
sort_kate_imports
def sort_kate_imports(add_imports=(), remove_imports=()): """Sorts imports within Kate while maintaining cursor position and selection, even if length of file changes.""" document = kate.activeDocument() view = document.activeView() position = view.cursorPosition() selection = view.selectionRange() sorter = SortImports(file_contents=document.text(), add_imports=add_imports, remove_imports=remove_imports, settings_path=os.path.dirname(os.path.abspath(str(document.url().path())))) document.setText(sorter.output) position.setLine(position.line() + sorter.length_change) if selection: start = selection.start() start.setLine(start.line() + sorter.length_change) end = selection.end() end.setLine(end.line() + sorter.length_change) selection.setRange(start, end) view.setSelection(selection) view.setCursorPosition(position)
python
def sort_kate_imports(add_imports=(), remove_imports=()): """Sorts imports within Kate while maintaining cursor position and selection, even if length of file changes.""" document = kate.activeDocument() view = document.activeView() position = view.cursorPosition() selection = view.selectionRange() sorter = SortImports(file_contents=document.text(), add_imports=add_imports, remove_imports=remove_imports, settings_path=os.path.dirname(os.path.abspath(str(document.url().path())))) document.setText(sorter.output) position.setLine(position.line() + sorter.length_change) if selection: start = selection.start() start.setLine(start.line() + sorter.length_change) end = selection.end() end.setLine(end.line() + sorter.length_change) selection.setRange(start, end) view.setSelection(selection) view.setCursorPosition(position)
[ "def", "sort_kate_imports", "(", "add_imports", "=", "(", ")", ",", "remove_imports", "=", "(", ")", ")", ":", "document", "=", "kate", ".", "activeDocument", "(", ")", "view", "=", "document", ".", "activeView", "(", ")", "position", "=", "view", ".", ...
Sorts imports within Kate while maintaining cursor position and selection, even if length of file changes.
[ "Sorts", "imports", "within", "Kate", "while", "maintaining", "cursor", "position", "and", "selection", "even", "if", "length", "of", "file", "changes", "." ]
493c02a1a000fe782cec56f1f43262bacb316381
https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/kate_plugin/isort_plugin.py#L37-L54
225,763
timothycrosley/isort
isort/isort.py
_SortImports._get_line
def _get_line(self) -> str: """Returns the current line from the file while incrementing the index.""" line = self.in_lines[self.index] self.index += 1 return line
python
def _get_line(self) -> str: """Returns the current line from the file while incrementing the index.""" line = self.in_lines[self.index] self.index += 1 return line
[ "def", "_get_line", "(", "self", ")", "->", "str", ":", "line", "=", "self", ".", "in_lines", "[", "self", ".", "index", "]", "self", ".", "index", "+=", "1", "return", "line" ]
Returns the current line from the file while incrementing the index.
[ "Returns", "the", "current", "line", "from", "the", "file", "while", "incrementing", "the", "index", "." ]
493c02a1a000fe782cec56f1f43262bacb316381
https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/isort.py#L139-L143
225,764
timothycrosley/isort
isort/isort.py
_SortImports._add_comments
def _add_comments( self, comments: Optional[Sequence[str]], original_string: str = "" ) -> str: """ Returns a string with comments added if ignore_comments is not set. """ if self.config['ignore_comments']: return self._strip_comments(original_string)[0] if not comments: return original_string else: return "{0}{1} {2}".format(self._strip_comments(original_string)[0], self.config['comment_prefix'], "; ".join(comments))
python
def _add_comments( self, comments: Optional[Sequence[str]], original_string: str = "" ) -> str: """ Returns a string with comments added if ignore_comments is not set. """ if self.config['ignore_comments']: return self._strip_comments(original_string)[0] if not comments: return original_string else: return "{0}{1} {2}".format(self._strip_comments(original_string)[0], self.config['comment_prefix'], "; ".join(comments))
[ "def", "_add_comments", "(", "self", ",", "comments", ":", "Optional", "[", "Sequence", "[", "str", "]", "]", ",", "original_string", ":", "str", "=", "\"\"", ")", "->", "str", ":", "if", "self", ".", "config", "[", "'ignore_comments'", "]", ":", "retu...
Returns a string with comments added if ignore_comments is not set.
[ "Returns", "a", "string", "with", "comments", "added", "if", "ignore_comments", "is", "not", "set", "." ]
493c02a1a000fe782cec56f1f43262bacb316381
https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/isort.py#L194-L210
225,765
timothycrosley/isort
isort/isort.py
_SortImports._wrap
def _wrap(self, line: str) -> str: """ Returns an import wrapped to the specified line-length, if possible. """ wrap_mode = self.config['multi_line_output'] if len(line) > self.config['line_length'] and wrap_mode != WrapModes.NOQA: line_without_comment = line comment = None if '#' in line: line_without_comment, comment = line.split('#', 1) for splitter in ("import ", ".", "as "): exp = r"\b" + re.escape(splitter) + r"\b" if re.search(exp, line_without_comment) and not line_without_comment.strip().startswith(splitter): line_parts = re.split(exp, line_without_comment) if comment: line_parts[-1] = '{0}#{1}'.format(line_parts[-1], comment) next_line = [] while (len(line) + 2) > (self.config['wrap_length'] or self.config['line_length']) and line_parts: next_line.append(line_parts.pop()) line = splitter.join(line_parts) if not line: line = next_line.pop() cont_line = self._wrap(self.config['indent'] + splitter.join(next_line).lstrip()) if self.config['use_parentheses']: output = "{0}{1}({2}{3}{4}{5})".format( line, splitter, self.line_separator, cont_line, "," if self.config['include_trailing_comma'] else "", self.line_separator if wrap_mode in {WrapModes.VERTICAL_HANGING_INDENT, WrapModes.VERTICAL_GRID_GROUPED} else "") lines = output.split(self.line_separator) if self.config['comment_prefix'] in lines[-1] and lines[-1].endswith(')'): line, comment = lines[-1].split(self.config['comment_prefix'], 1) lines[-1] = line + ')' + self.config['comment_prefix'] + comment[:-1] return self.line_separator.join(lines) return "{0}{1}\\{2}{3}".format(line, splitter, self.line_separator, cont_line) elif len(line) > self.config['line_length'] and wrap_mode == settings.WrapModes.NOQA: if "# NOQA" not in line: return "{0}{1} NOQA".format(line, self.config['comment_prefix']) return line
python
def _wrap(self, line: str) -> str: """ Returns an import wrapped to the specified line-length, if possible. """ wrap_mode = self.config['multi_line_output'] if len(line) > self.config['line_length'] and wrap_mode != WrapModes.NOQA: line_without_comment = line comment = None if '#' in line: line_without_comment, comment = line.split('#', 1) for splitter in ("import ", ".", "as "): exp = r"\b" + re.escape(splitter) + r"\b" if re.search(exp, line_without_comment) and not line_without_comment.strip().startswith(splitter): line_parts = re.split(exp, line_without_comment) if comment: line_parts[-1] = '{0}#{1}'.format(line_parts[-1], comment) next_line = [] while (len(line) + 2) > (self.config['wrap_length'] or self.config['line_length']) and line_parts: next_line.append(line_parts.pop()) line = splitter.join(line_parts) if not line: line = next_line.pop() cont_line = self._wrap(self.config['indent'] + splitter.join(next_line).lstrip()) if self.config['use_parentheses']: output = "{0}{1}({2}{3}{4}{5})".format( line, splitter, self.line_separator, cont_line, "," if self.config['include_trailing_comma'] else "", self.line_separator if wrap_mode in {WrapModes.VERTICAL_HANGING_INDENT, WrapModes.VERTICAL_GRID_GROUPED} else "") lines = output.split(self.line_separator) if self.config['comment_prefix'] in lines[-1] and lines[-1].endswith(')'): line, comment = lines[-1].split(self.config['comment_prefix'], 1) lines[-1] = line + ')' + self.config['comment_prefix'] + comment[:-1] return self.line_separator.join(lines) return "{0}{1}\\{2}{3}".format(line, splitter, self.line_separator, cont_line) elif len(line) > self.config['line_length'] and wrap_mode == settings.WrapModes.NOQA: if "# NOQA" not in line: return "{0}{1} NOQA".format(line, self.config['comment_prefix']) return line
[ "def", "_wrap", "(", "self", ",", "line", ":", "str", ")", "->", "str", ":", "wrap_mode", "=", "self", ".", "config", "[", "'multi_line_output'", "]", "if", "len", "(", "line", ")", ">", "self", ".", "config", "[", "'line_length'", "]", "and", "wrap_...
Returns an import wrapped to the specified line-length, if possible.
[ "Returns", "an", "import", "wrapped", "to", "the", "specified", "line", "-", "length", "if", "possible", "." ]
493c02a1a000fe782cec56f1f43262bacb316381
https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/isort.py#L212-L253
225,766
timothycrosley/isort
isort/finders.py
KnownPatternFinder._parse_known_pattern
def _parse_known_pattern(self, pattern: str) -> List[str]: """ Expand pattern if identified as a directory and return found sub packages """ if pattern.endswith(os.path.sep): patterns = [ filename for filename in os.listdir(pattern) if os.path.isdir(os.path.join(pattern, filename)) ] else: patterns = [pattern] return patterns
python
def _parse_known_pattern(self, pattern: str) -> List[str]: """ Expand pattern if identified as a directory and return found sub packages """ if pattern.endswith(os.path.sep): patterns = [ filename for filename in os.listdir(pattern) if os.path.isdir(os.path.join(pattern, filename)) ] else: patterns = [pattern] return patterns
[ "def", "_parse_known_pattern", "(", "self", ",", "pattern", ":", "str", ")", "->", "List", "[", "str", "]", ":", "if", "pattern", ".", "endswith", "(", "os", ".", "path", ".", "sep", ")", ":", "patterns", "=", "[", "filename", "for", "filename", "in"...
Expand pattern if identified as a directory and return found sub packages
[ "Expand", "pattern", "if", "identified", "as", "a", "directory", "and", "return", "found", "sub", "packages" ]
493c02a1a000fe782cec56f1f43262bacb316381
https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/finders.py#L86-L99
225,767
timothycrosley/isort
isort/finders.py
ReqsBaseFinder._load_mapping
def _load_mapping() -> Optional[Dict[str, str]]: """Return list of mappings `package_name -> module_name` Example: django-haystack -> haystack """ if not pipreqs: return None path = os.path.dirname(inspect.getfile(pipreqs)) path = os.path.join(path, 'mapping') with open(path) as f: # pypi_name: import_name mappings = {} # type: Dict[str, str] for line in f: import_name, _, pypi_name = line.strip().partition(":") mappings[pypi_name] = import_name return mappings
python
def _load_mapping() -> Optional[Dict[str, str]]: """Return list of mappings `package_name -> module_name` Example: django-haystack -> haystack """ if not pipreqs: return None path = os.path.dirname(inspect.getfile(pipreqs)) path = os.path.join(path, 'mapping') with open(path) as f: # pypi_name: import_name mappings = {} # type: Dict[str, str] for line in f: import_name, _, pypi_name = line.strip().partition(":") mappings[pypi_name] = import_name return mappings
[ "def", "_load_mapping", "(", ")", "->", "Optional", "[", "Dict", "[", "str", ",", "str", "]", "]", ":", "if", "not", "pipreqs", ":", "return", "None", "path", "=", "os", ".", "path", ".", "dirname", "(", "inspect", ".", "getfile", "(", "pipreqs", "...
Return list of mappings `package_name -> module_name` Example: django-haystack -> haystack
[ "Return", "list", "of", "mappings", "package_name", "-", ">", "module_name" ]
493c02a1a000fe782cec56f1f43262bacb316381
https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/finders.py#L200-L216
225,768
timothycrosley/isort
isort/finders.py
ReqsBaseFinder._load_names
def _load_names(self) -> List[str]: """Return list of thirdparty modules from requirements """ names = [] for path in self._get_files(): for name in self._get_names(path): names.append(self._normalize_name(name)) return names
python
def _load_names(self) -> List[str]: """Return list of thirdparty modules from requirements """ names = [] for path in self._get_files(): for name in self._get_names(path): names.append(self._normalize_name(name)) return names
[ "def", "_load_names", "(", "self", ")", "->", "List", "[", "str", "]", ":", "names", "=", "[", "]", "for", "path", "in", "self", ".", "_get_files", "(", ")", ":", "for", "name", "in", "self", ".", "_get_names", "(", "path", ")", ":", "names", "."...
Return list of thirdparty modules from requirements
[ "Return", "list", "of", "thirdparty", "modules", "from", "requirements" ]
493c02a1a000fe782cec56f1f43262bacb316381
https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/finders.py#L219-L226
225,769
timothycrosley/isort
isort/finders.py
ReqsBaseFinder._get_files
def _get_files(self) -> Iterator[str]: """Return paths to all requirements files """ path = os.path.abspath(self.path) if os.path.isfile(path): path = os.path.dirname(path) for path in self._get_parents(path): for file_path in self._get_files_from_dir(path): yield file_path
python
def _get_files(self) -> Iterator[str]: """Return paths to all requirements files """ path = os.path.abspath(self.path) if os.path.isfile(path): path = os.path.dirname(path) for path in self._get_parents(path): for file_path in self._get_files_from_dir(path): yield file_path
[ "def", "_get_files", "(", "self", ")", "->", "Iterator", "[", "str", "]", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "self", ".", "path", ")", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "path", "=", "os", ".",...
Return paths to all requirements files
[ "Return", "paths", "to", "all", "requirements", "files" ]
493c02a1a000fe782cec56f1f43262bacb316381
https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/finders.py#L236-L245
225,770
timothycrosley/isort
isort/finders.py
ReqsBaseFinder._normalize_name
def _normalize_name(self, name: str) -> str: """Convert package name to module name Examples: Django -> django django-haystack -> django_haystack Flask-RESTFul -> flask_restful """ if self.mapping: name = self.mapping.get(name, name) return name.lower().replace('-', '_')
python
def _normalize_name(self, name: str) -> str: """Convert package name to module name Examples: Django -> django django-haystack -> django_haystack Flask-RESTFul -> flask_restful """ if self.mapping: name = self.mapping.get(name, name) return name.lower().replace('-', '_')
[ "def", "_normalize_name", "(", "self", ",", "name", ":", "str", ")", "->", "str", ":", "if", "self", ".", "mapping", ":", "name", "=", "self", ".", "mapping", ".", "get", "(", "name", ",", "name", ")", "return", "name", ".", "lower", "(", ")", "....
Convert package name to module name Examples: Django -> django django-haystack -> django_haystack Flask-RESTFul -> flask_restful
[ "Convert", "package", "name", "to", "module", "name" ]
493c02a1a000fe782cec56f1f43262bacb316381
https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/finders.py#L247-L257
225,771
timothycrosley/isort
isort/finders.py
RequirementsFinder._get_names
def _get_names(self, path: str) -> Iterator[str]: """Load required packages from path to requirements file """ for i in RequirementsFinder._get_names_cached(path): yield i
python
def _get_names(self, path: str) -> Iterator[str]: """Load required packages from path to requirements file """ for i in RequirementsFinder._get_names_cached(path): yield i
[ "def", "_get_names", "(", "self", ",", "path", ":", "str", ")", "->", "Iterator", "[", "str", "]", ":", "for", "i", "in", "RequirementsFinder", ".", "_get_names_cached", "(", "path", ")", ":", "yield", "i" ]
Load required packages from path to requirements file
[ "Load", "required", "packages", "from", "path", "to", "requirements", "file" ]
493c02a1a000fe782cec56f1f43262bacb316381
https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/finders.py#L310-L314
225,772
graphql-python/graphql-ws
graphql_ws/django_channels.py
GraphQLSubscriptionConsumer.receive
def receive(self, content, **kwargs): """ Called when a message is received with either text or bytes filled out. """ self.connection_context = DjangoChannelConnectionContext(self.message) self.subscription_server = DjangoChannelSubscriptionServer(graphene_settings.SCHEMA) self.subscription_server.on_open(self.connection_context) self.subscription_server.handle(content, self.connection_context)
python
def receive(self, content, **kwargs): """ Called when a message is received with either text or bytes filled out. """ self.connection_context = DjangoChannelConnectionContext(self.message) self.subscription_server = DjangoChannelSubscriptionServer(graphene_settings.SCHEMA) self.subscription_server.on_open(self.connection_context) self.subscription_server.handle(content, self.connection_context)
[ "def", "receive", "(", "self", ",", "content", ",", "*", "*", "kwargs", ")", ":", "self", ".", "connection_context", "=", "DjangoChannelConnectionContext", "(", "self", ".", "message", ")", "self", ".", "subscription_server", "=", "DjangoChannelSubscriptionServer"...
Called when a message is received with either text or bytes filled out.
[ "Called", "when", "a", "message", "is", "received", "with", "either", "text", "or", "bytes", "filled", "out", "." ]
523dd1516d8709149a475602042d6a3c5eab5a3d
https://github.com/graphql-python/graphql-ws/blob/523dd1516d8709149a475602042d6a3c5eab5a3d/graphql_ws/django_channels.py#L106-L114
225,773
autokey/autokey
lib/autokey/qtui/settings/general.py
GeneralSettings.save
def save(self): """Called by the parent settings dialog when the user clicks on the Save button. Stores the current settings in the ConfigManager.""" logger.debug("User requested to save settings. New settings: " + self._settings_str()) cm.ConfigManager.SETTINGS[cm.PROMPT_TO_SAVE] = not self.autosave_checkbox.isChecked() cm.ConfigManager.SETTINGS[cm.SHOW_TRAY_ICON] = self.show_tray_checkbox.isChecked() # cm.ConfigManager.SETTINGS[cm.MENU_TAKES_FOCUS] = self.allow_kb_nav_checkbox.isChecked() cm.ConfigManager.SETTINGS[cm.SORT_BY_USAGE_COUNT] = self.sort_by_usage_checkbox.isChecked() cm.ConfigManager.SETTINGS[cm.UNDO_USING_BACKSPACE] = self.enable_undo_checkbox.isChecked() cm.ConfigManager.SETTINGS[cm.NOTIFICATION_ICON] = self.system_tray_icon_theme_combobox.currentData(Qt.UserRole) # TODO: After saving the notification icon, apply it to the currently running instance. self._save_autostart_settings()
python
def save(self): """Called by the parent settings dialog when the user clicks on the Save button. Stores the current settings in the ConfigManager.""" logger.debug("User requested to save settings. New settings: " + self._settings_str()) cm.ConfigManager.SETTINGS[cm.PROMPT_TO_SAVE] = not self.autosave_checkbox.isChecked() cm.ConfigManager.SETTINGS[cm.SHOW_TRAY_ICON] = self.show_tray_checkbox.isChecked() # cm.ConfigManager.SETTINGS[cm.MENU_TAKES_FOCUS] = self.allow_kb_nav_checkbox.isChecked() cm.ConfigManager.SETTINGS[cm.SORT_BY_USAGE_COUNT] = self.sort_by_usage_checkbox.isChecked() cm.ConfigManager.SETTINGS[cm.UNDO_USING_BACKSPACE] = self.enable_undo_checkbox.isChecked() cm.ConfigManager.SETTINGS[cm.NOTIFICATION_ICON] = self.system_tray_icon_theme_combobox.currentData(Qt.UserRole) # TODO: After saving the notification icon, apply it to the currently running instance. self._save_autostart_settings()
[ "def", "save", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"User requested to save settings. New settings: \"", "+", "self", ".", "_settings_str", "(", ")", ")", "cm", ".", "ConfigManager", ".", "SETTINGS", "[", "cm", ".", "PROMPT_TO_SAVE", "]", "=",...
Called by the parent settings dialog when the user clicks on the Save button. Stores the current settings in the ConfigManager.
[ "Called", "by", "the", "parent", "settings", "dialog", "when", "the", "user", "clicks", "on", "the", "Save", "button", ".", "Stores", "the", "current", "settings", "in", "the", "ConfigManager", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtui/settings/general.py#L59-L70
225,774
autokey/autokey
lib/autokey/qtui/settings/general.py
GeneralSettings._settings_str
def _settings_str(self): """Returns a human readable settings representation for logging purposes.""" settings = "Automatically save changes: {}, " \ "Show tray icon: {}, " \ "Allow keyboard navigation: {}, " \ "Sort by usage count: {}, " \ "Enable undo using backspace: {}, " \ "Tray icon theme: {}".format( self.autosave_checkbox.isChecked(), self.show_tray_checkbox.isChecked(), self.allow_kb_nav_checkbox.isChecked(), self.sort_by_usage_checkbox.isChecked(), self.enable_undo_checkbox.isChecked(), self.system_tray_icon_theme_combobox.currentData(Qt.UserRole) ) return settings
python
def _settings_str(self): """Returns a human readable settings representation for logging purposes.""" settings = "Automatically save changes: {}, " \ "Show tray icon: {}, " \ "Allow keyboard navigation: {}, " \ "Sort by usage count: {}, " \ "Enable undo using backspace: {}, " \ "Tray icon theme: {}".format( self.autosave_checkbox.isChecked(), self.show_tray_checkbox.isChecked(), self.allow_kb_nav_checkbox.isChecked(), self.sort_by_usage_checkbox.isChecked(), self.enable_undo_checkbox.isChecked(), self.system_tray_icon_theme_combobox.currentData(Qt.UserRole) ) return settings
[ "def", "_settings_str", "(", "self", ")", ":", "settings", "=", "\"Automatically save changes: {}, \"", "\"Show tray icon: {}, \"", "\"Allow keyboard navigation: {}, \"", "\"Sort by usage count: {}, \"", "\"Enable undo using backspace: {}, \"", "\"Tray icon theme: {}\"", ".", "format",...
Returns a human readable settings representation for logging purposes.
[ "Returns", "a", "human", "readable", "settings", "representation", "for", "logging", "purposes", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtui/settings/general.py#L72-L87
225,775
autokey/autokey
lib/autokey/model.py
AbstractAbbreviation._should_trigger_abbreviation
def _should_trigger_abbreviation(self, buffer): """ Checks whether, based on the settings for the abbreviation and the given input, the abbreviation should trigger. @param buffer Input buffer to be checked (as string) """ return any(self.__checkInput(buffer, abbr) for abbr in self.abbreviations)
python
def _should_trigger_abbreviation(self, buffer): """ Checks whether, based on the settings for the abbreviation and the given input, the abbreviation should trigger. @param buffer Input buffer to be checked (as string) """ return any(self.__checkInput(buffer, abbr) for abbr in self.abbreviations)
[ "def", "_should_trigger_abbreviation", "(", "self", ",", "buffer", ")", ":", "return", "any", "(", "self", ".", "__checkInput", "(", "buffer", ",", "abbr", ")", "for", "abbr", "in", "self", ".", "abbreviations", ")" ]
Checks whether, based on the settings for the abbreviation and the given input, the abbreviation should trigger. @param buffer Input buffer to be checked (as string)
[ "Checks", "whether", "based", "on", "the", "settings", "for", "the", "abbreviation", "and", "the", "given", "input", "the", "abbreviation", "should", "trigger", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/model.py#L175-L182
225,776
autokey/autokey
lib/autokey/model.py
AbstractWindowFilter.get_filter_regex
def get_filter_regex(self): """ Used by the GUI to obtain human-readable version of the filter """ if self.windowInfoRegex is not None: if self.isRecursive: return self.windowInfoRegex.pattern else: return self.windowInfoRegex.pattern elif self.parent is not None: return self.parent.get_child_filter() else: return ""
python
def get_filter_regex(self): """ Used by the GUI to obtain human-readable version of the filter """ if self.windowInfoRegex is not None: if self.isRecursive: return self.windowInfoRegex.pattern else: return self.windowInfoRegex.pattern elif self.parent is not None: return self.parent.get_child_filter() else: return ""
[ "def", "get_filter_regex", "(", "self", ")", ":", "if", "self", ".", "windowInfoRegex", "is", "not", "None", ":", "if", "self", ".", "isRecursive", ":", "return", "self", ".", "windowInfoRegex", ".", "pattern", "else", ":", "return", "self", ".", "windowIn...
Used by the GUI to obtain human-readable version of the filter
[ "Used", "by", "the", "GUI", "to", "obtain", "human", "-", "readable", "version", "of", "the", "filter" ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/model.py#L313-L325
225,777
autokey/autokey
lib/autokey/model.py
Folder.add_item
def add_item(self, item): """ Add a new script or phrase to the folder. """ item.parent = self #self.phrases[phrase.description] = phrase self.items.append(item)
python
def add_item(self, item): """ Add a new script or phrase to the folder. """ item.parent = self #self.phrases[phrase.description] = phrase self.items.append(item)
[ "def", "add_item", "(", "self", ",", "item", ")", ":", "item", ".", "parent", "=", "self", "#self.phrases[phrase.description] = phrase", "self", ".", "items", ".", "append", "(", "item", ")" ]
Add a new script or phrase to the folder.
[ "Add", "a", "new", "script", "or", "phrase", "to", "the", "folder", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/model.py#L546-L552
225,778
autokey/autokey
lib/autokey/model.py
Folder.get_backspace_count
def get_backspace_count(self, buffer): """ Given the input buffer, calculate how many backspaces are needed to erase the text that triggered this folder. """ if TriggerMode.ABBREVIATION in self.modes and self.backspace: if self._should_trigger_abbreviation(buffer): abbr = self._get_trigger_abbreviation(buffer) stringBefore, typedAbbr, stringAfter = self._partition_input(buffer, abbr) return len(abbr) + len(stringAfter) if self.parent is not None: return self.parent.get_backspace_count(buffer) return 0
python
def get_backspace_count(self, buffer): """ Given the input buffer, calculate how many backspaces are needed to erase the text that triggered this folder. """ if TriggerMode.ABBREVIATION in self.modes and self.backspace: if self._should_trigger_abbreviation(buffer): abbr = self._get_trigger_abbreviation(buffer) stringBefore, typedAbbr, stringAfter = self._partition_input(buffer, abbr) return len(abbr) + len(stringAfter) if self.parent is not None: return self.parent.get_backspace_count(buffer) return 0
[ "def", "get_backspace_count", "(", "self", ",", "buffer", ")", ":", "if", "TriggerMode", ".", "ABBREVIATION", "in", "self", ".", "modes", "and", "self", ".", "backspace", ":", "if", "self", ".", "_should_trigger_abbreviation", "(", "buffer", ")", ":", "abbr"...
Given the input buffer, calculate how many backspaces are needed to erase the text that triggered this folder.
[ "Given", "the", "input", "buffer", "calculate", "how", "many", "backspaces", "are", "needed", "to", "erase", "the", "text", "that", "triggered", "this", "folder", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/model.py#L572-L586
225,779
autokey/autokey
lib/autokey/model.py
Phrase.calculate_input
def calculate_input(self, buffer): """ Calculate how many keystrokes were used in triggering this phrase. """ # TODO: This function is unused? if TriggerMode.ABBREVIATION in self.modes: if self._should_trigger_abbreviation(buffer): if self.immediate: return len(self._get_trigger_abbreviation(buffer)) else: return len(self._get_trigger_abbreviation(buffer)) + 1 # TODO - re-enable me if restoring predictive functionality #if TriggerMode.PREDICTIVE in self.modes: # if self._should_trigger_predictive(buffer): # return ConfigManager.SETTINGS[PREDICTIVE_LENGTH] if TriggerMode.HOTKEY in self.modes: if buffer == '': return len(self.modifiers) + 1 return self.parent.calculate_input(buffer)
python
def calculate_input(self, buffer): """ Calculate how many keystrokes were used in triggering this phrase. """ # TODO: This function is unused? if TriggerMode.ABBREVIATION in self.modes: if self._should_trigger_abbreviation(buffer): if self.immediate: return len(self._get_trigger_abbreviation(buffer)) else: return len(self._get_trigger_abbreviation(buffer)) + 1 # TODO - re-enable me if restoring predictive functionality #if TriggerMode.PREDICTIVE in self.modes: # if self._should_trigger_predictive(buffer): # return ConfigManager.SETTINGS[PREDICTIVE_LENGTH] if TriggerMode.HOTKEY in self.modes: if buffer == '': return len(self.modifiers) + 1 return self.parent.calculate_input(buffer)
[ "def", "calculate_input", "(", "self", ",", "buffer", ")", ":", "# TODO: This function is unused?", "if", "TriggerMode", ".", "ABBREVIATION", "in", "self", ".", "modes", ":", "if", "self", ".", "_should_trigger_abbreviation", "(", "buffer", ")", ":", "if", "self...
Calculate how many keystrokes were used in triggering this phrase.
[ "Calculate", "how", "many", "keystrokes", "were", "used", "in", "triggering", "this", "phrase", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/model.py#L797-L818
225,780
autokey/autokey
lib/autokey/model.py
Script._persist_metadata
def _persist_metadata(self): """ Write all script meta-data, including the persistent script Store. The Store instance might contain arbitrary user data, like function objects, OpenCL contexts, or whatever other non-serializable objects, both as keys or values. Try to serialize the data, and if it fails, fall back to checking the store and removing all non-serializable data. """ serializable_data = self.get_serializable() try: self._try_persist_metadata(serializable_data) except TypeError: # The user added non-serializable data to the store, so skip all non-serializable keys or values. cleaned_data = Script._remove_non_serializable_store_entries(serializable_data["store"]) self._try_persist_metadata(cleaned_data)
python
def _persist_metadata(self): """ Write all script meta-data, including the persistent script Store. The Store instance might contain arbitrary user data, like function objects, OpenCL contexts, or whatever other non-serializable objects, both as keys or values. Try to serialize the data, and if it fails, fall back to checking the store and removing all non-serializable data. """ serializable_data = self.get_serializable() try: self._try_persist_metadata(serializable_data) except TypeError: # The user added non-serializable data to the store, so skip all non-serializable keys or values. cleaned_data = Script._remove_non_serializable_store_entries(serializable_data["store"]) self._try_persist_metadata(cleaned_data)
[ "def", "_persist_metadata", "(", "self", ")", ":", "serializable_data", "=", "self", ".", "get_serializable", "(", ")", "try", ":", "self", ".", "_try_persist_metadata", "(", "serializable_data", ")", "except", "TypeError", ":", "# The user added non-serializable data...
Write all script meta-data, including the persistent script Store. The Store instance might contain arbitrary user data, like function objects, OpenCL contexts, or whatever other non-serializable objects, both as keys or values. Try to serialize the data, and if it fails, fall back to checking the store and removing all non-serializable data.
[ "Write", "all", "script", "meta", "-", "data", "including", "the", "persistent", "script", "Store", ".", "The", "Store", "instance", "might", "contain", "arbitrary", "user", "data", "like", "function", "objects", "OpenCL", "contexts", "or", "whatever", "other", ...
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/model.py#L949-L963
225,781
autokey/autokey
lib/autokey/model.py
Script._remove_non_serializable_store_entries
def _remove_non_serializable_store_entries(store: Store) -> dict: """ Copy all serializable data into a new dict, and skip the rest. This makes sure to keep the items during runtime, even if the user edits and saves the script. """ cleaned_store_data = {} for key, value in store.items(): if Script._is_serializable(key) and Script._is_serializable(value): cleaned_store_data[key] = value else: _logger.info("Skip non-serializable item in the local script store. Key: '{}', Value: '{}'. " "This item cannot be saved and therefore will be lost when autokey quits.".format( key, value )) return cleaned_store_data
python
def _remove_non_serializable_store_entries(store: Store) -> dict: """ Copy all serializable data into a new dict, and skip the rest. This makes sure to keep the items during runtime, even if the user edits and saves the script. """ cleaned_store_data = {} for key, value in store.items(): if Script._is_serializable(key) and Script._is_serializable(value): cleaned_store_data[key] = value else: _logger.info("Skip non-serializable item in the local script store. Key: '{}', Value: '{}'. " "This item cannot be saved and therefore will be lost when autokey quits.".format( key, value )) return cleaned_store_data
[ "def", "_remove_non_serializable_store_entries", "(", "store", ":", "Store", ")", "->", "dict", ":", "cleaned_store_data", "=", "{", "}", "for", "key", ",", "value", "in", "store", ".", "items", "(", ")", ":", "if", "Script", ".", "_is_serializable", "(", ...
Copy all serializable data into a new dict, and skip the rest. This makes sure to keep the items during runtime, even if the user edits and saves the script.
[ "Copy", "all", "serializable", "data", "into", "a", "new", "dict", "and", "skip", "the", "rest", ".", "This", "makes", "sure", "to", "keep", "the", "items", "during", "runtime", "even", "if", "the", "user", "edits", "and", "saves", "the", "script", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/model.py#L970-L984
225,782
autokey/autokey
lib/autokey/qtapp.py
Application._configure_root_logger
def _configure_root_logger(self): """Initialise logging system""" root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG) if self.args.verbose: handler = logging.StreamHandler(sys.stdout) else: handler = logging.handlers.RotatingFileHandler( common.LOG_FILE, maxBytes=common.MAX_LOG_SIZE, backupCount=common.MAX_LOG_COUNT ) handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter(common.LOG_FORMAT)) root_logger.addHandler(handler)
python
def _configure_root_logger(self): """Initialise logging system""" root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG) if self.args.verbose: handler = logging.StreamHandler(sys.stdout) else: handler = logging.handlers.RotatingFileHandler( common.LOG_FILE, maxBytes=common.MAX_LOG_SIZE, backupCount=common.MAX_LOG_COUNT ) handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter(common.LOG_FORMAT)) root_logger.addHandler(handler)
[ "def", "_configure_root_logger", "(", "self", ")", ":", "root_logger", "=", "logging", ".", "getLogger", "(", ")", "root_logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "if", "self", ".", "args", ".", "verbose", ":", "handler", "=", "logging",...
Initialise logging system
[ "Initialise", "logging", "system" ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtapp.py#L165-L179
225,783
autokey/autokey
lib/autokey/qtapp.py
Application._create_storage_directories
def _create_storage_directories(): """Create various storage directories, if those do not exist.""" # Create configuration directory if not os.path.exists(common.CONFIG_DIR): os.makedirs(common.CONFIG_DIR) # Create data directory (for log file) if not os.path.exists(common.DATA_DIR): os.makedirs(common.DATA_DIR) # Create run directory (for lock file) if not os.path.exists(common.RUN_DIR): os.makedirs(common.RUN_DIR)
python
def _create_storage_directories(): """Create various storage directories, if those do not exist.""" # Create configuration directory if not os.path.exists(common.CONFIG_DIR): os.makedirs(common.CONFIG_DIR) # Create data directory (for log file) if not os.path.exists(common.DATA_DIR): os.makedirs(common.DATA_DIR) # Create run directory (for lock file) if not os.path.exists(common.RUN_DIR): os.makedirs(common.RUN_DIR)
[ "def", "_create_storage_directories", "(", ")", ":", "# Create configuration directory", "if", "not", "os", ".", "path", ".", "exists", "(", "common", ".", "CONFIG_DIR", ")", ":", "os", ".", "makedirs", "(", "common", ".", "CONFIG_DIR", ")", "# Create data direc...
Create various storage directories, if those do not exist.
[ "Create", "various", "storage", "directories", "if", "those", "do", "not", "exist", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtapp.py#L182-L192
225,784
autokey/autokey
lib/autokey/qtapp.py
Application.toggle_service
def toggle_service(self): """ Convenience method for toggling the expansion service on or off. This is called by the global hotkey. """ self.monitoring_disabled.emit(not self.service.is_running()) if self.service.is_running(): self.pause_service() else: self.unpause_service()
python
def toggle_service(self): """ Convenience method for toggling the expansion service on or off. This is called by the global hotkey. """ self.monitoring_disabled.emit(not self.service.is_running()) if self.service.is_running(): self.pause_service() else: self.unpause_service()
[ "def", "toggle_service", "(", "self", ")", ":", "self", ".", "monitoring_disabled", ".", "emit", "(", "not", "self", ".", "service", ".", "is_running", "(", ")", ")", "if", "self", ".", "service", ".", "is_running", "(", ")", ":", "self", ".", "pause_s...
Convenience method for toggling the expansion service on or off. This is called by the global hotkey.
[ "Convenience", "method", "for", "toggling", "the", "expansion", "service", "on", "or", "off", ".", "This", "is", "called", "by", "the", "global", "hotkey", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtapp.py#L271-L279
225,785
autokey/autokey
lib/autokey/qtui/notifier.py
Notifier.create_assign_context_menu
def create_assign_context_menu(self): """ Create a context menu, then set the created QMenu as the context menu. This builds the menu with all required actions and signal-slot connections. """ menu = QMenu("AutoKey") self._build_menu(menu) self.setContextMenu(menu)
python
def create_assign_context_menu(self): """ Create a context menu, then set the created QMenu as the context menu. This builds the menu with all required actions and signal-slot connections. """ menu = QMenu("AutoKey") self._build_menu(menu) self.setContextMenu(menu)
[ "def", "create_assign_context_menu", "(", "self", ")", ":", "menu", "=", "QMenu", "(", "\"AutoKey\"", ")", "self", ".", "_build_menu", "(", "menu", ")", "self", ".", "setContextMenu", "(", "menu", ")" ]
Create a context menu, then set the created QMenu as the context menu. This builds the menu with all required actions and signal-slot connections.
[ "Create", "a", "context", "menu", "then", "set", "the", "created", "QMenu", "as", "the", "context", "menu", ".", "This", "builds", "the", "menu", "with", "all", "required", "actions", "and", "signal", "-", "slot", "connections", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtui/notifier.py#L62-L69
225,786
autokey/autokey
lib/autokey/qtui/notifier.py
Notifier.update_tool_tip
def update_tool_tip(self, service_running: bool): """Slot function that updates the tooltip when the user activates or deactivates the expansion service.""" if service_running: self.setToolTip(TOOLTIP_RUNNING) else: self.setToolTip(TOOLTIP_PAUSED)
python
def update_tool_tip(self, service_running: bool): """Slot function that updates the tooltip when the user activates or deactivates the expansion service.""" if service_running: self.setToolTip(TOOLTIP_RUNNING) else: self.setToolTip(TOOLTIP_PAUSED)
[ "def", "update_tool_tip", "(", "self", ",", "service_running", ":", "bool", ")", ":", "if", "service_running", ":", "self", ".", "setToolTip", "(", "TOOLTIP_RUNNING", ")", "else", ":", "self", ".", "setToolTip", "(", "TOOLTIP_PAUSED", ")" ]
Slot function that updates the tooltip when the user activates or deactivates the expansion service.
[ "Slot", "function", "that", "updates", "the", "tooltip", "when", "the", "user", "activates", "or", "deactivates", "the", "expansion", "service", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtui/notifier.py#L71-L76
225,787
autokey/autokey
lib/autokey/qtui/notifier.py
Notifier._create_action
def _create_action( self, icon_name: Optional[str], title: str, slot_function: Callable[[None], None], tool_tip: Optional[str]=None)-> QAction: """ QAction factory. All items created belong to the calling instance, i.e. created QAction parent is self. """ action = QAction(title, self) if icon_name: action.setIcon(QIcon.fromTheme(icon_name)) action.triggered.connect(slot_function) if tool_tip: action.setToolTip(tool_tip) return action
python
def _create_action( self, icon_name: Optional[str], title: str, slot_function: Callable[[None], None], tool_tip: Optional[str]=None)-> QAction: """ QAction factory. All items created belong to the calling instance, i.e. created QAction parent is self. """ action = QAction(title, self) if icon_name: action.setIcon(QIcon.fromTheme(icon_name)) action.triggered.connect(slot_function) if tool_tip: action.setToolTip(tool_tip) return action
[ "def", "_create_action", "(", "self", ",", "icon_name", ":", "Optional", "[", "str", "]", ",", "title", ":", "str", ",", "slot_function", ":", "Callable", "[", "[", "None", "]", ",", "None", "]", ",", "tool_tip", ":", "Optional", "[", "str", "]", "="...
QAction factory. All items created belong to the calling instance, i.e. created QAction parent is self.
[ "QAction", "factory", ".", "All", "items", "created", "belong", "to", "the", "calling", "instance", "i", ".", "e", ".", "created", "QAction", "parent", "is", "self", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtui/notifier.py#L92-L107
225,788
autokey/autokey
lib/autokey/qtui/notifier.py
Notifier._create_static_actions
def _create_static_actions(self): """ Create all static menu actions. The created actions will be placed in the tray icon context menu. """ logger.info("Creating static context menu actions.") self.action_view_script_error = self._create_action( None, "&View script error", self.reset_tray_icon, "View the last script error." ) self.action_view_script_error.triggered.connect(self.app.show_script_error) # The action should disable itself self.action_view_script_error.setDisabled(True) self.action_view_script_error.triggered.connect(self.action_view_script_error.setEnabled) self.action_hide_icon = self._create_action( "edit-clear", "Temporarily &Hide Icon", self.hide, "Temporarily hide the system tray icon.\nUse the settings to hide it permanently." ) self.action_show_config_window = self._create_action( "configure", "&Show Main Window", self.app.show_configure, "Show the main AutoKey window. This does the same as left clicking the tray icon." ) self.action_quit = self._create_action("application-exit", "Exit AutoKey", self.app.shutdown) # TODO: maybe import this from configwindow.py ? The exact same Action is defined in the main window. self.action_enable_monitoring = self._create_action( None, "&Enable Monitoring", self.app.toggle_service, "Pause the phrase expansion and script execution, both by abbreviations and hotkeys.\n" "The global hotkeys to show the main window and to toggle this setting, as defined in the AutoKey " "settings, are not affected and will work regardless." ) self.action_enable_monitoring.setCheckable(True) self.action_enable_monitoring.setChecked(self.app.service.is_running()) self.action_enable_monitoring.setDisabled(self.app.serviceDisabled) # Sync action state with internal service state self.app.monitoring_disabled.connect(self.action_enable_monitoring.setChecked)
python
def _create_static_actions(self): """ Create all static menu actions. The created actions will be placed in the tray icon context menu. """ logger.info("Creating static context menu actions.") self.action_view_script_error = self._create_action( None, "&View script error", self.reset_tray_icon, "View the last script error." ) self.action_view_script_error.triggered.connect(self.app.show_script_error) # The action should disable itself self.action_view_script_error.setDisabled(True) self.action_view_script_error.triggered.connect(self.action_view_script_error.setEnabled) self.action_hide_icon = self._create_action( "edit-clear", "Temporarily &Hide Icon", self.hide, "Temporarily hide the system tray icon.\nUse the settings to hide it permanently." ) self.action_show_config_window = self._create_action( "configure", "&Show Main Window", self.app.show_configure, "Show the main AutoKey window. This does the same as left clicking the tray icon." ) self.action_quit = self._create_action("application-exit", "Exit AutoKey", self.app.shutdown) # TODO: maybe import this from configwindow.py ? The exact same Action is defined in the main window. self.action_enable_monitoring = self._create_action( None, "&Enable Monitoring", self.app.toggle_service, "Pause the phrase expansion and script execution, both by abbreviations and hotkeys.\n" "The global hotkeys to show the main window and to toggle this setting, as defined in the AutoKey " "settings, are not affected and will work regardless." ) self.action_enable_monitoring.setCheckable(True) self.action_enable_monitoring.setChecked(self.app.service.is_running()) self.action_enable_monitoring.setDisabled(self.app.serviceDisabled) # Sync action state with internal service state self.app.monitoring_disabled.connect(self.action_enable_monitoring.setChecked)
[ "def", "_create_static_actions", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Creating static context menu actions.\"", ")", "self", ".", "action_view_script_error", "=", "self", ".", "_create_action", "(", "None", ",", "\"&View script error\"", ",", "self", ...
Create all static menu actions. The created actions will be placed in the tray icon context menu.
[ "Create", "all", "static", "menu", "actions", ".", "The", "created", "actions", "will", "be", "placed", "in", "the", "tray", "icon", "context", "menu", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtui/notifier.py#L109-L142
225,789
autokey/autokey
lib/autokey/qtui/notifier.py
Notifier._fill_context_menu_with_model_item_actions
def _fill_context_menu_with_model_item_actions(self, context_menu: QMenu): """ Find all model items that should be available in the context menu and create QActions for each, by using the available logic in popupmenu.PopupMenu. """ # Get phrase folders to add to main menu logger.info("Rebuilding model item actions, adding all items marked for access through the tray icon.") folders = [folder for folder in self.config_manager.allFolders if folder.show_in_tray_menu] items = [item for item in self.config_manager.allItems if item.show_in_tray_menu] # Only extract the QActions, but discard the PopupMenu instance. # This is done, because the PopupMenu class is not directly usable as a context menu here. menu = popupmenu.PopupMenu(self.app.service, folders, items, False, "AutoKey") new_item_actions = menu.actions() context_menu.addActions(new_item_actions) for action in new_item_actions: # type: QAction # QMenu does not take the ownership when adding QActions, so manually re-parent all actions. # This causes the QActions to be destroyed when the context menu is cleared or re-created. action.setParent(context_menu) if not context_menu.isEmpty(): # Avoid a stray separator line, if no items are marked for display in the context menu. context_menu.addSeparator()
python
def _fill_context_menu_with_model_item_actions(self, context_menu: QMenu): """ Find all model items that should be available in the context menu and create QActions for each, by using the available logic in popupmenu.PopupMenu. """ # Get phrase folders to add to main menu logger.info("Rebuilding model item actions, adding all items marked for access through the tray icon.") folders = [folder for folder in self.config_manager.allFolders if folder.show_in_tray_menu] items = [item for item in self.config_manager.allItems if item.show_in_tray_menu] # Only extract the QActions, but discard the PopupMenu instance. # This is done, because the PopupMenu class is not directly usable as a context menu here. menu = popupmenu.PopupMenu(self.app.service, folders, items, False, "AutoKey") new_item_actions = menu.actions() context_menu.addActions(new_item_actions) for action in new_item_actions: # type: QAction # QMenu does not take the ownership when adding QActions, so manually re-parent all actions. # This causes the QActions to be destroyed when the context menu is cleared or re-created. action.setParent(context_menu) if not context_menu.isEmpty(): # Avoid a stray separator line, if no items are marked for display in the context menu. context_menu.addSeparator()
[ "def", "_fill_context_menu_with_model_item_actions", "(", "self", ",", "context_menu", ":", "QMenu", ")", ":", "# Get phrase folders to add to main menu", "logger", ".", "info", "(", "\"Rebuilding model item actions, adding all items marked for access through the tray icon.\"", ")", ...
Find all model items that should be available in the context menu and create QActions for each, by using the available logic in popupmenu.PopupMenu.
[ "Find", "all", "model", "items", "that", "should", "be", "available", "in", "the", "context", "menu", "and", "create", "QActions", "for", "each", "by", "using", "the", "available", "logic", "in", "popupmenu", ".", "PopupMenu", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtui/notifier.py#L144-L165
225,790
autokey/autokey
lib/autokey/qtui/notifier.py
Notifier._build_menu
def _build_menu(self, context_menu: QMenu): """Build the context menu.""" logger.debug("Show tray icon enabled in settings: {}".format(cm.ConfigManager.SETTINGS[cm.SHOW_TRAY_ICON])) # Items selected for display are shown on top self._fill_context_menu_with_model_item_actions(context_menu) # The static actions are added at the bottom context_menu.addAction(self.action_view_script_error) context_menu.addAction(self.action_enable_monitoring) context_menu.addAction(self.action_hide_icon) context_menu.addAction(self.action_show_config_window) context_menu.addAction(self.action_quit)
python
def _build_menu(self, context_menu: QMenu): """Build the context menu.""" logger.debug("Show tray icon enabled in settings: {}".format(cm.ConfigManager.SETTINGS[cm.SHOW_TRAY_ICON])) # Items selected for display are shown on top self._fill_context_menu_with_model_item_actions(context_menu) # The static actions are added at the bottom context_menu.addAction(self.action_view_script_error) context_menu.addAction(self.action_enable_monitoring) context_menu.addAction(self.action_hide_icon) context_menu.addAction(self.action_show_config_window) context_menu.addAction(self.action_quit)
[ "def", "_build_menu", "(", "self", ",", "context_menu", ":", "QMenu", ")", ":", "logger", ".", "debug", "(", "\"Show tray icon enabled in settings: {}\"", ".", "format", "(", "cm", ".", "ConfigManager", ".", "SETTINGS", "[", "cm", ".", "SHOW_TRAY_ICON", "]", "...
Build the context menu.
[ "Build", "the", "context", "menu", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtui/notifier.py#L167-L177
225,791
autokey/autokey
lib/autokey/configmanager.py
_persist_settings
def _persist_settings(config_manager): """ Write the settings, including the persistent global script Store. The Store instance might contain arbitrary user data, like function objects, OpenCL contexts, or whatever other non-serializable objects, both as keys or values. Try to serialize the data, and if it fails, fall back to checking the store and removing all non-serializable data. """ serializable_data = config_manager.get_serializable() try: _try_persist_settings(serializable_data) except (TypeError, ValueError): # The user added non-serializable data to the store, so remove all non-serializable keys or values. _remove_non_serializable_store_entries(serializable_data["settings"][SCRIPT_GLOBALS]) _try_persist_settings(serializable_data)
python
def _persist_settings(config_manager): """ Write the settings, including the persistent global script Store. The Store instance might contain arbitrary user data, like function objects, OpenCL contexts, or whatever other non-serializable objects, both as keys or values. Try to serialize the data, and if it fails, fall back to checking the store and removing all non-serializable data. """ serializable_data = config_manager.get_serializable() try: _try_persist_settings(serializable_data) except (TypeError, ValueError): # The user added non-serializable data to the store, so remove all non-serializable keys or values. _remove_non_serializable_store_entries(serializable_data["settings"][SCRIPT_GLOBALS]) _try_persist_settings(serializable_data)
[ "def", "_persist_settings", "(", "config_manager", ")", ":", "serializable_data", "=", "config_manager", ".", "get_serializable", "(", ")", "try", ":", "_try_persist_settings", "(", "serializable_data", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", ...
Write the settings, including the persistent global script Store. The Store instance might contain arbitrary user data, like function objects, OpenCL contexts, or whatever other non-serializable objects, both as keys or values. Try to serialize the data, and if it fails, fall back to checking the store and removing all non-serializable data.
[ "Write", "the", "settings", "including", "the", "persistent", "global", "script", "Store", ".", "The", "Store", "instance", "might", "contain", "arbitrary", "user", "data", "like", "function", "objects", "OpenCL", "contexts", "or", "whatever", "other", "non", "-...
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/configmanager.py#L118-L132
225,792
autokey/autokey
lib/autokey/configmanager.py
_remove_non_serializable_store_entries
def _remove_non_serializable_store_entries(store: dict): """ This function is called if there are non-serializable items in the global script storage. This function removes all such items. """ removed_key_list = [] for key, value in store.items(): if not (_is_serializable(key) and _is_serializable(value)): _logger.info("Remove non-serializable item from the global script store. Key: '{}', Value: '{}'. " "This item cannot be saved and therefore will be lost.".format(key, value)) removed_key_list.append(key) for key in removed_key_list: del store[key]
python
def _remove_non_serializable_store_entries(store: dict): """ This function is called if there are non-serializable items in the global script storage. This function removes all such items. """ removed_key_list = [] for key, value in store.items(): if not (_is_serializable(key) and _is_serializable(value)): _logger.info("Remove non-serializable item from the global script store. Key: '{}', Value: '{}'. " "This item cannot be saved and therefore will be lost.".format(key, value)) removed_key_list.append(key) for key in removed_key_list: del store[key]
[ "def", "_remove_non_serializable_store_entries", "(", "store", ":", "dict", ")", ":", "removed_key_list", "=", "[", "]", "for", "key", ",", "value", "in", "store", ".", "items", "(", ")", ":", "if", "not", "(", "_is_serializable", "(", "key", ")", "and", ...
This function is called if there are non-serializable items in the global script storage. This function removes all such items.
[ "This", "function", "is", "called", "if", "there", "are", "non", "-", "serializable", "items", "in", "the", "global", "script", "storage", ".", "This", "function", "removes", "all", "such", "items", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/configmanager.py#L145-L157
225,793
autokey/autokey
lib/autokey/configmanager.py
get_autostart
def get_autostart() -> AutostartSettings: """Returns the autostart settings as read from the system.""" autostart_file = Path(common.AUTOSTART_DIR) / "autokey.desktop" if not autostart_file.exists(): return AutostartSettings(None, False) else: return _extract_data_from_desktop_file(autostart_file)
python
def get_autostart() -> AutostartSettings: """Returns the autostart settings as read from the system.""" autostart_file = Path(common.AUTOSTART_DIR) / "autokey.desktop" if not autostart_file.exists(): return AutostartSettings(None, False) else: return _extract_data_from_desktop_file(autostart_file)
[ "def", "get_autostart", "(", ")", "->", "AutostartSettings", ":", "autostart_file", "=", "Path", "(", "common", ".", "AUTOSTART_DIR", ")", "/", "\"autokey.desktop\"", "if", "not", "autostart_file", ".", "exists", "(", ")", ":", "return", "AutostartSettings", "("...
Returns the autostart settings as read from the system.
[ "Returns", "the", "autostart", "settings", "as", "read", "from", "the", "system", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/configmanager.py#L172-L178
225,794
autokey/autokey
lib/autokey/configmanager.py
_create_autostart_entry
def _create_autostart_entry(autostart_data: AutostartSettings, autostart_file: Path): """Create an autostart .desktop file in the autostart directory, if possible.""" try: source_desktop_file = get_source_desktop_file(autostart_data.desktop_file_name) except FileNotFoundError: _logger.exception("Failed to find a usable .desktop file! Unable to find: {}".format( autostart_data.desktop_file_name)) else: _logger.debug("Found source desktop file that will be placed into the autostart directory: {}".format( source_desktop_file)) with open(str(source_desktop_file), "r") as opened_source_desktop_file: desktop_file_content = opened_source_desktop_file.read() desktop_file_content = "\n".join(_manage_autostart_desktop_file_launch_flags( desktop_file_content, autostart_data.switch_show_configure )) + "\n" with open(str(autostart_file), "w", encoding="UTF-8") as opened_autostart_file: opened_autostart_file.write(desktop_file_content) _logger.debug("Written desktop file: {}".format(autostart_file))
python
def _create_autostart_entry(autostart_data: AutostartSettings, autostart_file: Path): """Create an autostart .desktop file in the autostart directory, if possible.""" try: source_desktop_file = get_source_desktop_file(autostart_data.desktop_file_name) except FileNotFoundError: _logger.exception("Failed to find a usable .desktop file! Unable to find: {}".format( autostart_data.desktop_file_name)) else: _logger.debug("Found source desktop file that will be placed into the autostart directory: {}".format( source_desktop_file)) with open(str(source_desktop_file), "r") as opened_source_desktop_file: desktop_file_content = opened_source_desktop_file.read() desktop_file_content = "\n".join(_manage_autostart_desktop_file_launch_flags( desktop_file_content, autostart_data.switch_show_configure )) + "\n" with open(str(autostart_file), "w", encoding="UTF-8") as opened_autostart_file: opened_autostart_file.write(desktop_file_content) _logger.debug("Written desktop file: {}".format(autostart_file))
[ "def", "_create_autostart_entry", "(", "autostart_data", ":", "AutostartSettings", ",", "autostart_file", ":", "Path", ")", ":", "try", ":", "source_desktop_file", "=", "get_source_desktop_file", "(", "autostart_data", ".", "desktop_file_name", ")", "except", "FileNotFo...
Create an autostart .desktop file in the autostart directory, if possible.
[ "Create", "an", "autostart", ".", "desktop", "file", "in", "the", "autostart", "directory", "if", "possible", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/configmanager.py#L205-L222
225,795
autokey/autokey
lib/autokey/configmanager.py
delete_autostart_entry
def delete_autostart_entry(): """Remove a present autostart entry. If none is found, nothing happens.""" autostart_file = Path(common.AUTOSTART_DIR) / "autokey.desktop" if autostart_file.exists(): autostart_file.unlink() _logger.info("Deleted old autostart entry: {}".format(autostart_file))
python
def delete_autostart_entry(): """Remove a present autostart entry. If none is found, nothing happens.""" autostart_file = Path(common.AUTOSTART_DIR) / "autokey.desktop" if autostart_file.exists(): autostart_file.unlink() _logger.info("Deleted old autostart entry: {}".format(autostart_file))
[ "def", "delete_autostart_entry", "(", ")", ":", "autostart_file", "=", "Path", "(", "common", ".", "AUTOSTART_DIR", ")", "/", "\"autokey.desktop\"", "if", "autostart_file", ".", "exists", "(", ")", ":", "autostart_file", ".", "unlink", "(", ")", "_logger", "."...
Remove a present autostart entry. If none is found, nothing happens.
[ "Remove", "a", "present", "autostart", "entry", ".", "If", "none", "is", "found", "nothing", "happens", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/configmanager.py#L225-L230
225,796
autokey/autokey
lib/autokey/configmanager.py
apply_settings
def apply_settings(settings): """ Allows new settings to be added without users having to lose all their configuration """ for key, value in settings.items(): ConfigManager.SETTINGS[key] = value
python
def apply_settings(settings): """ Allows new settings to be added without users having to lose all their configuration """ for key, value in settings.items(): ConfigManager.SETTINGS[key] = value
[ "def", "apply_settings", "(", "settings", ")", ":", "for", "key", ",", "value", "in", "settings", ".", "items", "(", ")", ":", "ConfigManager", ".", "SETTINGS", "[", "key", "]", "=", "value" ]
Allows new settings to be added without users having to lose all their configuration
[ "Allows", "new", "settings", "to", "be", "added", "without", "users", "having", "to", "lose", "all", "their", "configuration" ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/configmanager.py#L278-L283
225,797
autokey/autokey
lib/autokey/configmanager.py
ConfigManager.check_abbreviation_unique
def check_abbreviation_unique(self, abbreviation, newFilterPattern, targetItem): """ Checks that the given abbreviation is not already in use. @param abbreviation: the abbreviation to check @param newFilterPattern: @param targetItem: the phrase for which the abbreviation to be used """ for item in self.allFolders: if model.TriggerMode.ABBREVIATION in item.modes: if abbreviation in item.abbreviations and item.filter_matches(newFilterPattern): return item is targetItem, item for item in self.allItems: if model.TriggerMode.ABBREVIATION in item.modes: if abbreviation in item.abbreviations and item.filter_matches(newFilterPattern): return item is targetItem, item return True, None
python
def check_abbreviation_unique(self, abbreviation, newFilterPattern, targetItem): """ Checks that the given abbreviation is not already in use. @param abbreviation: the abbreviation to check @param newFilterPattern: @param targetItem: the phrase for which the abbreviation to be used """ for item in self.allFolders: if model.TriggerMode.ABBREVIATION in item.modes: if abbreviation in item.abbreviations and item.filter_matches(newFilterPattern): return item is targetItem, item for item in self.allItems: if model.TriggerMode.ABBREVIATION in item.modes: if abbreviation in item.abbreviations and item.filter_matches(newFilterPattern): return item is targetItem, item return True, None
[ "def", "check_abbreviation_unique", "(", "self", ",", "abbreviation", ",", "newFilterPattern", ",", "targetItem", ")", ":", "for", "item", "in", "self", ".", "allFolders", ":", "if", "model", ".", "TriggerMode", ".", "ABBREVIATION", "in", "item", ".", "modes",...
Checks that the given abbreviation is not already in use. @param abbreviation: the abbreviation to check @param newFilterPattern: @param targetItem: the phrase for which the abbreviation to be used
[ "Checks", "that", "the", "given", "abbreviation", "is", "not", "already", "in", "use", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/configmanager.py#L837-L855
225,798
autokey/autokey
lib/autokey/configmanager.py
ConfigManager.check_hotkey_unique
def check_hotkey_unique(self, modifiers, hotKey, newFilterPattern, targetItem): """ Checks that the given hotkey is not already in use. Also checks the special hotkeys configured from the advanced settings dialog. @param modifiers: modifiers for the hotkey @param hotKey: the hotkey to check @param newFilterPattern: @param targetItem: the phrase for which the hotKey to be used """ for item in self.allFolders: if model.TriggerMode.HOTKEY in item.modes: if item.modifiers == modifiers and item.hotKey == hotKey and item.filter_matches(newFilterPattern): return item is targetItem, item for item in self.allItems: if model.TriggerMode.HOTKEY in item.modes: if item.modifiers == modifiers and item.hotKey == hotKey and item.filter_matches(newFilterPattern): return item is targetItem, item for item in self.globalHotkeys: if item.enabled: if item.modifiers == modifiers and item.hotKey == hotKey and item.filter_matches(newFilterPattern): return item is targetItem, item return True, None
python
def check_hotkey_unique(self, modifiers, hotKey, newFilterPattern, targetItem): """ Checks that the given hotkey is not already in use. Also checks the special hotkeys configured from the advanced settings dialog. @param modifiers: modifiers for the hotkey @param hotKey: the hotkey to check @param newFilterPattern: @param targetItem: the phrase for which the hotKey to be used """ for item in self.allFolders: if model.TriggerMode.HOTKEY in item.modes: if item.modifiers == modifiers and item.hotKey == hotKey and item.filter_matches(newFilterPattern): return item is targetItem, item for item in self.allItems: if model.TriggerMode.HOTKEY in item.modes: if item.modifiers == modifiers and item.hotKey == hotKey and item.filter_matches(newFilterPattern): return item is targetItem, item for item in self.globalHotkeys: if item.enabled: if item.modifiers == modifiers and item.hotKey == hotKey and item.filter_matches(newFilterPattern): return item is targetItem, item return True, None
[ "def", "check_hotkey_unique", "(", "self", ",", "modifiers", ",", "hotKey", ",", "newFilterPattern", ",", "targetItem", ")", ":", "for", "item", "in", "self", ".", "allFolders", ":", "if", "model", ".", "TriggerMode", ".", "HOTKEY", "in", "item", ".", "mod...
Checks that the given hotkey is not already in use. Also checks the special hotkeys configured from the advanced settings dialog. @param modifiers: modifiers for the hotkey @param hotKey: the hotkey to check @param newFilterPattern: @param targetItem: the phrase for which the hotKey to be used
[ "Checks", "that", "the", "given", "hotkey", "is", "not", "already", "in", "use", ".", "Also", "checks", "the", "special", "hotkeys", "configured", "from", "the", "advanced", "settings", "dialog", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/configmanager.py#L888-L913
225,799
autokey/autokey
lib/autokey/qtui/dialogs/hotkeysettings.py
HotkeySettingsDialog.on_setButton_pressed
def on_setButton_pressed(self): """ Start recording a key combination when the user clicks on the setButton. The button itself is automatically disabled during the recording process. """ self.keyLabel.setText("Press a key or combination...") # TODO: i18n logger.debug("User starts to record a key combination.") self.grabber = iomediator.KeyGrabber(self) self.grabber.start()
python
def on_setButton_pressed(self): """ Start recording a key combination when the user clicks on the setButton. The button itself is automatically disabled during the recording process. """ self.keyLabel.setText("Press a key or combination...") # TODO: i18n logger.debug("User starts to record a key combination.") self.grabber = iomediator.KeyGrabber(self) self.grabber.start()
[ "def", "on_setButton_pressed", "(", "self", ")", ":", "self", ".", "keyLabel", ".", "setText", "(", "\"Press a key or combination...\"", ")", "# TODO: i18n", "logger", ".", "debug", "(", "\"User starts to record a key combination.\"", ")", "self", ".", "grabber", "=",...
Start recording a key combination when the user clicks on the setButton. The button itself is automatically disabled during the recording process.
[ "Start", "recording", "a", "key", "combination", "when", "the", "user", "clicks", "on", "the", "setButton", ".", "The", "button", "itself", "is", "automatically", "disabled", "during", "the", "recording", "process", "." ]
35decb72f286ce68cd2a1f09ace8891a520b58d1
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtui/dialogs/hotkeysettings.py#L68-L76