예제 #1
0
파일: core.py 프로젝트: lupine37/gps
    def async_fetch_commit_details(self, ids, visitor):
        """
        Fetch the details for each of the commits in the list.
        These details are returned asynchronously to GPS by calling
        `visitor.set_details`.

        :param List(str) ids: the list of commits for which we want the
          details.
        :param GPS.VCS2_Task_Visitor visitor: the object used to
          report the details.
        """
        GPS.Console().write("This action is not supported for %s" %
                            (self.name, ))
예제 #2
0
    def on_spawn(self, filestr, project, recursive):
        """
        Spawn gnatcheck.
        Must be called only after we have set the rules file
        """

        self.updateGnatCmd()

        if self.checkCmd == "":
            GPS.Console("Messages").write("Error: could not find gnatcheck")
            return

        # launch gnat check with specified project
        cmd = [self.checkCmd,
               '-P', project.file().name("Tools_Server"),
               '-dd']   # progress

        if self.gnatArgs:
            cmd += self.gnatArgs

        # also analyse subprojects ?
        if recursive:
            cmd.append('-U')

        # define the scenario variables
        scenario = GPS.Project.scenario_variables()
        if scenario is not None:
            for i, j in scenario.items():
                cmd.append('-X%s=%s' % (i, j))

        # now specify the files to check
        cmd.append(filestr)

        if self.rules_file:
            cmd.extend(
                ['-rules', '-from=%s' % self.rules_file.name("Tools_Server")])

        # clear the Checks category in the Locations view
        if GPS.Locations.list_categories().count(self.locations_string) > 0:
            GPS.Locations.remove_category(self.locations_string)

        self.msg = ""
        GPS.Process(
            cmd, "^.+$",
            on_match=self.on_match,
            on_exit=self.on_exit,
            progress_regexp="^ *completed (\d*) out of (\d*) .*$",
            progress_current=1,
            progress_total=2,
            remote_server="Tools_Server",
            show_command=True)
예제 #3
0
파일: align.py 프로젝트: ocsobservatory/gps
def align_arrows():
    """Aligns Ada arrow symbol '=>' in current selection"""
    # The algorithm is the following:
    #   - indent the selection
    #   - for N 1 .. 9:
    #      - replace level Nth of => by a special tag @>
    #      - aling on the special tag @> replacing it with =>
    buffer = GPS.EditorBuffer.get()
    top = buffer.selection_start()
    bottom = buffer.selection_end()
    top.create_mark("top")
    bottom.create_mark("bottom")
    found = False
    if top == bottom:
        GPS.MDI.dialog("You must first select the intended text")
        return
    try:
        with buffer.new_undo_group():
            for lr in range(9):
                try_indent(buffer, top, bottom)
                top = buffer.get_mark("top").location()
                bottom = buffer.get_mark("bottom").location()
                chars = buffer.get_chars(top, bottom)
                level = 0
                for k in range(len(chars)):
                    if chars[k] == '(':
                        level = level + 1
                    elif chars[k] == ')':
                        level = level - 1
                    elif chars[k] == '\n':
                        found = False
                    elif k + 4 < len(chars) and chars[k:k + 4] == "case":
                        level = level + 1
                    elif k + 8 < len(chars) and chars[k:k + 8] == "end case":
                        level = level - 1
                    elif (level == lr and k + 2 < len(chars)
                          and chars[k:k + 2] == "=>" and not found):
                        chars = chars[:k] + "@>" + chars[k + 2:]
                        found = True
                buffer.delete(top, bottom)
                buffer.insert(top, chars)
                top.create_mark("top")
                bottom.create_mark("bottom")
                top = buffer.get_mark("top").location()
                bottom = buffer.get_mark("bottom").location()
                range_align_on(top, bottom, sep="@>", replace_with=" => ")
                top = buffer.get_mark("top").location()
                bottom = buffer.get_mark("bottom").location()
                buffer.select(top, bottom)
    except:
        GPS.Console().write(str(sys.exc_info()) + "\n")
예제 #4
0
    def __verify_settings(self, for_debug=False):
        """
        Verify that the settings have correctly been set in order to flash,
        and, if for_debug is True, to debug a remote target.


        Return True if the settings are correctly set, False otherwise.
        """

        console = GPS.Console("Messages")
        message_header = ("Can't debug on board:"
                          if for_debug else "Can't flash the board:")
        result = True

        if not self.__connection_tool:
            console.write(("%s no connection tool specified. Please set the " %
                           (message_header)),
                          mode="error")
            console.insert_link("IDE'Connection_Tool",
                                self.__open_remote_project_properties)
            console.write(" project attribute\n", mode="error")
            result = False

        if self.__connection_tool == "openocd" and not self.__config_file:
            console.write(("%s no configuration file specified. "
                           "Please set the " % (message_header)),
                          mode="error")
            console.insert_link("IDE'Connection_Config_File",
                                self.__open_remote_project_properties)
            console.write(" project attribute\n", mode="error")
            result = False

        if for_debug and not self.__remote_target:
            console.write(("%s no remote target specified. Please set the " %
                           (message_header)),
                          mode="error")
            console.insert_link("IDE'Protocol_Host",
                                self.__open_remote_project_properties)
            console.write(" project attribute\n", mode="error")
            result = False

        if for_debug and not self.__remote_protocol:
            console.write(("%s no remote protocol specified. Please set the " %
                           (message_header)),
                          mode="error")
            console.insert_link("IDE'Communication_Protocol",
                                self.__open_remote_project_properties)
            console.write(" project attribute\n", mode="error")
            result = False

        return result
예제 #5
0
def on_project_changed(self):
    global attempted
    CreatedDirs = False
    created = []
    try:
        must_create = GPS.Preference("Auto-Create-Dirs").get()
    except Exception:
        must_create = True

    if must_create:
        prjs = GPS.Project.root().dependencies(True)
        prjs.append(GPS.Project.root())
        for i in prjs:
            dirs = [
                i.get_attribute_as_string("Exec_Dir"),
                i.get_attribute_as_string("Library_Dir"),
                i.get_attribute_as_string("Object_Dir"),
                i.get_attribute_as_string("Library_Src_Dir"),
                i.get_attribute_as_string("Library_ALI_Dir"),
                i.get_attribute_as_string("Artifacts_Dir", "IDE"),
                i.get_attribute_as_string("Documentation_Dir", "Documentation")
            ]
            for j in dirs:
                if i and i not in [".", "", " "]:
                    dir = os.path.join(os.path.dirname(i.file().path),
                                       j).strip()
                    # Only attempt to create each directory once
                    if dir not in attempted:
                        if not os.path.exists(dir):
                            os.makedirs(dir)
                            attempted.append(dir)
                            created.append(dir)
                            CreatedDirs = True
        if CreatedDirs:
            GPS.Console("Messages").write("Created missing dirs\n")
            GPS.Console("Messages").write(string.join(created, "\n"))
            GPS.Console("Messages").write("\n")
            GPS.Project.recompute()
예제 #6
0
 def __init__(self,
              command,
              close_on_exit=True,
              force=False,
              ansi=False,
              manage_prompt=True,
              task_manager=False):
     self.close_on_exit = close_on_exit
     try:
         GPS.Console.__init__(self,
                              command[0],
                              manage_prompt=manage_prompt,
                              on_input=self.on_input,
                              on_destroy=Console_Process.on_destroy,
                              on_resize=self.on_resize,
                              on_interrupt=Console_Process.on_interrupt,
                              on_completion=self.on_completion,
                              on_key=self.on_key,
                              ansi=ansi,
                              force=force,
                              save_desktop=self.save_desktop)
         GPS.Process.__init__(
             self,
             command=command,
             regexp='.+',
             single_line_regexp=True,  # For efficiency
             strip_cr=not ansi,  # if ANSI terminal, CR is irrelevant
             task_manager=task_manager,
             on_exit=self.on_exit,
             on_match=self.on_output)
     except Exception:
         GPS.Console().write(str(sys.exc_info()[1]) + '\n')
         try:
             self.destroy()
             self.kill()
         except Exception:
             pass
         GPS.Console().write('Could not spawn: %s\n' % (' '.join(command)))
예제 #7
0
    def run_gnatcov_wf(self, main_name):
        # Build the project with GNATcov switches
        p = promises.TargetWrapper("GNATcov Build Main")
        r = yield p.wait_on_execute()
        if r is not 0:
            GPS.Console("Messages").write("Can't build the project with " +
                                          "the GNATcov switches",
                                          mode="error")
            return

        # Get the executable to analyze
        exe = str(GPS.File(main_name).executable_path)

        # Run GNATcov on it
        p = promises.TargetWrapper("Run under GNATcov")
        r = yield p.wait_on_execute(exe)
        if r is not 0:
            GPS.Console("Messages").write("GNATcov run failed ", mode="error")
            return

        # Generate and display the GNATcov Coverage Report
        p = promises.TargetWrapper("Generate GNATcov Main Report")
        r = yield p.wait_on_execute(exe)
예제 #8
0
파일: aws.py 프로젝트: yoshiken/aws
def ada2wsdl(api):
    toolexe = locate_exec_on_path("ada2wsdl")
    if toolexe == "":
        GPS.Console("Messages").write("Error: ada2wsdl tool not found.")
    else:
        ofile = os.path.splitext(api)[0] + '.wsdl'
        idirs = []
        proj = GPS.current_context().project()
        for dir in proj.source_dirs():
            idirs = idirs + ["-I", dir]
        opts = GPS.Project.get_tool_switches_as_list (proj, "Ada2WSDL") \
            + ["-o", ofile] + idirs + [api]
        fopts = " ".join(opts)
        fopts = string.replace(fopts, "\\", "/")
        Console_Process(ofile, toolexe, fopts)
예제 #9
0
    def async_action_on_branch(self, visitor, action, category, id, text=''):
        """
        React to a double-click action in the Branches view.

        :param GPS.VCS2_Task_Visitor visitor: the object used to report
           asynchronously.
           If action is ACTION_TOOLTIP, use `visitor.tooltip`.
        :param GPS.VCS2.Action action: the action to perform
        :param str category: the upper-cased category, i.e. the first
           parameter to `visitor.branches` in the call to `async_branches`.
        :param str id: the id of the specific line that was selected.
        :param str text: the new name, when action is ACTION_RENAME
        """
        GPS.Console().write("This action is not supported for %s" %
                            (self.name, ))
예제 #10
0
    def async_view_file(self, visitor, ref, file):
        """
        Show the full contents of the file for the given revision.

        :param GPS.VCS2_Task.Visitor visitor: the object used to
           report the diff, via its 'file_computed` method.
        :param str ref: the ref to which we want to compare. This is
           typically the id of a commit (as returned from
           `async_fetch_history`, although it can also be the name of a
           branch, or "HEAD" to indicate the last commit done on the
           current branch.
        :param GPS.File file: the file for which we want a diff.
        """
        GPS.Console().write("This action is not supported for %s" %
                            (self.name, ))
예제 #11
0
파일: test.py 프로젝트: doytsujin/gps
def run_test():
    GPS.execute_action("open Outline")

    # Select 'my_class.hh' directory in the Project view
    GPS.MDI.get("Project").raise_window()
    explorer = get_widget_by_name("Project Explorer Tree")
    select_in_tree(explorer, column=1, key='my_class.hh')

    yield timeout(300)

    # Check the Outline view contents
    explorer = get_widget_by_name("Outline View Tree")
    GPS.Console().write(str(dump_tree_model(explorer.get_model(), 1)))
    gps_assert(dump_tree_model(explorer.get_model(), 1),
               expected,
               "Wrong outline view for main.cpp")
예제 #12
0
    def _internal_commit_staged_files(self, visitor, args):
        """
        Execute the command `args` and pass all staged files.

        :param List(str) args: the command and its arguments
        """
        # Need to copy the list, since '_staged' will be changed below
        files = list(self._staged)
        p = ProcessWrapper(args + [f.path for f in files],
                           directory=self.working_dir.path)
        (status, output) = yield p.wait_until_terminate()
        if status:
            GPS.Console().write("%s %s" % (" ".join(args), output))
        else:
            self.stage_or_unstage_files(files, stage=False)
            visitor.success('Commit successful')
예제 #13
0
 def run_gnatemu(args, in_console=True):
     command = GNATemulator.generate_gnatemu_command(
         GNATemulator.get_gnatemu_name(), args)
     GPS.Console("Messages").write("Running in emulator: %s\n" %
                                   (' '.join(command)))
     #  - We open GNATemu in a console by default.
     #  - If specified, we use the BuildTarget for running GNATemu instead.
     #  - Don't close the console when GNAtemu exits so we have time to see
     #    the results
     #  - GNATemu should be in the task manager
     if in_console:
         yield Console_Process(command=command, force=True,
                               close_on_exit=False, task_manager=True,
                               manage_prompt=False)
     else:
         builder = promises.TargetWrapper("Run GNATemulator")
         yield builder.wait_on_execute(extra_args=args)
예제 #14
0
파일: test.py 프로젝트: AdaCore/gps
def run_test():
    # Open a file that contains a Right To Left Override unicode
    # character.
    buf = GPS.EditorBuffer.get(GPS.File("main.adb"))

    # Set the charset to UTF8
    prop = Editor_Properties_Dialog()
    yield prop.open_and_yield("")
    charset = prop.get_character_set_entry()
    while charset.get_active_text() != "Unicode UTF-8":
        charset.set_active(charset.get_active() + 1)
    yield prop.ok()

    gps_assert(
        "Warning: the file contains bidirectional" in GPS.Console().get_text(),
        True,
        "A warning for unicode bidirectional characters should be displayed")
예제 #15
0
    def _setup(self):
        """
        Internal version of setup
        """

        self.__connect_hooks()
        if not self.view_title:
            self.view_title = self.__class__.__name__.replace("_", " ")
        self.setup()

        # Catch "gps_started" implementation in legacy or user-defined plugins
        if hasattr(self, "gps_started"):
            GPS.Console("Messages").write(
                "warning: Python module '%s' defines class '%s' with a"
                " method 'gps_started': this is no longer supported: instead,"
                " you should override 'setup'\n." % (
                    self.__module__, self.__class__.__name__))
예제 #16
0
파일: test.py 프로젝트: sungyeon-hancom/gps
def test_driver():
    GPS.execute_action("/Debug/Initialize/no main file")
    yield wait_tasks(other_than=known_tasks)

    GPS.Console("Messages").clear()
    yield wait_for_mdi_child('Debugger Console')
    debugger = GPS.Debugger.get()

    debugger.send("-target-attach " + os.environ['TESTPID'])
    e = debugger.get_executable()

    GPS.execute_action("debug continue")
    yield timeout(500)

    text = debugger.get_console().get_text()
    gps_assert("[program running]" in text, True,
               "The program should have been run on 'debug continue'")
예제 #17
0
def copy_base_file_name():
    """
    Copy the base name of the current file in the clipboard, so that it can be
    pasted elsewhere.
    """

    ctxt = GPS.current_context()
    if ctxt.file():
        f = ctxt.file().base_name()
    else:
        b = GPS.EditorBuffer.get(open=False)
        if b:
            f = b.file().base_name()

    if not f:
        GPS.Console().write("No file found\n")
    else:
        GPS.Clipboard.copy(f)
예제 #18
0
    def __init__(self):
        self.vc_time_pattern = re.compile(VC_PATTERN)
        self.vc_dictionary = dict()
        self.loc_list = list()

        try:
            proc = GPS.Process(command="gnatprove --list-categories")
            result = proc.get_result()

            for line in result.split("\n"):
                description = line.split("-")

                if len(description) == 3:
                    self.vc_dictionary[
                        description[0].strip()] = description[1].strip()
        except:
            GPS.Console(MESSAGES).write(
                "spat.py: Could not retrieve list of categories.", "error")
예제 #19
0
    def is_instrumentation_supported(self):
        # Check if GNATcov and GPRbuild are recent enough (after the 21
        # release)
        for exe in 'gnatcov', 'gprbuild':
            try:
                version_major, version_minor = self.version(exe)
            except Exception as e:
                # Can happen with the GS testuite if we use a fake gnatcov exe
                GPS.Console().write(str(e))
                return False

            if not (int(version_major) >= 22 or
                    (int(version_major) == 21 and version_minor[-1] != "w")):
                GPS.Logger("GNATCOVERAGE").log("instrumentation mode not " +
                                               "supported due to an older %s" %
                                               exe)
                return False

        return True
예제 #20
0
    def restore_run(self, run_timestamp):
        run = self.runs[run_timestamp]
        # Restore the files from the saved dir
        src = self._save_dir(run)
        dest = GPS.Project.root().artifacts_dir()
        for f in glob.glob(os.path.join(src, '*')):
            tgt = os.path.join(dest, os.path.basename(f))
            if os.path.exists(tgt):
                shutil.rmtree(tgt)
            shutil.copytree(f, tgt)

        # Clear the Messages view
        GPS.Console("Messages").clear()
        # Clear the locations
        GPS.Locations.remove_category(run["category"])

        parser = spark2014.GNATprove_Parser(None)
        parser.on_stdout(run['output'], None)
        parser.on_exit(0, None)
예제 #21
0
    def load_json(file, diagramFactory=None, load_styles=None):
        """
        Load the contents of the JSON file into the specified diagram. See the
        GPS.Browsers documentation for more information on the format.

        :param file: A file-like object, or a string, the name of the file
        :return: an instance of JSON_Diagram_File
        """

        try:
            if isinstance(file, str):
                file = open(file)

            return GPS.Browsers.Diagram.load_json_data(json.load(file),
                                                       diagramFactory,
                                                       load_styles)
        except Exception as e:
            GPS.Console().write("Unexpected exception %s\n%s\n" %
                                (e, traceback.format_exc()))
예제 #22
0
파일: gnatemulator.py 프로젝트: dailler/gps
    def run_gnatemu(self, args):
        sv = GPS.Project.scenario_variables()
        var_args = ["-X%s=%s" % (k, v) for k, v in sv.items()] if sv else []
        command = [self.get_gnatemu_name()]
        proj = GPS.Project.root()
        if proj:
            command.append("-P%s" % proj.file().path)
        command += var_args + args

        GPS.Console("Messages").write("Running in emulator: %s" %
                                      (' '.join(command)))
        #  - Open a console for each GNATemu run
        #  - Don't close the console when GNAtemu exits so we have time to see
        #    the results
        #  - GNATemu should be in the task manager
        Console_Process(command=command,
                        force=True,
                        close_on_exit=False,
                        task_manager=True)
예제 #23
0
파일: gerrit.py 프로젝트: zackboll/gps
    def async_action_on_branch(self, visitor, action, category, id, text=''):
        if category == CAT_REVIEWS:
            if id:
                id = json.loads(id)
            if action == GPS.VCS2.Actions.DOUBLE_CLICK and id:
                import webbrowser
                webbrowser.open(id['url'])

            elif action == GPS.VCS2.Actions.TOOLTIP:
                visitor.tooltip(
                    '\nDouble-click to open Gerrit on this change' +
                    ('\nClick [+] to cherry-pick this review' if id else ''))

            elif action == GPS.VCS2.Actions.ADD and id:
                p = self.base._git(['review', '--cherrypick', id['number']])
                status, _ = yield p.wait_until_terminate(show_if_error=True)
                if status == 0:
                    GPS.Console().write(
                        "Applied to working directory: %s\n" % id['number'])
예제 #24
0
def get_prep_file(for_subprogram=False, reset=False):
    """Retreive the .prep file in the project"""
    context = GPS.current_context()
    local_file = context.file().path
    file = context.file().name("Build_Server")

    if context.project():
        list_dir = context.project().object_dirs(False)
    else:
        list_dir = GPS.Project.root().object_dirs(False)

    if list_dir:
        objdir = list_dir[0]
    else:
        objdir = GPS.get_tmp_dir()
        GPS.Console("Messages").write(
            "Could not find an object directory for %s, reverting to %s" %
            (file, objdir))
    prep_file = os.path.join(objdir, os.path.basename(local_file)) + ".prep"
    return local_file, prep_file
예제 #25
0
def cu_load_preference(num):
    cu_regexp = GPS.Preference(
        "Messages:Custom Highlighting " + str(num) + "/regexp")
    cu_style = GPS.Preference(
        "Messages:Custom Highlighting " + str(num) + "/variant")

    if cu_regexp.get() == "":
        return

    style_value = cu_style.get().split('@')

    try:
        GPS.Console().create_link(regexp=cu_regexp.get(),
                                  on_click=lambda x: None,
                                  foreground=style_value[1],
                                  background=style_value[2],
                                  underline=False,
                                  font=style_value[0])
    except GPS.Exception:
        return
예제 #26
0
def __close_editors_if_needed(keep=set()):
    """
    If too many editors are opened, close one.

    :param set keep: a set of files that should not be closed, even if
       they are not pinned.
    """
    opened = GPS.EditorBuffer.list()
    toclose = len(opened) - maxeditors.get()

    for ed in reversed(opened):
        if toclose <= 0:
            break

        if (ed.file() not in keep and not ed.is_modified()
                and not getattr(ed, 'pinned', False)):

            GPS.Console().write('Automatically closing %s\n' % ed.file().path)
            ed.close(force=False)
            toclose -= 1
예제 #27
0
    def run_gnatemu(self, args):
        gnatemu = self.get_gnatemu_name()
        proj = GPS.Project.root()
        project_arg = "-P%s" % proj.file().path if proj else ""
        var_args = GPS.Project.scenario_variables_cmd_line("-X")

        if var_args:
            command = [gnatemu, project_arg, var_args] + args
        else:
            command = [gnatemu, project_arg] + args

        GPS.Console("Messages").write("Running in emulator: %s" %
                                      (' '.join(command)))
        #  - Open a console for each GNATemu run
        #  - Don't close the console when GNAtemu exits so we have time to see
        #    the results
        #  - GNATemu should be in the task manager
        Console_Process(command=command,
                        force=True,
                        close_on_exit=False,
                        task_manager=True)
예제 #28
0
def textmate_themes():
    """ Find all themes installed in the color_themes directory
        and return them as a list of dictionary objects.
    """

    results = []

    for file in glob.glob(
            os.path.join(GPS.get_system_dir(), 'share', 'gps', 'color_themes',
                         'themes', '*', '*.tmTheme')):
        try:
            results.append(TextmateTheme(file).theme())
        except Exception:
            msg, _, tb = sys.exc_info()
            tb = "\n".join(traceback.format_list(traceback.extract_tb(tb)))

            GPS.Console("Messages").write(
                "Exception when parsing theme file '%s':\n%s\n%s\n" %
                (file, msg, str(tb)))

    return results
예제 #29
0
파일: gnatfind.py 프로젝트: zackboll/gps
def __activate():
    context = GPS.contextual_context() or GPS.current_context()

    entity = context.entity()
    loc = context.location()

    buf = GPS.EditorBuffer.get(loc.file())
    location = buf.at(loc.line(), loc.column())

    entity_name = entity.name()
    length = len(entity_name)

    # Go to the beginning of the entity, as needed by gnatfind

    while not location.starts_word():
        location = location.forward_word(-1)

    entity_file = os.path.basename(loc.file().path)
    entity_line = location.line()
    entity_column = location.column()
    source_dirs = GPS.Project.root().get_attribute_as_list("source_dirs")
    object_dir = GPS.Project.root().get_attribute_as_string("object_dir")

    # Create the gnatfind command line

    command = (["gnatfind", "-r"] + ["-aI%s" % d for d in source_dirs] + [
        "-aO", object_dir,
        "%s:%s:%s:%s" %
        (entity_name, entity_file.split('\\')[-1], entity_line, entity_column)
    ])

    # Write the command line in the Messages window

    GPS.Console().write(" ".join(command) + "\n")

    # Launch the process

    proc = GPS.Process(command, on_exit=__on_gnatfind_exit)

    proc.query = "%s (%s:%s)" % (entity_name, entity_line, entity_column)
예제 #30
0
    def kill(self):
        """ Kill everything created during interactive theorem proving """

        global itp_started
        itp_started = False

        a = GPS.Console(ITP_CONSOLE)
        # Any closing destroying can fail so try are needed to avoid killing
        # nothing when the first exiting function fail.
        try:
            a.destroy()
        except Exception:
            print("Cannot close console")
        try:
            windows = GPS.MDI.children()
            for a in windows:
                if PROOF_TASK == a.name(short=True):
                    a.close(force=True)
        except Exception:
            print("Cannot close proof_task")
        try:
            windows = GPS.MDI.children()
            for a in windows:
                if PROOF_TREE_SHORT == a.name(short=True):
                    a.close(force=True)
        except Exception:
            print("Cannot close tree")
        try:
            self.process.kill()
        except BaseException:  # This is caught somewhere else and hang
            print("Cannot kill why3_server process")
        try:
            self.timeout.remove()
        except Exception:
            print("Cannot stop timeout")
        try:
            self.kill_menu()
        except Exception:
            print "Cannot remove transformations menu"