desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Returns the package metadata for an installed package
:param package:
The name of the package
:param is_dependency:
If the metadata is for a dependency
:return:
A dict with the keys:
version
url
description
or an empty dict on error'
| def get_metadata(self, package, is_dependency=False):
| metadata_filename = 'package-metadata.json'
if is_dependency:
metadata_filename = 'dependency-metadata.json'
if package_file_exists(package, metadata_filename):
metadata_json = read_package_file(package, metadata_filename)
if metadata_json:
try:
return jso... |
'Returns a list of dependencies for the specified package on the
current machine
:param package:
The name of the package
:return:
A list of dependency names'
| def get_dependencies(self, package):
| if package_file_exists(package, 'dependencies.json'):
dep_info_json = read_package_file(package, 'dependencies.json')
if dep_info_json:
try:
return self.select_dependencies(json.loads(dep_info_json))
except ValueError:
console_write(u'\n ... |
'Returns the priority and loader code for a dependency that is already
on disk.
This is primarily only useful when a package author has a
dependency they are developing locally and Package Control needs to
know how to set up a loader for it.
:param dependency:
A unicode string of the dependency to get the info for
:ret... | def get_dependency_priority_code(self, dependency):
| dependency_path = self.get_package_dir(dependency)
if (not os.path.exists(dependency_path)):
return (None, None)
dependencies = self.list_available_dependencies()
hidden_file_path = os.path.join(dependency_path, '.sublime-dependency')
loader_py_path = os.path.join(dependency_path, 'loader.py... |
':param package:
The package name
:return:
If the package is installed via git'
| def _is_git_package(self, package):
| git_dir = os.path.join(self.get_package_dir(package), '.git')
return (os.path.exists(git_dir) and (os.path.isdir(git_dir) or os.path.isfile(git_dir)))
|
':param package:
The package name
:return:
If the package is installed via hg'
| def _is_hg_package(self, package):
| hg_dir = os.path.join(self.get_package_dir(package), '.hg')
return (os.path.exists(hg_dir) and os.path.isdir(hg_dir))
|
'If the package is installed via git or hg
:param package:
The package to check
:return:
bool'
| def is_vcs_package(self, package):
| return (self._is_git_package(package) or self._is_hg_package(package))
|
'Determines the current version for a package
:param package:
The package name'
| def get_version(self, package):
| version = self.get_metadata(package).get('version')
if version:
return version
if self.is_vcs_package(package):
upgrader = self.instantiate_upgrader(package)
version = upgrader.latest_commit()
if version:
return ('%s commit %s' % (upgrader.cli_name, version)... |
'Creates an HgUpgrader or GitUpgrader object to run operations on a VCS-
based package
:param package:
The name of the package
:return:
GitUpgrader, HgUpgrader or None'
| def instantiate_upgrader(self, package):
| if self._is_git_package(package):
return GitUpgrader(self.settings['git_binary'], self.settings['git_update_command'], self.get_package_dir(package), self.settings['cache_length'], self.settings['debug'])
if self._is_hg_package(package):
return HgUpgrader(self.settings['hg_binary'], self.setting... |
'Takes the a dict from a dependencies.json file and returns the
dependency names that are applicable to the current machine
:param dependency_info:
A dict from a dependencies.json file
:return:
A list of dependency names'
| def select_dependencies(self, dependency_info):
| platform_selectors = [((self.settings['platform'] + '-') + self.settings['arch']), self.settings['platform'], '*']
for platform_selector in platform_selectors:
if (platform_selector not in dependency_info):
continue
platform_dependency = dependency_info[platform_selector]
ver... |
'Returns a master list of all repositories pulled from all sources
These repositories come from the channels specified in the
"channels" setting, plus any repositories listed in the
"repositories" setting.
:return:
A list of all available repositories'
| def list_repositories(self):
| cache_ttl = self.settings.get('cache_length')
repositories = self.settings.get('repositories')[:]
channels = self.settings.get('channels')
updated_channels = []
found_default = False
for channel in channels:
if re.match('https?://([^.]+\\.)*package-control.io', channel):
cons... |
'Returns a master list of every available package and dependency from all sources
:return:
A 2-element tuple, in the format:
\'Package Name\': {
# Package details - see example-repository.json for format
\'Dependency Name\': {
# Dependency details - see example-repository.json for format'
| def _list_available(self):
| if self.settings.get('debug'):
console_write(u'\n Fetching list of available packages and dependencies\n Platform: %s-%s\n ... |
'Returns a master list of every available dependency from all sources
:return:
A dict in the format:
\'Dependency Name\': {
# Dependency details - see example-repository.json for format'
| def list_available_dependencies(self):
| return self._list_available()[1]
|
'Returns a master list of every available package from all sources
:return:
A dict in the format:
\'Package Name\': {
# Package details - see example-repository.json for format'
| def list_available_packages(self):
| return self._list_available()[0]
|
':param unpacked_only:
Only list packages that are not inside of .sublime-package files
:return: A list of all installed, non-default, non-dependency, package names'
| def list_packages(self, unpacked_only=False):
| packages = self._list_visible_dirs(self.settings['packages_path'])
if ((self.settings['version'] > 3000) and (unpacked_only is False)):
packages |= self._list_sublime_package_files(self.settings['installed_packages_path'])
packages -= set(self.list_default_packages())
packages -= set(self.list_d... |
':return: A list of all installed dependency names'
| def list_dependencies(self):
| output = []
if (sys.version_info >= (3,)):
output.append('0_package_control_loader')
for name in self._list_visible_dirs(self.settings['packages_path']):
if (not self._is_dependency(name)):
continue
output.append(name)
return sorted(output, key=(lambda s: s.lower()))
|
':return:
A list of the names of dependencies in the Packages/ folder that
are not currently being loaded'
| def list_unloaded_dependencies(self):
| output = []
for name in self._list_visible_dirs(self.settings['packages_path']):
hidden_file_path = os.path.join(self.settings['packages_path'], name, '.sublime-dependency')
if (not os.path.exists(hidden_file_path)):
continue
if (not loader.exists(name)):
output.a... |
'Lists all packages on the machine
:return:
A list of all installed package names, including default packages'
| def list_all_packages(self):
| packages = (self.list_default_packages() + self.list_packages())
return sorted(packages, key=(lambda s: s.lower()))
|
':return: A list of all default package names'
| def list_default_packages(self):
| if (self.settings['version'] > 3000):
app_dir = os.path.dirname(sublime.executable_path())
packages = self._list_sublime_package_files(os.path.join(app_dir, 'Packages'))
else:
config_dir = os.path.dirname(self.settings['packages_path'])
pristine_dir = os.path.join(config_dir, 'Pr... |
'Return a set of directories in the folder specified that are not
hidden and are not marked to be removed
:param path:
The folder to list the directories inside of
:return:
A set of directory names'
| def _list_visible_dirs(self, path):
| output = set()
for filename in os.listdir(path):
if (filename[0] == '.'):
continue
file_path = os.path.join(path, filename)
if (not os.path.isdir(file_path)):
continue
if os.path.exists(os.path.join(file_path, 'package-control.cleanup')):
conti... |
'Return a set of all .sublime-package files in a folder
:param path:
The directory to look in for .sublime-package files
:return:
A set of the package names - i.e. with the .sublime-package suffix removed'
| def _list_sublime_package_files(self, path):
| output = set()
if (not os.path.exists(path)):
return output
for filename in os.listdir(path):
if (not re.search('\\.sublime-package$', filename)):
continue
output.add(filename.replace('.sublime-package', ''))
return output
|
'Checks if a package specified is a dependency
:param name:
The name of the package to check if it is a dependency
:return:
Bool, if the package is a dependency'
| def _is_dependency(self, name):
| metadata_path = os.path.join(self.settings['packages_path'], name, 'dependency-metadata.json')
hidden_path = os.path.join(self.settings['packages_path'], name, '.sublime-dependency')
return (os.path.exists(metadata_path) or os.path.exists(hidden_path))
|
'Find all of the dependencies required by the installed packages,
ignoring the specified package.
:param ignore_package:
The package to ignore when enumerating dependencies
:return:
A list of the dependencies required by the installed packages'
| def find_required_dependencies(self, ignore_package=None):
| output = ['0_package_control_loader']
for package in self.list_packages():
if (package == ignore_package):
continue
output.extend(self.get_dependencies(package))
for name in self._list_visible_dirs(self.settings['packages_path']):
metadata_path = os.path.join(self.setting... |
':return: The full filesystem path to the package directory'
| def get_package_dir(self, package):
| return os.path.join(self.settings['packages_path'], package)
|
':return: The name of the package after passing through mapping rules'
| def get_mapped_name(self, package):
| return self.settings.get('package_name_map', {}).get(package, package)
|
'Creates a .sublime-package file from the running Packages directory
:param package_name:
The package to create a .sublime-package file for
:param package_destination:
The full filesystem path of the directory to save the new
.sublime-package file in.
:param profile:
If None, the "dirs_to_ignore", "files_to_ignore", "f... | def create_package(self, package_name, package_destination, profile=None):
| package_dir = self.get_package_dir(package_name)
if (not os.path.exists(package_dir)):
show_error(u'\n The folder for the package name specified, %s,\n does ... |
'Downloads and installs (or upgrades) a package
Uses the self.list_available_packages() method to determine where to
retrieve the package file from.
The install process consists of:
1. Finding the package
2. Downloading the .sublime-package/.zip file
3. Extracting the package file
4. Showing install/upgrade messaging
5... | def install_package(self, package_name, is_dependency=False):
| if is_dependency:
packages = self.list_available_dependencies()
else:
packages = self.list_available_packages()
is_available = (package_name in list(packages.keys()))
unavailable_key = 'unavailable_packages'
if is_dependency:
unavailable_key = 'unavailable_dependencies'
i... |
'Ensures a list of dependencies are installed and up-to-date
:param dependencies:
A list of dependency names
:return:
A boolean indicating if the dependencies are properly installed'
| def install_dependencies(self, dependencies, fail_early=True):
| debug = self.settings.get('debug')
packages = self.list_available_dependencies()
error = False
for dependency in dependencies:
if (dependency == '0_package_control_loader'):
continue
dependency_dir = os.path.join(self.settings['packages_path'], dependency)
dependency_... |
'Remove all not needed dependencies by the installed packages,
ignoring the specified package.
:param ignore_package:
The package to ignore when enumerating dependencies.
Not used when required_dependencies is provided.
:param required_dependencies:
All required dependencies, for speedup purposes.
:return:
Boolean indi... | def cleanup_dependencies(self, ignore_package=None, required_dependencies=None):
| installed_dependencies = self.list_dependencies()
if (not required_dependencies):
required_dependencies = self.find_required_dependencies(ignore_package)
orphaned_dependencies = (set(installed_dependencies) - set(required_dependencies))
orphaned_dependencies = sorted(orphaned_dependencies, key=(... |
'Does a full backup of the Packages/{package}/ dir to Backup/
:param package_name:
The name of the package to back up
:return:
If the backup succeeded'
| def backup_package_dir(self, package_name):
| package_dir = os.path.join(self.settings['packages_path'], package_name)
if (not os.path.exists(package_dir)):
return True
try:
backup_dir = os.path.join(os.path.dirname(self.settings['packages_path']), 'Backup', datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
if (not os.path.exist... |
'Prints out package install and upgrade messages
The functionality provided by this allows package maintainers to
show messages to the user when a package is installed, or when
certain version upgrade occur.
:param package:
The name of the package the message is for
:param package_dir:
The full filesystem path to the p... | def print_messages(self, package, package_dir, is_upgrade, old_version, new_version):
| messages_file = os.path.join(package_dir, 'messages.json')
if (not os.path.exists(messages_file)):
return
messages_fp = open_compat(messages_file, 'r')
try:
message_info = json.loads(read_compat(messages_fp))
except ValueError:
console_write(u'\n ... |
'Deletes a package
The deletion process consists of:
1. Deleting the directory (or marking it for deletion if deletion fails)
2. Submitting usage info
3. Removing the package from the list of installed packages
:param package_name:
The package to delete
:return: bool if the package was successfully deleted or None
if t... | def remove_package(self, package_name, is_dependency=False):
| if (not is_dependency):
installed_packages = self.list_packages()
else:
installed_packages = self.list_dependencies()
package_type = 'package'
if is_dependency:
package_type = 'dependency'
if (package_name not in installed_packages):
show_error(u'\n ... |
'Submits install, upgrade and delete actions to a usage server
The usage information is currently displayed on the Package Control
website at https://packagecontrol.io
:param params:
A dict of the information to submit'
| def record_usage(self, params):
| if (not self.settings.get('submit_usage')):
return
params['package_control_version'] = self.get_metadata('Package Control').get('version')
params['sublime_platform'] = self.settings.get('platform')
params['sublime_version'] = self.settings.get('version')
for param in params:
if is... |
'Removes all cache entries older than the TTL
:param ttl:
The number of seconds a cache entry should be valid for'
| def clear(self, ttl):
| ttl = int(ttl)
for filename in os.listdir(self.base_path):
path = os.path.join(self.base_path, filename)
if os.path.isdir(path):
continue
mtime = os.stat(path).st_mtime
if (mtime < (time.time() - ttl)):
os.unlink(path)
|
'Returns a cached value
:param key:
The key to fetch the cache for
:return:
The (binary) cached value, or False'
| def get(self, key):
| cache_file = os.path.join(self.base_path, key)
if (not os.path.exists(cache_file)):
return False
with open_compat(cache_file, 'rb') as f:
return read_compat(f)
|
'Returns the filesystem path to the key
:param key:
The key to get the path for
:return:
The absolute filesystem path to the cache file'
| def path(self, key):
| return os.path.join(self.base_path, key)
|
'Saves a value in the cache
:param key:
The key to save the cache with
:param content:
The (binary) content to cache'
| def set(self, key, content):
| cache_file = os.path.join(self.base_path, key)
with open_compat(cache_file, 'wb') as f:
f.write(content)
|
'Loads the list of installed packages'
| def load_settings(self):
| settings = sublime.load_settings(pc_settings_filename())
self.original_installed_packages = load_list_setting(settings, 'installed_packages')
|
'Renames any installed packages that the user has installed.
:param installer:
An instance of :class:`PackageInstaller`'
| def rename_packages(self, installer):
| installer.manager.list_available_packages()
renamed_packages = installer.manager.settings.get('renamed_packages', {})
if (not renamed_packages):
renamed_packages = {}
installed_packages = list(self.original_installed_packages)
present_packages = installer.manager.list_packages()
case_ins... |
'Saves the list of installed packages (after having been appropriately
renamed)
:param installed_packages:
The new list of installed packages'
| def save_packages(self, installed_packages):
| filename = pc_settings_filename()
settings = sublime.load_settings(filename)
save_list_setting(settings, filename, 'installed_packages', installed_packages, self.original_installed_packages)
|
'On Windows, .sublime-package files are locked when imported, so we must
disable the package, delete it and then re-enable the package.
:param name:
The name of the package
:param filename:
The filename of the package'
| def remove_package_file(self, name, filename):
| def do_remove():
try:
os.remove(filename)
console_write(u'\n Removed orphaned package %s\n ', name)
except OS... |
'Detects if a package is compatible with the current Sublime Text install
:param metadata:
A dict from a metadata file
:return:
If the package is compatible'
| def is_compatible(self, metadata):
| sublime_text = metadata.get('sublime_text')
platforms = metadata.get('platforms', [])
if ((not sublime_text) and (not platforms)):
return True
if (not is_compatible_version(sublime_text)):
return False
if (not isinstance(platforms, list)):
platforms = [platforms]
platform... |
'A callback that can be run the main UI thread to perform saving of the
Package Control.sublime-settings file. Also fires off the
:class:`AutomaticUpgrader`.
:param installed_packages:
A list of the string package names of all "installed" packages,
even ones that do not appear to be in the filesystem.
:param found_pack... | def finish(self, installed_packages, found_packages, found_dependencies):
| pc_filename = pc_settings_filename()
pc_settings = sublime.load_settings(pc_filename)
in_process = load_list_setting(pc_settings, 'in_process_packages')
if in_process:
filename = preferences_filename()
settings = sublime.load_settings(filename)
ignored = load_list_setting(setting... |
'Gets the current version of a package
:param package:
The name of the package
:return:
The string version'
| def get_version(self, package):
| if package_file_exists(package, 'package-metadata.json'):
metadata_json = read_package_file(package, 'package-metadata.json')
if metadata_json:
try:
return json.loads(metadata_json).get('version', 'unknown version')
except ValueError:
pass
... |
'Disables one or more packages before installing or upgrading to prevent
errors where Sublime Text tries to read files that no longer exist, or
read a half-written file.
:param packages:
The string package name, or an array of strings
:param type:
The type of operation that caused the package to be disabled:
- "upgrade... | def disable_packages(self, packages, type='upgrade'):
| global events
if (events is None):
from package_control import events
if (not isinstance(packages, list)):
packages = [packages]
disabled = []
settings = sublime.load_settings(preferences_filename())
ignored = load_list_setting(settings, 'ignored_packages')
pc_settings = subl... |
'Re-enables a package after it has been installed or upgraded
:param package:
The string package name
:param type:
The type of operation that caused the package to be re-enabled:
- "upgrade"
- "remove"
- "install"
- "enable"
- "loader"'
| def reenable_package(self, package, type='upgrade'):
| global events
if (events is None):
from package_control import events
settings = sublime.load_settings(preferences_filename())
ignored = load_list_setting(settings, 'ignored_packages')
if (package in ignored):
if (type in ['install', 'upgrade']):
version = self.get_versio... |
'There are two different constructor styles that are allowed:
- Option 1 allows specification of a semantic version as a string and the option to "clean"
the string before parsing it.
- Option 2 allows specification of each component separately as one parameter.
Note that all the parameters specified in the following s... | def __new__(cls, *args, **kwargs):
| (ver, clean, comps) = (None, False, None)
(kw, l) = (kwargs.copy(), (len(args) + len(kwargs)))
def inv():
raise TypeError(('Invalid parameter combination: args=%s; kwargs=%s' % (args, kwargs)))
if ((l == 0) or (l > 5)):
raise TypeError(('SemVer accepts at least 1 ... |
'Alias for `bool(sel.matches(self))` or `bool(SemSel(sel).matches(self))`.
See `SemSel.__init__()` and `SemSel.matches(*vers)` for possible exceptions.
Returns:
* bool: `True` if the version matches the passed selector, `False` otherwise.'
| def satisfies(self, sel):
| if (not isinstance(sel, SemSel)):
sel = SemSel(sel)
return bool(sel.matches(self))
|
'Check if `ver` is a valid semantic version. Classmethod.
Parameters:
* ver (str)
The string that should be stripped.
Raises:
* TypeError
Invalid parameter type.
Returns:
* bool: `True` if it is valid, `False` otherwise.'
| @classmethod
def valid(cls, ver):
| if (not isinstance(ver, basestring)):
raise TypeError(('%r is not a string' % ver))
if cls._match_regex.match(ver):
return True
else:
return False
|
'Remove everything before and after a valid version string. Classmethod.
Parameters:
* vers (str)
The string that should be stripped.
Raises:
* TypeError
Invalid parameter type.
Returns:
* str: The stripped version string. Only the first version is matched.
* None: No version found in the string.'
| @classmethod
def clean(cls, vers):
| if (not isinstance(vers, basestring)):
raise TypeError(('%r is not a string' % vers))
m = cls._search_regex.search(vers)
if m:
return vers[m.start():m.end()]
else:
return None
|
'Private. Do not touch. Classmethod.'
| @classmethod
def _parse(cls, ver):
| if (not isinstance(ver, basestring)):
raise TypeError(('%r is not a string' % ver))
match = cls._match_regex.match(ver)
if (match is None):
raise ValueError(("'%s' is not a valid SemVer string" % ver))
g = list(match.groups())
for i in range(3):
... |
'Private. Do not touch.
self > other: 1
self = other: 0
self < other: -1'
| def _compare(self, other):
| def cp_len(t, i=0):
return cmp(len(t[i]), len(t[(not i)]))
for (i, (x1, x2)) in enumerate(zip(self, other)):
if (i > 2):
if ((x1 is None) and (x2 is None)):
continue
if ((x1 is None) or (x2 is None)):
return (int((2 * (i - 3.5))) * (1 - (2 ... |
'Constructor examples:
SemComparator(\'<=\', SemVer("1.2.3"))
SemComparator(\'!=\', SemVer("2.3.4"))
Parameters:
* op (str, False, None)
One of [>=, <=, >, <, =, !=, !, ~] or evaluates to `False` which defaults to \'~\'.
\'~\' means a "satisfy" operation where pre-releases and builds are ignored.
\'!\' is a negative "~... | def __init__(self, op, ver):
| super(SemComparator, self).__init__()
if (op and (op not in self._ops_satisfy) and (op not in self._ops)):
raise ValueError('Invalid value for `op` parameter.')
if (not isinstance(ver, SemVer)):
raise TypeError('`ver` parameter is not instance of SemVer.')
o... |
'Match the internal version (constructor) against `ver`.
Parameters:
* ver (SemVer)
Raises:
* TypeError
Could not compare `ver` against the version passed in the constructor with the
passed operator.
Returns:
* bool
`True` if the version matched the specified operator and internal version, `False`
otherwise.'
| def matches(self, ver):
| if (self.op in self._ops_satisfy):
return bool(((self.ver[:3] == ver[:3]) + ((self.op == '!') * (-1))))
ret = getattr(ver, self._ops[self.op])(self.ver)
if (ret == NotImplemented):
raise TypeError(("Unable to compare %r with operator '%s'" % (ver, self.op)))
return ret
|
'Match all of the added children against `ver`.
Parameters:
* ver (SemVer)
Raises:
* TypeError
Invalid `ver` parameter.
Returns:
* bool:
`True` if *all* of the SemComparator children match `ver`, `False` otherwise.'
| def matches(self, ver):
| if (not isinstance(ver, SemVer)):
raise TypeError('`ver` parameter is not instance of SemVer.')
return all((cp.matches(ver) for cp in self))
|
'Create a SemComparator instance with the given parameters and appends that to self.
Parameters:
* op (str)
* ver (SemVer)
Both parameters are forwarded to `SemComparator.__init__`, see there for a more detailed
description.
Raises:
Exceptions raised by `SemComparator.__init__`.'
| def add_child(self, op, ver):
| self.append(SemComparator(op, SemVer(ver)))
|
'Match all of the added children against `ver`.
Parameters:
* ver (SemVer)
Raises:
* TypeError
Invalid `ver` parameter.
Returns:
* bool
`True` if *any* of the SemSelAndChunk children matches `ver`.
`False` otherwise.'
| def matches(self, ver):
| if (not isinstance(ver, SemVer)):
raise TypeError('`ver` parameter is not instance of SemVer.')
return any((ch.matches(ver) for ch in self))
|
'Creates a new SemSelAndChunk instance, appends it to self and returns it.
Returns:
* SemSelAndChunk: An empty instance.'
| def new_child(self):
| ch = SemSelAndChunk()
self.append(ch)
return ch
|
'Constructor examples:
SemSel(">1.0.0")
SemSel("~1.2.9 !=1.2.12")
Parameters:
* sel (str)
A version selector string.
Raises:
* TypeError
`sel` parameter is not a string.
* ValueError
A version in the selector could not be matched as a SemVer.
* SemParseError
The version selector\'s syntax is unparsable; invalid ranges ... | def __new__(cls, sel):
| chunk = cls._parse(sel)
return super(SemSel, cls).__new__(cls, (chunk,))
|
'Match the selector against a selection of versions.
Parameters:
* *vers (str, SemVer)
Versions can be passed as strings and SemVer objects will be created with them.
May also be a mixed list.
Raises:
* TypeError
A version is not an instance of str (basestring) or SemVer.
* ValueError
A string version could not be pars... | def matches(self, *vers):
| ret = []
for v in vers:
if isinstance(v, str):
t = self._chunk.matches(SemVer(v))
elif isinstance(v, SemVer):
t = self._chunk.matches(v)
else:
raise TypeError(("Invalid parameter type '%s': %s" % (v, type(v))))
if t:
ret... |
'Private. Do not touch.
1. split by whitespace into tokens
a. start new and_chunk on \' || \'
b. parse " - " ranges
c. replace "xX*" ranges with "~" equivalent
d. parse "~" ranges
e. parse unmatched token as comparator
~. append to current and_chunk
2. return SemSelOrChunk
Raises TypeError, ValueError or SelParseError.... | @classmethod
def _parse(cls, sel):
| if (not isinstance(sel, basestring)):
raise TypeError('Selector must be a string')
if (not sel):
raise ValueError('String must not be empty')
tokens = sel.split()
i = (-1)
or_chunk = SemSelOrChunk()
and_chunk = or_chunk.new_child()
while ((i + 1) < len... |
'Creates a subprocess with the executable/args
:param args:
A list of the executable path and all arguments to it
:param cwd:
The directory in which to run the executable
:param input:
The input text to send to the program
:param meaningful_output:
If the output from the command is possibly meaningful and should
be dis... | def execute(self, args, cwd, input=None, encoding='utf-8', meaningful_output=False, ignore_errors=None):
| orig_cwd = cwd
startupinfo = None
if (os.name == 'nt'):
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
try:
cwd.encode('mbcs')
except UnicodeEncodeError:
buf = create_unicode_buffer(512)
if win... |
'Locates the executable by looking in the PATH and well-known directories
:param name:
The string filename of the executable
:return:
The filesystem path to the executable, or None if not found'
| def find_binary(self, name):
| if (self.cli_name in Cli.binary_paths):
return Cli.binary_paths[self.cli_name]
check_binaries = []
if self.binary_locations:
if (not isinstance(self.binary_locations, list)):
self.binary_locations = [self.binary_locations]
check_binaries.extend(self.binary_locations)
... |
':param found_packages:
A list of package names for the packages that were found to be
installed on the machine.
:param found_dependencies:
A list of installed dependencies found on the machine'
| def __init__(self, found_packages, found_dependencies):
| self.installer = PackageInstaller()
self.manager = self.installer.manager
self.load_settings()
self.package_renamer = PackageRenamer()
self.package_renamer.load_settings()
self.auto_upgrade = self.settings.get('auto_upgrade')
self.auto_upgrade_ignore = self.settings.get('auto_upgrade_ignore'... |
'Loads the last run time from disk into memory'
| def load_last_run(self):
| self.last_run = None
self.last_run_file = os.path.join(sublime.packages_path(), 'User', 'Package Control.last-run')
if os.path.isfile(self.last_run_file):
with open_compat(self.last_run_file) as fobj:
try:
self.last_run = int(read_compat(fobj))
except Value... |
'Figure out when the next run should happen'
| def determine_next_run(self):
| self.next_run = int(time.time())
frequency = self.settings.get('auto_upgrade_frequency')
if frequency:
if self.last_run:
self.next_run = (int(self.last_run) + ((frequency * 60) * 60))
else:
self.next_run = time.time()
|
'Saves a record of when the last run was
:param last_run:
The unix timestamp of when to record the last run as'
| def save_last_run(self, last_run):
| with open_compat(self.last_run_file, 'w') as fobj:
write_compat(fobj, int(last_run))
|
'Loads the list of installed packages'
| def load_settings(self):
| self.settings = sublime.load_settings(pc_settings_filename())
self.installed_packages = load_list_setting(self.settings, 'installed_packages')
self.should_install_missing = self.settings.get('install_missing')
|
'Installs all packages that were listed in the list of
`installed_packages` from Package Control.sublime-settings but were not
found on the filesystem and passed as `found_packages`. Also installs
any missing dependencies.'
| def install_missing(self):
| if self.missing_dependencies:
total_missing_dependencies = len(self.missing_dependencies)
dependency_s = ('ies' if (total_missing_dependencies != 1) else 'y')
console_write(u'\n Installing %s missing dependenc%s\n ... |
'Prints a notice in the console if the automatic upgrade is skipped
due to already having been run in the last `auto_upgrade_frequency`
hours.'
| def print_skip(self):
| last_run = datetime.datetime.fromtimestamp(self.last_run)
next_run = datetime.datetime.fromtimestamp(self.next_run)
date_format = '%Y-%m-%d %H:%M:%S'
console_write(u'\n Skipping automatic upgrade, last run at %s, next run at ... |
'Upgrades all packages that are not currently upgraded to the lastest
version. Also renames any installed packages to their new names.'
| def upgrade_packages(self):
| if (not self.auto_upgrade):
return
self.package_renamer.rename_packages(self.installer)
package_list = self.installer.make_package_list(['install', 'reinstall', 'downgrade', 'overwrite', 'none'], ignore_packages=self.auto_upgrade_ignore)
for package in package_list:
if (package[0] != 'Pa... |
'Downloads a URL and returns the contents
:param url:
The string URL to download
:param error_message:
The error message to include if the download fails
:param prefer_cached:
If cached version of the URL content is preferred over a new request
:raises:
DownloaderException: if there was an error downloading the URL
:re... | def fetch(self, url, error_message, prefer_cached=False):
| is_ssl = (re.search('^https://', url) is not None)
url = update_url(url, self.settings.get('debug'))
if (sys.platform == 'darwin'):
platform = 'osx'
elif (sys.platform == 'win32'):
platform = 'windows'
else:
platform = 'linux'
downloader_precedence = self.settings.get('do... |
'Shows a list of packages that can be turned into a .sublime-package file'
| def show_panel(self):
| self.manager = PackageManager()
self.packages = self.manager.list_packages(unpacked_only=True)
if (not self.packages):
show_error(u'\n There are no packages available to be packaged\n ... |
'Quick panel user selection handler - processes the user package
selection and prompts the user to pick a profile, or just creates the
package file if there are no profiles
:param picked:
An integer of the 0-based package name index from the presented
list. -1 means the user cancelled.'
| def on_done(self, picked):
| self.profile = None
if (picked == (-1)):
return
self.package_name = self.packages[picked]
rules = self.manager.settings.get('package_profiles')
if (not rules):
self.do_create_package()
return
self.profiles = ['Default']
for key in rules.keys():
self.profiles.a... |
'Quick panel user selection handler - processes the package profile
selection and creates the package file
:param picked:
An integer of the 0-based profile name index from the presented
list. -1 means the user cancelled.'
| def on_done_profile(self, picked):
| if (picked == (-1)):
return
if (picked > 0):
self.profile = self.profiles[picked]
self.do_create_package()
|
'Calls into the PackageManager to actually create the package file'
| def do_create_package(self):
| destination = self.get_package_destination()
if self.manager.create_package(self.package_name, destination, profile=self.profile):
self.window.run_command('open_dir', {'dir': destination, 'file': (self.package_name + '.sublime-package')})
|
'Retrieves the destination for .sublime-package files
:return:
A string - the path to the folder to save .sublime-package files in'
| def get_package_destination(self):
| destination = None
if self.profile:
profiles = self.manager.settings.get('package_profiles', {})
if (self.profile in profiles):
profile_settings = profiles[self.profile]
destination = profile_settings.get('package_destination')
if (not destination):
destinatio... |
'Check the key-value pairs of a release for validity.'
| def check_release_key_values(self, data, dependency):
| release_key_types_map = (self.dep_release_key_types_map if dependency else self.pck_release_key_types_map)
for (k, v) in data.items():
self.enforce_key_types_map(k, v, release_key_types_map)
if (k == 'url'):
if dependency:
if ('sha256' not in data):
... |
'A generic error-returning function used by the meta-programming features
of this class.
:param msg:
The error message to return
:param e:
An optional exception to include with the error message'
| def _test_error(self, msg, e=None):
| if e:
if isinstance(e, HTTPError):
self.fail(('%s: %s' % (msg, e)))
else:
self.fail(('%s: %r' % (msg, e)))
else:
self.fail(msg)
|
'Yields tuples of (method, args) to add to a unittest TestCase class.
A meta-programming function to expand the definition of class at run
time, based on the contents of a file or URL.
:param cls:
The class to add the methods to
:param path:
The URL or file path to fetch the repository info from
:param stream:
A file-l... | @classmethod
def _include_tests(cls, path, stream):
| stream.write(('%s ... ' % path))
stream.flush()
success = False
try:
if (re.match('https?://', path, re.I) is not None):
try:
f = urlopen(path)
source = f.read()
f.close()
except Exception as e:
(yield ... |
'Generates a (method, args) tuple that returns an error when called.
Allows for defering an error until the tests are actually run.'
| @classmethod
def _fail(cls, *args):
| return (cls._test_error, args)
|
'Writes dianostic output to a file-like object.
:param stream:
Must have the methods .write() and .flush()
:param string:
The string to write - a newline will NOT be appended'
| @classmethod
def _write(cls, stream, string):
| stream.write(string)
stream.flush()
|
'set_tunnel [True|False]
sets if the script will handle tunneling for you'
| def do_set_tunnel(self, option):
| if (option.lower() == 'true'):
self.logger.info('Script will handle tunneling for you')
self.sfile['do_tunnel'] = True
elif (option.lower() == 'false'):
self.logger.info('Script will not handle tunneling for you')
self.sfile['do_tunnel'] = False
... |
'set_shelve [KEY] [VALUE]
sets KEY to VALUE in the shelve file'
| def do_set_shelve(self, option):
| self.logger.debug('user ran set_shelve')
space = option.find(' ')
if (space == (-1)):
self.logger.error('could not determine your key and value')
return
key = option[:space]
value = option[(space + 1):]
if (key == ''):
self.logger.error('could ... |
'show_settings
displays all of the current configuration settings'
| def do_show_settings(self, option):
| self.logger.debug('user ran show_settings')
tools.show_settings(self.sfile, option, self.logger)
|
'show_tools
shows the support tools and versions'
| def do_show_tools(self, option):
| self.logger.debug('user ran show_tools')
for i in self.config.get('main', 'tools').split(','):
self.logger.info(('tool : ' + str(i)))
self.logger.info(('versions : ' + str(self.config.get(i, 'versions'))))
|
'bananaglee [VERSION]
selects the bananaglee VERSION to use'
| def do_bananaglee(self, version):
| self.logger.debug('user ran bananaglee')
if (version == ''):
self.logger.error('please specify a version')
elif (version in self.bg_versions):
self.logger.debug(('selected bananaglee ' + str(version)))
self.sfile['tool'] = 'bananaglee'
self.sfile['version... |
'add_iprange [IP NETMASK] or [IP/CIDR]
will all an IP range to use for tunneling'
| def do_add_iprange(self, input):
| self.logger.debug('user ran add_iprange')
tools.cidr(self.sfile, self.logger, input)
self.logger.debug('output from cidr')
self.logger.debug(self.sfile['iprange'])
|
'show_iprange
will print out all the IPs to use for communication'
| def do_show_iprange(self, input):
| self.logger.debug('user ran show_iprange')
if (self.sfile.has_key('iprange') == False):
self.logger.info('I do not have any IPs to use for communication')
else:
self.logger.info(self.sfile['iprange'])
|
'delete_iprange
deletes all the IPs to use for communication'
| def do_delete_iprange(self, input):
| self.logger.debug('user ran delete_iprange')
if (self.sfile.has_key('iprange') == False):
self.logger.info('I do not have any IPs to use for communication')
else:
self.logger.debug('current IPs in list: ')
self.logger.debug(self.sfile['ipr... |
'exit
exits the program'
| def do_exit(self, line):
| self.sfile['auto'] = False
self.sfile['auto_start'] = False
self.sfile['auto_end'] = False
self.logger.debug('exiting')
self.logger.debug(self.sfile)
self.sfile.close()
sys.exit()
|
'quit
quits the current context'
| def do_quit(self, line):
| self.sfile['auto'] = False
self.sfile['auto_start'] = False
self.sfile['auto_end'] = False
self.logger.debug('exiting')
self.logger.debug(self.sfile)
self.sfile.close()
return True
|
'Intalize variables'
| def __init__(self, shelve_file, logger):
| cmd.Cmd.__init__(self)
self.sfile = shelve_file
name = ('bananaglee' + self.sfile['version'])
self.logger = logger
self.prompt = (('BG' + self.sfile['version']) + '>>')
self.logger.debug('sfile contents:')
for i in self.sfile:
self.logger.debug(((i + ' : ') + str(self.sfile[... |
'show_settings
prints out the current settings'
| def do_show_settings(self, option):
| tools.show_settings(self.sfile, option, self.logger)
|
'survey - preforms a survey, interface info/config/arp'
| def do_survey(self, line):
| self.logger.debug('user ran survey')
self.logger.info('running survey')
if (tools.checks(self.sfile, self.logger) == False):
print tools.show_settings(self.sfile, ' ')
self.logger.error('missing required parameters')
return False
tunnel_number = tools.openTunnel... |
'show_uploadable_modules
displays the modules that can be uploaded'
| def do_show_uploadable_modules(self, option):
| self.logger.debug('user ran show_uploadable_modules')
self.logger.info('List of modules that can be uploaded')
try:
for i in self.sfile['mod_num_dict']:
self.logger.info(i)
except:
self.logger.exception('could not read mod_num_dict from ... |
'tunnel [OPTION]
calls program to manage tunnels
option: simple advanced'
| def do_tunnel(self, option):
| self.logger.debug('user ran tunnel')
if (self.sfile['survey'] == False):
self.logger.error('survey had not been completed, please run survey')
return
if ('packetToolkit' in self.sfile['uploaded_mod_list']):
pass
else:
self.logger.error('your ... |
'unload [module]
deactivates and removes a module'
| def do_unload(self, module):
| self.logger.debug(('user ran unload ' + str(module)))
if (self.sfile['survey'] == False):
self.logger.error('survey had not been completed, please run survey')
return
if (module in self.sfile['uploaded_mod_list']):
pass
else:
self.logger.erro... |
'show_uploaded_modules [connect]
returns the modules that are currently uploaded
if connect is used a connection to the firewall will be made'
| def do_show_uploaded_modules(self, line):
| if (line == ''):
self.logger.info('modules that are currently loaded')
for mod in self.sfile['uploaded_mod_list']:
self.logger.info(str(mod))
elif (line[0].lower() == 'c'):
tunnel_number = tools.openTunnel(self.sfile, self.logger)
command = ((((((((((((str... |
'shell
drops user to a BANANAGLEE shell'
| def do_shell(self, module):
| self.logger.debug('user ran shell')
tunnel_number = tools.openTunnel(self.sfile, self.logger)
command = ((((((((((((str(self.sfile['lp_bin']) + ' --lp ') + str(self.sfile['lp'])) + ' --implant ') + str(self.sfile['implant'])) + ' --idkey ') + str(self.sfile['idkey'])) + ' --sport ... |
'load [module]
uploads and activates a module'
| def do_load(self, module):
| self.logger.debug(('user ran load ' + str(module)))
if (module in self.sfile['mod_num_dict']):
module_number = self.sfile['mod_num_dict'][module]
else:
self.logger.error('selected an invalid module, the valid modules are:')
self.do_show_uploadable_module... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.