text
stringlengths
81
112k
This function is used for create tab page for notebook. Input arguments are: assistant - used for collecting all info about assistants and subassistants def _create_notebook_page(self, assistant): """ This function is used for create tab page for notebook. Input arguments are: ...
Hides this window and opens path window. Passes all needed data and kwargs. 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_as...
Function serves for getting full assistant path and collects the information from GUI 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_...
Function return current assistant 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
Function is used for case that assistant does not have any subassistants 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 ...
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 def open_window(self, widget, data=None): """ Function opens Main Window and in cas...
Function is used for showing Popup menu 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, ...
Function for running DevAssistant GUI 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__._...
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. def needs_fully_loaded(method): """Wraps all publicly callable methods of YamlAssistant. If the assistant was loaded from cache,...
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") 2) Substitute its extension fo...
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. def proper_kwargs(self, section, kwargs): """Returns kwargs updated with proper meta variables (like __a...
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: [{'rpm', ['rubygems']}, {'gem', ['mygem']}, {'rpm', ['spam...
Return text for prompt (do you want to install...), to install given packages. 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 = le...
Try to detect a package manager used in a current Gentoo system. 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: p...
Returns True if this package manager is usable, False otherwise. 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() == ...
Choose proper package manager and return it. 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 pac...
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 based systems, etc. Skips dependencies that are...
Return True if user wants to install packages, False otherwise 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), ...
Install missing dependencies 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 ...
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 install(self, struct, ui, debug=False): """ ...
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.\ YamlAssistantLoader.get_assistants_file_hierarchy def refresh_role(self, ...
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 current cache (for format see Cache class docstring) ...
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 - stored list of subassistants is different than given list of su...
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 (for format see what refresh_role accept...
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: the newly created cache hierarchy def _new_ass_hie...
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 invocation. Args: snip_name: nam...
Expands dependency section, e.g. substitues "use: foo" for its contents, but doesn't evaluate conditions nor substitue variables. def expand_dependencies_section(section, kwargs): """Expands dependency section, e.g. substitues "use: foo" for its contents, but doesn't evaluate conditions nor substitue varia...
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", returns (['k', 'v'], '$foo') def parse_fo...
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' it returns (['i', 'j'], [('foo', 'bar')]) def get_for_control_v...
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, this method will check if it really is else); pos...
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 catch line is malformed def get_...
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: some: struct $log_res, $foo: some: ...
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 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 pow...
Advance to next token, optionally check that current token is 'id' 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.ne...
A decorator - adds the decorated method to symbol 'symbol_name' 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
Evaluates 'expression' and returns it's value(s) 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: ...
Returns set of all possible platforms 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 ...
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 or None if file is not found def find_file...
Function that behaves exactly like Python's atexit, but runs atexit functions in the order in which they were registered, not reversed. 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. """ ...
Strip the prefix from the string If 'regex' is specified, prefix is understood as a regular expression. 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_typ...
Strip the suffix from the string. If 'regex' is specified, suffix is understood as a regular expression. 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_t...
Return complement of pattern in string 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
Registers console logging handler to given logger. 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_hand...
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 def run(cls): """Runs the whole cli: 1. Registers console logging handler 2...
Historically, we had "devassistant" binary, but we chose to go with shorter "da". We still allow "devassistant", but we recommend using "da". def inform_of_short_bin_name(cls, binary): """Historically, we had "devassistant" binary, but we chose to go with shorter "da". We still allow "devassist...
Function returns a full dir name 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())
Function opens the run Window who executes the assistant project creation 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...
Function builds kwargs variable for run_window 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 'en...
Function opens the Options dialog 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...
Function manipulates with entries and buttons. 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'...
Function deactivate options in case of deps_only and opposite 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_na...
Function returns to Main Window def prev_window(self, widget, data=None): """ Function returns to Main Window """ self.path_window.hide() self.parent.open_window(widget, self.data)
Function opens the file chooser dialog for settings project dir 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") i...
Function adds options to a grid 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_...
Function sets the directory to entry 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)
Function controls whether run button is enabled 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)...
Function is used for controlling label Full Directory project name and storing current project directory in configuration manager def dir_name_changed(self, widget, data=None): """ Function is used for controlling label Full Directory project name and storing cur...
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 def check(self): """Checks whether loaded yaml is well-formed according to...
Validate the argument section. Args may be either a dict or a list (to allow multiple positional args). 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 = ...
Checks whether struct is a command dict (e.g. it's a dict and has 1 key-value pair. 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) ...
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/tuple of types that are allowed for given struct path: list with a source file...
Returns all individual licenses in the input 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))
Returns True if given license field is correct Taken from rpmlint. It's named match() to mimic a compiled regexp. 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: ...
Decorator that registers a command runner. Accepts either: - CommandRunner directly or - String prefix to register a command runner under (returning a decorator) def register_command_runner(arg): """Decorator that registers a command runner. Accepts either: - CommandRunner directly or - String pr...
Version comparing, returns 0 if are the same, returns >0 if first is bigger, <0 if first is smaller, excepts valid version 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: ...
Cuts the version to array, excepts valid version 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(par...
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 (devassistant.actions.Action subclasses) to their ...
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 assistant tree (see generate_argument_parser doc) level: level of subassista...
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 add_action_to(cls, parser, action, subactions, level): "...
Format a log entry according to its level and context 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.get...
Functions switches the cursor to cursor type 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)
Function inserts log messages to list_view 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 ...
Function opens the run window 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 ...
Function removes link button from Run Window 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
Event cancels the project creation 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 creatio...
Function shows last rows. 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())
Function disables buttons 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.lin...
Function allows buttons 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.l...
Thread executes devassistant API. def dev_assistant_start(self): """ Thread executes devassistant API. """ #logger_gui.info("Thread run") path = self.top_assistant.get_selected_subassistant_path(**self.kwargs) kwargs_decoded = dict() for k, v in self.kwargs.items...
Event in case that debug button is pressed. def debug_btn_clicked(self, widget, data=None): """ Event in case that debug button is pressed. """ self.store.clear() self.thread = threading.Thread(target=self.logs_update) self.thread.start()
Function updates logs. def logs_update(self): """ Function updates logs. """ Gdk.threads_enter() if not self.debugging: self.debugging = True self.debug_btn.set_label('Info logs') else: self.debugging = False self.debug_btn...
Function copies logs to clipboard. def clipboard_btn_clicked(self, widget, data=None): """ Function copies logs to clipboard. """ _clipboard_text = [] for record in self.debug_logs['logs']: if self.debugging: _clipboard_text.append(format_entry(record...
Event for back button. This occurs in case of devassistant fail. def back_btn_clicked(self, widget, data=None): """ Event for back button. This occurs in case of devassistant fail. """ self.remove_link_button() self.run_window.hide() self.parent.path_wind...
Button switches to Dev Assistant GUI main window def main_btn_clicked(self, widget, data=None): """ Button switches to Dev Assistant GUI main window """ self.remove_link_button() data = dict() data['debugging'] = self.debugging self.run_window.hide() self...
Function opens the firefox window with relevant link def list_view_row_clicked(self, list_view, path, view_column): """ Function opens the firefox window with relevant link """ model = list_view.get_model() text = model[path][0] match = URL_FINDER.search(text) if...
Create an authorization for a GitHub user using two-factor authentication. Unlike its non-two-factor counterpart, this method does not traverse the available authentications as they are not visible until the user logs in. Please note: cls._user's attributes are not accessibl...
Create a GitHub authorization for the given user in case they don't already have one. def _github_create_simple_authorization(cls): """Create a GitHub authorization for the given user in case they don't already have one. """ try: auth = None for a i...
Store an authorization token for the given GitHub user in the git global config file. def _github_store_authorization(cls, user, auth): """Store an authorization token for the given GitHub user in the git global config file. """ ClHelper.run_command("git config --global gi...
Starts ssh-agent and returns the environment variables related to it def _start_ssh_agent(cls): """Starts ssh-agent and returns the environment variables related to it""" env = dict() stdout = ClHelper.run_command('ssh-agent -s') lines = stdout.split('\n') for line in lines: ...
Creates a local ssh key, if it doesn't exist already, and uploads it to Github. def _github_create_ssh_key(cls): """Creates a local ssh key, if it doesn't exist already, and uploads it to Github.""" try: login = cls._user.login pkey_path = '{home}/.ssh/{keyname}'.format( ...
Returns True if any key on Github matches a local key, else False. def _github_ssh_key_exists(cls): """Returns True if any key on Github matches a local key, else False.""" remote_keys = map(lambda k: k._key, cls._user.get_keys()) found = False pubkey_files = glob.glob(os.path.expanduse...
Does user authentication, creates SSH keys if needed and injects "_user" attribute into class/object bound to the decorated function. Don't call any other methods of this class manually, this should be everything you need. def github_authenticated(cls, func): """Does user authentication, create...
Returns list of assistants that are subassistants of given superassistants (I love this docstring). Args: roles: list of names of roles, defaults to all roles Returns: list of YamlAssistant instances with specified roles def get_assistants(cls, superassistants): ...
Fills self._assistants with loaded YamlAssistant instances of requested roles. Tries to use cache (updated/created if needed). If cache is unusable, it falls back to loading all assistants. Args: roles: list of required assistant roles def load_all_assistants(cls, superassistants)...
Accepts cache_hierarch as described in devassistant.cache and returns instances of YamlAssistant (only with cached attributes) for loaded files Args: cache_hierarchy: structure as described in devassistant.cache role: role of all assistants in this hierarchy (we could find ...
Accepts file_hierarch as returned by cls.get_assistant_file_hierarchy and returns instances of YamlAssistant for loaded files Args: file_hierarchy: structure as described in cls.get_assistants_file_hierarchy role: role of all assistants in this hierarchy (we could find ...
Returns assistants file hierarchy structure (see below) representing assistant hierarchy in given directories. It works like this: 1. It goes through all *.yaml files in all given directories and adds them into hierarchy (if there are two files with same name in more directories, the...
Constructs instance of YamlAssistant loaded from given structure y, loaded from source file source. Args: source: path to assistant source file y: loaded yaml structure superassistant: superassistant of this assistant Returns: YamlAssistant instan...
name is in dotted format, e.g. topsnippet.something.wantedsnippet def get_snippet_by_name(cls, name): """name is in dotted format, e.g. topsnippet.something.wantedsnippet""" name_with_dir_separators = name.replace('.', os.path.sep) loaded = yaml_loader.YamlLoader.load_yaml_by_relpath(cls.snippe...
`5.6.1 Schema Validation Requirement <http://shex.io/shex-semantics/#validation-requirement>`_ A graph G is said to conform with a schema S with a ShapeMap m when: Every, SemAct in the startActs of S has a successful evaluation of semActsSatisfied. Every node n in m conforms to its associated shapeExp...