Ejemplo n.º 1
0
def project_data(project_dir, environment, json_output):
    if not is_platformio_project(project_dir):
        raise NotPlatformIOProjectError(project_dir)
    with fs.cd(project_dir):
        config = ProjectConfig.get_instance()
        config.validate(environment)
        environment = list(environment or config.envs())

    if json_output:
        return click.echo(
            json.dumps(load_project_ide_data(project_dir, environment)))

    for envname in environment:
        click.echo("Environment: " +
                   click.style(envname, fg="cyan", bold=True))
        click.echo("=" * (13 + len(envname)))
        click.echo(
            tabulate(
                [(click.style(name, bold=True), "=", json.dumps(value,
                                                                indent=2))
                 for name, value in load_project_ide_data(
                     project_dir, envname).items()],
                tablefmt="plain",
            ))
        click.echo()

    return None
Ejemplo n.º 2
0
    def setup_paths(self):
        self.project_dir = path_to_unicode(os.path.abspath(self.project_dir))
        try:
            data = load_project_ide_data(self.project_dir, self.environment)
            self.firmware_path = data["prog_path"]
            if not os.path.isfile(self.firmware_path):
                sys.stderr.write(
                    "%s: firmware at %s does not exist, rebuild the project?\n"
                    % (self.__class__.__name__, self.firmware_path))
                return False

            cc_path = data.get("cc_path", "")
            if "-gcc" in cc_path:
                path = cc_path.replace("-gcc", "-addr2line")
                if os.path.isfile(path):
                    self.addr2line_path = path
                    return True
        except PlatformioException as e:
            sys.stderr.write(
                "%s: disabling, exception while looking for addr2line: %s\n" %
                (self.__class__.__name__, e))
            return False
        sys.stderr.write("%s: disabling, failed to find addr2line.\n" %
                         self.__class__.__name__)
        return False
Ejemplo n.º 3
0
def print_target_list(envs):
    tabular_data = []
    for env, data in load_project_ide_data(os.getcwd(), envs).items():
        tabular_data.extend(
            sorted(
                [
                    (
                        click.style(env, fg="cyan"),
                        t["group"],
                        click.style(t.get("name"), fg="yellow"),
                        t["title"],
                        t.get("description"),
                    )
                    for t in data.get("targets", [])
                ],
                key=operator.itemgetter(1, 2),
            )
        )
        tabular_data.append((None, None, None, None, None))
    click.echo(
        tabulate(
            tabular_data,
            headers=[
                click.style(s, bold=True)
                for s in ("Environment", "Group", "Name", "Title", "Description")
            ],
        ),
    )
Ejemplo n.º 4
0
    def _load_tplvars(self):
        tpl_vars = {"env_name": self.env_name}
        # default env configuration
        tpl_vars.update(
            ProjectConfig.get_instance(join(
                self.project_dir, "platformio.ini")).items(env=self.env_name,
                                                           as_dict=True))
        # build data
        tpl_vars.update(
            load_project_ide_data(self.project_dir, self.env_name) or {})

        with util.cd(self.project_dir):
            tpl_vars.update({
                "project_name": basename(self.project_dir),
                "src_files": self.get_src_files(),
                "user_home_dir": abspath(expanduser("~")),
                "project_dir": self.project_dir,
                "project_src_dir": get_project_src_dir(),
                "project_lib_dir": get_project_lib_dir(),
                "project_libdeps_dir": join(
                    get_project_libdeps_dir(), self.env_name),
                "systype": util.get_systype(),
                "platformio_path": self._fix_os_path(
                    sys.argv[0] if isfile(sys.argv[0])
                    else where_is_program("platformio")),
                "env_pathsep": os.pathsep,
                "env_path": self._fix_os_path(os.getenv("PATH"))
            })  # yapf: disable
        return tpl_vars
Ejemplo n.º 5
0
 def _load_cpp_data(self, project_dir, envname):
     data = load_project_ide_data(project_dir, envname)
     if not data:
         return
     self.cpp_flags = data.get("cxx_flags", "").split(" ")
     self.cpp_includes = data.get("includes", [])
     self.cpp_defines = data.get("defines", [])
     self.cpp_defines.extend(
         self._get_toolchain_defines(data.get("cc_path")))
Ejemplo n.º 6
0
 def _load_cpp_data(self, project_dir):
     data = load_project_ide_data(project_dir, self.envname)
     if not data:
         return
     self.cc_flags = click.parser.split_arg_string(data.get("cc_flags", ""))
     self.cxx_flags = click.parser.split_arg_string(data.get("cxx_flags", ""))
     self.cpp_includes = self._dump_includes(data.get("includes", {}))
     self.cpp_defines = data.get("defines", [])
     self.cc_path = data.get("cc_path")
     self.cxx_path = data.get("cxx_path")
     self.toolchain_defines = self._get_toolchain_defines()
Ejemplo n.º 7
0
    def _load_tplvars(self):
        tpl_vars = {
            "config":
            self.config,
            "systype":
            util.get_systype(),
            "project_name":
            basename(self.project_dir),
            "project_dir":
            self.project_dir,
            "env_name":
            self.env_name,
            "user_home_dir":
            realpath(fs.expanduser("~")),
            "platformio_path":
            sys.argv[0]
            if isfile(sys.argv[0]) else where_is_program("platformio"),
            "env_path":
            os.getenv("PATH"),
            "env_pathsep":
            os.pathsep,
        }

        # default env configuration
        tpl_vars.update(self.config.items(env=self.env_name, as_dict=True))
        # build data
        tpl_vars.update(
            load_project_ide_data(self.project_dir, self.env_name) or {})

        with fs.cd(self.project_dir):
            tpl_vars.update({
                "src_files":
                self.get_src_files(),
                "project_src_dir":
                self.config.get_optional_dir("src"),
                "project_lib_dir":
                self.config.get_optional_dir("lib"),
                "project_libdeps_dir":
                join(self.config.get_optional_dir("libdeps"), self.env_name),
            })

        for key, value in tpl_vars.items():
            if key.endswith(("_path", "_dir")):
                tpl_vars[key] = fs.to_unix_path(value)
        for key in ("src_files", "libsource_dirs"):
            if key not in tpl_vars:
                continue
            tpl_vars[key] = [fs.to_unix_path(inc) for inc in tpl_vars[key]]

        tpl_vars["to_unix_path"] = fs.to_unix_path
        tpl_vars["filter_includes"] = self.filter_includes
        return tpl_vars
Ejemplo n.º 8
0
def cli(ctx, project_dir, project_conf, environment, verbose, interface,
        __unprocessed):
    # use env variables from Eclipse or CLion
    for sysenv in ("CWD", "PWD", "PLATFORMIO_PROJECT_DIR"):
        if is_platformio_project(project_dir):
            break
        if os.getenv(sysenv):
            project_dir = os.getenv(sysenv)

    with util.cd(project_dir):
        config = ProjectConfig.get_instance(
            project_conf or join(project_dir, "platformio.ini"))
        config.validate(envs=[environment] if environment else None)

        env_name = environment or helpers.get_default_debug_env(config)
        env_options = config.items(env=env_name, as_dict=True)
        if not set(env_options.keys()) >= set(["platform", "board"]):
            raise exception.ProjectEnvsNotAvailable()
        debug_options = helpers.validate_debug_options(ctx, env_options)
        assert debug_options

    if not interface:
        return helpers.predebug_project(ctx, project_dir, env_name, False,
                                        verbose)

    configuration = load_project_ide_data(project_dir, env_name)
    if not configuration:
        raise exception.DebugInvalidOptions(
            "Could not load debug configuration")

    if "--version" in __unprocessed:
        result = util.exec_command([configuration['gdb_path'], "--version"])
        if result['returncode'] == 0:
            return click.echo(result['out'])
        raise exception.PlatformioException("\n".join(
            [result['out'], result['err']]))

    try:
        util.ensure_udev_rules()
    except NameError:
        pass
    except exception.InvalidUdevRules as e:
        for line in str(e).split("\n") + [""]:
            click.echo(
                ('~"%s\\n"' if helpers.is_mi_mode(__unprocessed) else "%s") %
                line)

    debug_options['load_cmds'] = helpers.configure_esp32_load_cmds(
        debug_options, configuration)

    rebuild_prog = False
    preload = debug_options['load_cmds'] == ["preload"]
    load_mode = debug_options['load_mode']
    if load_mode == "always":
        rebuild_prog = (
            preload
            or not helpers.has_debug_symbols(configuration['prog_path']))
    elif load_mode == "modified":
        rebuild_prog = (
            helpers.is_prog_obsolete(configuration['prog_path'])
            or not helpers.has_debug_symbols(configuration['prog_path']))
    else:
        rebuild_prog = not isfile(configuration['prog_path'])

    if preload or (not rebuild_prog and load_mode != "always"):
        # don't load firmware through debug server
        debug_options['load_cmds'] = []

    if rebuild_prog:
        if helpers.is_mi_mode(__unprocessed):
            click.echo('~"Preparing firmware for debugging...\\n"')
            output = helpers.GDBBytesIO()
            with util.capture_std_streams(output):
                helpers.predebug_project(ctx, project_dir, env_name, preload,
                                         verbose)
            output.close()
        else:
            click.echo("Preparing firmware for debugging...")
            helpers.predebug_project(ctx, project_dir, env_name, preload,
                                     verbose)

        # save SHA sum of newly created prog
        if load_mode == "modified":
            helpers.is_prog_obsolete(configuration['prog_path'])

    if not isfile(configuration['prog_path']):
        raise exception.DebugInvalidOptions("Program/firmware is missed")

    # run debugging client
    inject_contrib_pysite()
    from platformio.commands.debug.client import GDBClient, reactor

    client = GDBClient(project_dir, __unprocessed, debug_options, env_options)
    client.spawn(configuration['gdb_path'], configuration['prog_path'])

    signal.signal(signal.SIGINT, lambda *args, **kwargs: None)
    reactor.run()

    return True
Ejemplo n.º 9
0
def cli(ctx, project_dir, project_conf, environment, verbose, interface,
        __unprocessed):
    app.set_session_var("custom_project_conf", project_conf)

    # use env variables from Eclipse or CLion
    for sysenv in ("CWD", "PWD", "PLATFORMIO_PROJECT_DIR"):
        if is_platformio_project(project_dir):
            break
        if os.getenv(sysenv):
            project_dir = os.getenv(sysenv)

    with fs.cd(project_dir):
        config = ProjectConfig.get_instance(project_conf)
        config.validate(envs=[environment] if environment else None)

        env_name = environment or helpers.get_default_debug_env(config)
        env_options = config.items(env=env_name, as_dict=True)
        if not set(env_options.keys()) >= set(["platform", "board"]):
            raise ProjectEnvsNotAvailableError()
        debug_options = helpers.validate_debug_options(ctx, env_options)
        assert debug_options

    if not interface:
        return helpers.predebug_project(ctx, project_dir, env_name, False,
                                        verbose)

    configuration = load_project_ide_data(project_dir, env_name)
    if not configuration:
        raise DebugInvalidOptionsError("Could not load debug configuration")

    if "--version" in __unprocessed:
        result = proc.exec_command([configuration["gdb_path"], "--version"])
        if result["returncode"] == 0:
            return click.echo(result["out"])
        raise exception.PlatformioException("\n".join(
            [result["out"], result["err"]]))

    try:
        fs.ensure_udev_rules()
    except exception.InvalidUdevRules as e:
        click.echo(
            helpers.escape_gdbmi_stream("~",
                                        str(e) + "\n")
            if helpers.is_gdbmi_mode() else str(e) + "\n",
            nl=False,
        )

    debug_options["load_cmds"] = helpers.configure_esp32_load_cmds(
        debug_options, configuration)

    rebuild_prog = False
    preload = debug_options["load_cmds"] == ["preload"]
    load_mode = debug_options["load_mode"]
    if load_mode == "always":
        rebuild_prog = preload or not helpers.has_debug_symbols(
            configuration["prog_path"])
    elif load_mode == "modified":
        rebuild_prog = helpers.is_prog_obsolete(
            configuration["prog_path"]) or not helpers.has_debug_symbols(
                configuration["prog_path"])
    else:
        rebuild_prog = not isfile(configuration["prog_path"])

    if preload or (not rebuild_prog and load_mode != "always"):
        # don't load firmware through debug server
        debug_options["load_cmds"] = []

    if rebuild_prog:
        if helpers.is_gdbmi_mode():
            click.echo(
                helpers.escape_gdbmi_stream(
                    "~", "Preparing firmware for debugging...\n"),
                nl=False,
            )
            stream = helpers.GDBMIConsoleStream()
            with util.capture_std_streams(stream):
                helpers.predebug_project(ctx, project_dir, env_name, preload,
                                         verbose)
            stream.close()
        else:
            click.echo("Preparing firmware for debugging...")
            helpers.predebug_project(ctx, project_dir, env_name, preload,
                                     verbose)

        # save SHA sum of newly created prog
        if load_mode == "modified":
            helpers.is_prog_obsolete(configuration["prog_path"])

    if not isfile(configuration["prog_path"]):
        raise DebugInvalidOptionsError("Program/firmware is missed")

    # run debugging client
    inject_contrib_pysite()

    # pylint: disable=import-outside-toplevel
    from platformio.commands.debug.process.client import GDBClient, reactor

    client = GDBClient(project_dir, __unprocessed, debug_options, env_options)
    client.spawn(configuration["gdb_path"], configuration["prog_path"])

    signal.signal(signal.SIGINT, lambda *args, **kwargs: None)
    reactor.run()

    return True