Search is not available for this dataset
text
stringlengths
75
104k
def check_meta(cls, dap): '''Check the meta.yaml in the dap. Return a list of DapProblems.''' problems = list() # Check for non array-like metadata for datatype in (Dap._required_meta | Dap._optional_meta) - Dap._array_meta: if not dap._isvalid(datatype): ...
def check_topdir(cls, dap): '''Check that everything is in the correct top-level directory. Return a list of DapProblems''' problems = list() dirname = os.path.dirname(dap._meta_location) if not dirname: msg = 'meta.yaml is not in top-level directory' pr...
def check_no_self_dependency(cls, dap): '''Check that the package does not depend on itself. Return a list of problems.''' problems = list() if 'package_name' in dap.meta and 'dependencies' in dap.meta: dependencies = set() for dependency in dap.meta['dependenc...
def check_name_not_on_dapi(cls, dap): '''Check that the package_name is not registered on Dapi. Return list of problems.''' problems = list() if dap.meta['package_name']: from . import dapicli d = dapicli.metadap(dap.meta['package_name']) if d: ...
def check_files(cls, dap): '''Check that there are only those files the standard accepts. Return list of DapProblems.''' problems = list() dirname = os.path.dirname(dap._meta_location) if dirname: dirname += '/' files = [f for f in dap.files if f.startswith(...
def check_yamls(cls, dap): '''Check that all assistants and snippets are valid. Return list of DapProblems.''' problems = list() for yaml in dap.assistants_and_snippets: path = yaml + '.yaml' parsed_yaml = YamlLoader.load_yaml_by_path(dap._get_file(path, prepend...
def _strip_leading_dirname(self, path): '''Strip leading directory name from the given path''' return os.path.sep.join(path.split(os.path.sep)[1:])
def assistants(self): '''Get all assistants in this DAP''' return [strip_suffix(f, '.yaml') for f in self._stripped_files if self._assistants_pattern.match(f)]
def snippets(self): '''Get all snippets in this DAP''' return [strip_suffix(f, '.yaml') for f in self._stripped_files if self._snippets_pattern.match(f)]
def icons(self, strip_ext=False): '''Get all icons in this DAP, optionally strip extensions''' result = [f for f in self._stripped_files if self._icons_pattern.match(f)] if strip_ext: result = [strip_suffix(f, '\.({ext})'.format(ext=self._icons_ext), regex=True) for f in result] ...
def _find_bad_meta(self): '''Fill self._badmeta with meta datatypes that are invalid''' self._badmeta = dict() for datatype in self.meta: for item in self.meta[datatype]: if not Dap._meta_valid[datatype].match(item): if datatype not in self._badme...
def _get_file(self, path, prepend=False): '''Extracts a file from dap to a file-like object''' if prepend: path = os.path.join(self._dirname(), path) extracted = self._tar.extractfile(path) if extracted: return extracted raise DapFileError(('Could not read...
def _load_meta(self, meta): '''Load data from meta.yaml to a dictionary''' meta = yaml.load(meta, Loader=Loader) # Versions are often specified in a format that is convertible to an # int or a float, so we want to make sure it is interpreted as a str. # Fix for the bug #300. ...
def _report_problem(self, problem, level=logging.ERROR): '''Report a given problem''' problem = self.basename + ': ' + problem if self._logger.isEnabledFor(level): self._problematic = True if self._check_raises: raise DapInvalid(problem) self._logger.log(l...
def _isvalid(self, datatype): '''Checks if the given datatype is valid in meta''' if datatype in self.meta: return bool(Dap._meta_valid[datatype].match(self.meta[datatype])) else: return datatype in Dap._optional_meta
def _arevalid(self, datatype): '''Checks if the given datatype is valid in meta (for array-like types)''' # Datatype not specified if datatype not in self.meta: return datatype in Dap._optional_meta, [] # Required datatype empty if datatype in self._required_meta and...
def _is_dir(self, f): '''Check if the given in-dap file is a directory''' return self._tar.getmember(f).type == tarfile.DIRTYPE
def _get_emptydirs(self, files): '''Find empty directories and return them Only works for actual files in dap''' emptydirs = [] for f in files: if self._is_dir(f): empty = True for ff in files: if ff.startswith(f + '/'): ...
def load_configuration_file(self): """ Load all configuration from file """ if not os.path.exists(self.config_file): return try: with open(self.config_file, 'r') as file: csvreader = csv.reader(file, delimiter='=', ...
def save_configuration_file(self): """ Save all configuration into file Only if config file does not yet exist or configuration was changed """ if os.path.exists(self.config_file) and not self.config_changed: return dirname = os.path.dirname(self.config_file) ...
def set_config_value(self, name, value): """ Set configuration value with given name. Value can be string or boolean type. """ if value is True: value = "True" elif value is False: if name in self.config_dict: del self.config_dict[n...
def tooltip_queries(self, item, x_coord, y_coord, key_mode, tooltip, text): """ The function is used for setting tooltip on menus and submenus """ tooltip.set_text(text) return True
def _create_notebook_page(self, assistant): """ This function is used for create tab page for notebook. Input arguments are: assistant - used for collecting all info about assistants and subassistants """ #frame = self._create_frame() grid_lang = self.gui_helper.c...
def _open_path_window(self): """ Hides this window and opens path window. Passes all needed data and kwargs. """ self.data['top_assistant'] = self.top_assistant self.data['current_main_assistant'] = self.get_current_main_assistant() self.data['kwargs'] = self.kwar...
def sub_menu_pressed(self, widget, event): """ Function serves for getting full assistant path and collects the information from GUI """ for index, data in enumerate(self.dev_assistant_path): index += 1 if settings.SUBASSISTANT_N_STRING.format(index) in se...
def get_current_main_assistant(self): """ Function return current assistant """ current_page = self.notebook.get_nth_page(self.notebook.get_current_page()) return current_page.main_assistant
def btn_clicked(self, widget, data=None): """ Function is used for case that assistant does not have any subassistants """ self.kwargs['subassistant_0'] = self.get_current_main_assistant().name self.kwargs['subassistant_1'] = data if 'subassistant_2' in self.kwarg...
def open_window(self, widget, data=None): """ Function opens Main Window and in case of previously created project is switches to /home directory This is fix in case that da creats a project and project was deleted and GUI was not closed yet """ if data is not Non...
def btn_press_event(self, widget, event): """ Function is used for showing Popup menu """ if event.type == Gdk.EventType.BUTTON_PRESS: if event.button.button == 1: widget.popup(None, None, None, None, event.button.button, event.tim...
def run_gui(): """ Function for running DevAssistant GUI """ try: from gi.repository import Gtk except ImportError as ie: pass except RuntimeError as e: sys.stderr.write(GUI_MESSAGE) sys.stderr.write("%s: %r" % (e.__class__.__name__, utils.exc_as_decoded_string(e)...
def needs_fully_loaded(method): """Wraps all publicly callable methods of YamlAssistant. If the assistant was loaded from cache, this decorator will fully load it first time a publicly callable method is used. """ @functools.wraps(method) def inner(self, *args, **kwargs): if not self.ful...
def default_icon_path(self): """Returns default path to icon of this assistant. Assuming self.path == "/foo/assistants/crt/python/django.yaml" For image format in [png, svg]: 1) Take the path of this assistant and strip it of load path (=> "crt/python/django.yaml") ...
def proper_kwargs(self, section, kwargs): """Returns kwargs updated with proper meta variables (like __assistant__). If this method is run repeatedly with the same section and the same kwargs, it always modifies kwargs in the same way. """ kwargs['__section__'] = section ...
def dependencies(self, kwargs=None, expand_only=False): """Returns all dependencies of this assistant with regards to specified kwargs. If expand_only == False, this method returns list of mappings of dependency types to actual dependencies (keeps order, types can repeat), e.g. Example:...
def get_perm_prompt(cls, package_list): """ Return text for prompt (do you want to install...), to install given packages. """ if cls == PackageManager: raise NotImplementedError() ln = len(package_list) plural = 's' if ln > 1 else '' return cls.permis...
def _try_get_current_manager(cls): """ Try to detect a package manager used in a current Gentoo system. """ if utils.get_distro_name().find('gentoo') == -1: return None if 'PACKAGE_MANAGER' in os.environ: pm = os.environ['PACKAGE_MANAGER'] if pm == 'paludis': ...
def is_current_manager_equals_to(cls, pm): """Returns True if this package manager is usable, False otherwise.""" if hasattr(cls, 'works_result'): return cls.works_result is_ok = bool(cls._try_get_current_manager() == pm) setattr(cls, 'works_result', is_ok) return is_...
def get_package_manager(self, dep_t): """Choose proper package manager and return it.""" mgrs = managers.get(dep_t, []) for manager in mgrs: if manager.works(): return manager if not mgrs: err = 'No package manager for dependency type "{dep_t}"'.fo...
def _process_dependency(self, dep_t, dep_l): """Add dependencies into self.dependencies, possibly also adding system packages that contain non-distro package managers (e.g. if someone wants to install dependencies with pip and pip is not present, it will get installed through RPM on RPM ...
def _ask_to_confirm(self, ui, pac_man, *to_install): """ Return True if user wants to install packages, False otherwise """ ret = DialogHelper.ask_for_package_list_confirm( ui, prompt=pac_man.get_perm_prompt(to_install), package_list=to_install, ) return bool(ret)
def _install_dependencies(self, ui, debug): """Install missing dependencies""" for dep_t, dep_l in self.dependencies: if not dep_l: continue pkg_mgr = self.get_package_manager(dep_t) pkg_mgr.works() to_resolve = [] for dep in de...
def install(self, struct, ui, debug=False): """ This is the only method that should be called from outside. Call it like: `DependencyInstaller(struct)` and it will install packages which are not present on system (it uses package managers specified by `struct` structure) ...
def refresh_role(self, role, file_hierarchy): """Checks and refreshes (if needed) all assistants with given role. Args: role: role of assistants to refresh file_hierarchy: hierarchy as returned by devassistant.yaml_assistant_loader.\ YamlAssistantLoad...
def _refresh_hierarchy_recursive(self, cached_hierarchy, file_hierarchy): """Recursively goes through given corresponding hierarchies from cache and filesystem and adds/refreshes/removes added/changed/removed assistants. Args: cached_hierarchy: the respective hierarchy part from cur...
def _ass_needs_refresh(self, cached_ass, file_ass): """Checks if assistant needs refresh. Assistant needs refresh iff any of following conditions is True: - stored source file is different than given source file - stored assistant ctime is lower than current source file ctime - ...
def _ass_refresh_attrs(self, cached_ass, file_ass): """Completely refreshes cached assistant from file. Args: cached_ass: an assistant from cache hierarchy (for format see Cache class docstring) file_ass: the respective assistant from filesystem hierarchy...
def _new_ass_hierarchy(self, file_ass): """Returns a completely new cache hierarchy for given assistant file. Args: file_ass: the assistant from filesystem hierarchy to create cache hierarchy for (for format see what refresh_role accepts) Returns: ...
def _get_snippet_ctime(self, snip_name): """Returns and remembers (during this DevAssistant invocation) last ctime of given snippet. Calling ctime costs lost of time and some snippets, like common_args, are used widely, so we don't want to call ctime bazillion times on them during one i...
def expand_dependencies_section(section, kwargs): """Expands dependency section, e.g. substitues "use: foo" for its contents, but doesn't evaluate conditions nor substitue variables.""" deps = [] for dep in section: for dep_type, dep_list in dep.items(): if dep_type in ['call', 'use...
def parse_for(control_line): """Returns name of loop control variable(s), iteration type (in/word_in) and expression to iterate on. For example: - given "for $i in $foo", returns (['i'], '$foo') - given "for ${i} in $(ls $foo)", returns (['i'], '$(ls $foo)') - given "for $k, $v in $foo", return...
def get_for_control_var_and_eval_expr(comm_type, kwargs): """Returns tuple that consists of control variable name and iterable that is result of evaluated expression of given for loop. For example: - given 'for $i in $(echo "foo bar")' it returns (['i'], ['foo', 'bar']) - given 'for $i, $j in $foo'...
def get_section_from_condition(if_section, else_section, kwargs): """Returns section that should be used from given if/else sections by evaluating given condition. Args: if_section - section with if clause else_section - section that *may* be else clause (just next section after if_section,...
def get_catch_vars(catch): """Returns 2-tuple with names of catch control vars, e.g. for "catch $was_exc, $exc" it returns ('was_exc', 'err'). Args: catch: the whole catch line Returns: 2-tuple with names of catch control variables Raises: exceptions.YamlSyntaxError if the...
def assign_variable(variable, log_res, res, kwargs): """Assigns given result (resp. logical result and result) to a variable (resp. to two variables). log_res and res are already computed result of an exec/input section. For example: $foo~: $spam and $eggs $log_res, $foo~: $spam and $eggs $foo...
def symbol(self, id, bp=0): """ Adds symbol 'id' to symbol_table if it does not exist already, if it does it merely updates its binding power and returns it's symbol class """ try: s = self.symbol_table[id] except KeyError: class s(self.sy...
def advance(self, id=None): """ Advance to next token, optionally check that current token is 'id' """ if id and self.token.id != id: raise SyntaxError("Expected {0}".format(id)) self.token = self.next()
def method(self, symbol_name): """ A decorator - adds the decorated method to symbol 'symbol_name' """ s = self.symbol(symbol_name) def bind(fn): setattr(s, fn.__name__, fn) return bind
def parse(self, expression): """ Evaluates 'expression' and returns it's value(s) """ if isinstance(expression, (list, dict)): return (True if expression else False, expression) if sys.version_info[0] > 2: self.next = self.tokenize(expression).__next__ ...
def get_platforms_set(): '''Returns set of all possible platforms''' # arch and mageia are not in Py2 _supported_dists, so we add them manually # Ubuntu adds itself to the list on Ubuntu platforms = set([x.lower() for x in platform._supported_dists]) platforms |= set(['darwin', 'arch', 'mageia', 'ub...
def find_file_in_load_dirs(relpath): """If given relative path exists in one of DevAssistant load paths, return its full path. Args: relpath: a relative path, e.g. "assitants/crt/test.yaml" Returns: absolute path of the file, e.g. "/home/x/.devassistant/assistanta/crt/test.yaml ...
def run_exitfuncs(): """Function that behaves exactly like Python's atexit, but runs atexit functions in the order in which they were registered, not reversed. """ exc_info = None for func, targs, kargs in _exithandlers: try: func(*targs, **kargs) except SystemExit: ...
def strip_prefix(string, prefix, regex=False): """Strip the prefix from the string If 'regex' is specified, prefix is understood as a regular expression.""" if not isinstance(string, six.string_types) or not isinstance(prefix, six.string_types): msg = 'Arguments to strip_prefix must be string types...
def strip_suffix(string, suffix, regex=False): """Strip the suffix from the string. If 'regex' is specified, suffix is understood as a regular expression.""" if not isinstance(string, six.string_types) or not isinstance(suffix, six.string_types): msg = 'Arguments to strip_suffix must be string type...
def _strip(string, pattern): """Return complement of pattern in string""" m = re.compile(pattern).search(string) if m: return string[0:m.start()] + string[m.end():len(string)] else: return string
def register_console_logging_handler(cls, lgr, level=logging.INFO): """Registers console logging handler to given logger.""" console_handler = logger.DevassistantClHandler(sys.stdout) if console_handler.stream.isatty(): console_handler.setFormatter(logger.DevassistantClColorFormatter...
def run(cls): """Runs the whole cli: 1. Registers console logging handler 2. Creates argparser from all assistants and actions 3. Parses args and decides what to run 4. Runs a proper assistant or action """ sigint_handler.override() # set settings.USE_CAC...
def inform_of_short_bin_name(cls, binary): """Historically, we had "devassistant" binary, but we chose to go with shorter "da". We still allow "devassistant", but we recommend using "da". """ binary = os.path.splitext(os.path.basename(binary))[0] if binary != 'da': ms...
def get_full_dir_name(self): """ Function returns a full dir name """ return os.path.join(self.dir_name.get_text(), self.entry_project_name.get_text())
def next_window(self, widget, data=None): """ Function opens the run Window who executes the assistant project creation """ # check whether deps-only is selected deps_only = ('deps_only' in self.args and self.args['deps_only']['checkbox'].get_active()) # preserve...
def _build_flags(self): """ Function builds kwargs variable for run_window """ # Check if all entries for selected arguments are nonempty for arg_dict in [x for x in self.args.values() if self.arg_is_selected(x)]: if 'entry' in arg_dict and not arg_dict['entry'].get_t...
def open_window(self, data=None): """ Function opens the Options dialog """ self.args = dict() if data is not None: self.top_assistant = data.get('top_assistant', None) self.current_main_assistant = data.get('current_main_assistant', None) self...
def _check_box_toggled(self, widget, data=None): """ Function manipulates with entries and buttons. """ active = widget.get_active() arg_name = data if 'entry' in self.args[arg_name]: self.args[arg_name]['entry'].set_sensitive(active) if 'browse_btn' ...
def _deps_only_toggled(self, widget, data=None): """ Function deactivate options in case of deps_only and opposite """ active = widget.get_active() self.dir_name.set_sensitive(not active) self.entry_project_name.set_sensitive(not active) self.dir_name_browse_btn.s...
def prev_window(self, widget, data=None): """ Function returns to Main Window """ self.path_window.hide() self.parent.open_window(widget, self.data)
def browse_path(self, window): """ Function opens the file chooser dialog for settings project dir """ text = self.gui_helper.create_file_chooser_dialog("Choose project directory", self.path_window, name="Select") if text is not None: self.dir_name.set_text(text)
def _add_table_row(self, arg, number, row): """ Function adds options to a grid """ self.args[arg.name] = dict() self.args[arg.name]['arg'] = arg check_box_title = arg.flags[number][2:].title() self.args[arg.name]['label'] = check_box_title align = self.gu...
def browse_clicked(self, widget, data=None): """ Function sets the directory to entry """ text = self.gui_helper.create_file_chooser_dialog("Please select directory", self.path_window) if text is not None: data.set_text(text)
def project_name_changed(self, widget, data=None): """ Function controls whether run button is enabled """ if widget.get_text() != "": self.run_btn.set_sensitive(True) else: self.run_btn.set_sensitive(False) self.update_full_label()
def dir_name_changed(self, widget, data=None): """ Function is used for controlling label Full Directory project name and storing current project directory in configuration manager """ config_manager.set_config_value("da.project_dir", self.dir_name.get_text()) ...
def check(self): """Checks whether loaded yaml is well-formed according to syntax defined for version 0.9.0 and later. Raises: YamlError: (containing a meaningful message) when the loaded Yaml is not well formed """ if not isinstance(self.parsed_yaml,...
def _check_args(self, source): '''Validate the argument section. Args may be either a dict or a list (to allow multiple positional args). ''' path = [source] args = self.parsed_yaml.get('args', {}) self._assert_struct_type(args, 'args', (dict, list), path) path.a...
def _assert_command_dict(self, struct, name, path=None, extra_info=None): """Checks whether struct is a command dict (e.g. it's a dict and has 1 key-value pair.""" self._assert_dict(struct, name, path, extra_info) if len(struct) != 1: err = [self._format_error_path(path + [name])] ...
def _assert_struct_type(self, struct, name, types, path=None, extra_info=None): """Asserts that given structure is of any of given types. Args: struct: structure to check name: displayable name of the checked structure (e.g. "run_foo" for section run_foo) types: list...
def _split_license(license): '''Returns all individual licenses in the input''' return (x.strip() for x in (l for l in _regex.split(license) if l))
def match(license): '''Returns True if given license field is correct Taken from rpmlint. It's named match() to mimic a compiled regexp.''' if license not in VALID_LICENSES: for l1 in _split_license(license): if l1 in VALID_LICENSES: continue for l2 in _s...
def register_command_runner(arg): """Decorator that registers a command runner. Accepts either: - CommandRunner directly or - String prefix to register a command runner under (returning a decorator) """ if isinstance(arg, str): def inner(command_runner): command_runners.setdefau...
def compare(ver1, ver2): '''Version comparing, returns 0 if are the same, returns >0 if first is bigger, <0 if first is smaller, excepts valid version''' if ver1 == ver2: return 0 ver1 = _cut(ver1) ver2 = _cut(ver2) # magic multiplier m = 1 # if the first one is shorter, repl...
def _cut(ver): '''Cuts the version to array, excepts valid version''' ver = ver.split('.') for i, part in enumerate(ver): try: ver[i] = int(part) except: if part[-len('dev'):] == 'dev': ver[i] = int(part[:-len('dev')]) ver.append(-3) ...
def generate_argument_parser(cls, tree, actions={}): """Generates argument parser for given assistant tree and actions. Args: tree: assistant tree as returned by devassistant.assistant_base.AssistantBase.get_subassistant_tree actions: dict mapping actions (deva...
def add_subassistants_to(cls, parser, assistant_tuple, level, alias=None): """Adds assistant from given part of assistant tree and all its subassistants to a given argument parser. Args: parser: instance of devassistant_argparse.ArgumentParser assistant_tuple: part of as...
def add_action_to(cls, parser, action, subactions, level): """Adds given action to given parser Args: parser: instance of devassistant_argparse.ArgumentParser action: devassistant.actions.Action subclass subactions: dict with subactions - {SubA: {SubB: {}}, SubC: {}}...
def format_entry(record, show_level=False, colorize=False): """ Format a log entry according to its level and context """ if show_level: log_str = u'{}: {}'.format(record.levelname, record.getMessage()) else: log_str = record.getMessage() if colorize and record.levelname in LOG_...
def switch_cursor(cursor_type, parent_window): """ Functions switches the cursor to cursor type """ watch = Gdk.Cursor(cursor_type) window = parent_window.get_root_window() window.set_cursor(watch)
def emit(self, record): """ Function inserts log messages to list_view """ msg = record.getMessage() list_store = self.list_view.get_model() Gdk.threads_enter() if msg: # Underline URLs in the record message msg = replace_markup_chars(recor...
def open_window(self, widget, data=None): """ Function opens the run window """ if data is not None: self.kwargs = data.get('kwargs', None) self.top_assistant = data.get('top_assistant', None) self.current_main_assistant = data.get('current_main_assist...
def remove_link_button(self): """ Function removes link button from Run Window """ if self.link is not None: self.info_box.remove(self.link) self.link.destroy() self.link = None
def delete_event(self, widget, event, data=None): """ Event cancels the project creation """ if not self.close_win: if self.thread.isAlive(): dlg = self.gui_helper.create_message_dialog("Do you want to cancel project creation?", ...
def list_view_changed(self, widget, event, data=None): """ Function shows last rows. """ adj = self.scrolled_window.get_vadjustment() adj.set_value(adj.get_upper() - adj.get_page_size())
def disable_buttons(self): """ Function disables buttons """ self.main_btn.set_sensitive(False) self.back_btn.hide() self.info_label.set_label('<span color="#FFA500">In progress...</span>') self.disable_close_window() if self.link is not None: ...
def allow_buttons(self, message="", link=True, back=True): """ Function allows buttons """ self.info_label.set_label(message) self.allow_close_window() if link and self.link is not None: self.link.set_sensitive(True) self.link.show_all() if...