Ejemplo n.º 1
0
def test_run(pioproject_dir):
    with util.cd(pioproject_dir):
        build_dir = util.get_projectbuild_dir()
        if isdir(build_dir):
            util.rmtree_(build_dir)

        result = util.exec_command(["platformio", "--force", "run"])
        if result['returncode'] != 0:
            pytest.fail(result)

        assert isdir(build_dir)

        # check .elf file
        for item in listdir(build_dir):
            if not isdir(item):
                continue
            assert isfile(join(build_dir, item, "firmware.elf"))
            # check .hex or .bin files
            firmwares = []
            for ext in ("bin", "hex"):
                firmwares += glob(join(build_dir, item, "firmware*.%s" % ext))
            if not firmwares:
                pytest.fail("Missed firmware file")
            for firmware in firmwares:
                assert getsize(firmware) > 0
Ejemplo n.º 2
0
def cli(ctx, **options):
    non_storage_cmds = ("search", "show", "register", "stats", "builtin")
    # skip commands that don't need storage folder
    if ctx.invoked_subcommand in non_storage_cmds or \
            (len(ctx.args) == 2 and ctx.args[1] in ("-h", "--help")):
        return
    storage_dir = options['storage_dir']
    if not storage_dir:
        if options['global']:
            storage_dir = join(util.get_home_dir(), "lib")
        elif util.is_platformio_project():
            storage_dir = util.get_projectlibdeps_dir()
        elif util.is_ci():
            storage_dir = join(util.get_home_dir(), "lib")
            click.secho(
                "Warning! Global library storage is used automatically. "
                "Please use `platformio lib --global %s` command to remove "
                "this warning." % ctx.invoked_subcommand,
                fg="yellow")
    elif util.is_platformio_project(storage_dir):
        with util.cd(storage_dir):
            storage_dir = util.get_projectlibdeps_dir()

    if not storage_dir and not util.is_platformio_project():
        raise exception.NotGlobalLibDir(util.get_project_dir(),
                                        join(util.get_home_dir(), "lib"),
                                        ctx.invoked_subcommand)

    ctx.obj = LibraryManager(storage_dir)
    if "--json-output" not in ctx.args:
        click.echo("Library Storage: " + storage_dir)
Ejemplo n.º 3
0
def test_run(pioproject_dir):
    with util.cd(pioproject_dir):
        build_dir = util.get_projectbuild_dir()
        if isdir(build_dir):
            util.rmtree_(build_dir)

        env_names = []
        for section in util.load_project_config().sections():
            if section.startswith("env:"):
                env_names.append(section[4:])

        result = util.exec_command(
            ["platformio", "run", "-e",
             random.choice(env_names)])
        if result['returncode'] != 0:
            pytest.fail(result)

        assert isdir(build_dir)

        # check .elf file
        for item in listdir(build_dir):
            if not isdir(item):
                continue
            assert isfile(join(build_dir, item, "firmware.elf"))
            # check .hex or .bin files
            firmwares = []
            for ext in ("bin", "hex"):
                firmwares += glob(join(build_dir, item, "firmware*.%s" % ext))
            if not firmwares:
                pytest.fail("Missed firmware file")
            for firmware in firmwares:
                assert getsize(firmware) > 0
Ejemplo n.º 4
0
 def get_src_files(self):
     result = []
     with util.cd(self.project_dir):
         for root, _, files in os.walk(util.get_projectsrc_dir()):
             for f in files:
                 result.append(relpath(join(root, f)))
     return result
Ejemplo n.º 5
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.º 6
0
def test_run(pioproject_dir):
    with util.cd(pioproject_dir):
        build_dir = get_project_build_dir()
        if isdir(build_dir):
            util.rmtree_(build_dir)

        env_names = ProjectConfig(join(pioproject_dir,
                                       "platformio.ini")).envs()
        result = util.exec_command(
            ["platformio", "run", "-e",
             random.choice(env_names)])
        if result['returncode'] != 0:
            pytest.fail(str(result))

        assert isdir(build_dir)

        # check .elf file
        for item in listdir(build_dir):
            if not isdir(item):
                continue
            assert isfile(join(build_dir, item, "firmware.elf"))
            # check .hex or .bin files
            firmwares = []
            for ext in ("bin", "hex"):
                firmwares += glob(join(build_dir, item, "firmware*.%s" % ext))
            if not firmwares:
                pytest.fail("Missed firmware file")
            for firmware in firmwares:
                assert getsize(firmware) > 0
Ejemplo n.º 7
0
def test_run(pioproject_dir):
    with util.cd(pioproject_dir):
        build_dir = util.get_projectbuild_dir()
        if isdir(build_dir):
            util.rmtree_(build_dir)

        env_names = []
        for section in util.load_project_config().sections():
            if section.startswith("env:"):
                env_names.append(section[4:])

        result = util.exec_command(
            ["platformio", "run", "-e",
             random.choice(env_names)])
        if result['returncode'] != 0:
            pytest.fail(result)

        assert isdir(build_dir)

        # check .elf file
        for item in listdir(build_dir):
            if not isdir(item):
                continue
            assert isfile(join(build_dir, item, "firmware.elf"))
            # check .hex or .bin files
            firmwares = []
            for ext in ("bin", "hex"):
                firmwares += glob(join(build_dir, item, "firmware*.%s" % ext))
            if not firmwares:
                pytest.fail("Missed firmware file")
            for firmware in firmwares:
                assert getsize(firmware) > 0
 def get_src_files(self):
     result = []
     with util.cd(self.project_dir):
         for root, _, files in os.walk(self.project_src_dir):
             for f in files:
                 result.append(relpath(join(root, f)))
     return result
Ejemplo n.º 9
0
 def _finalize_arduino_import(_, project_dir, arduino_project_dir):
     with util.cd(project_dir):
         src_dir = get_project_src_dir()
         if isdir(src_dir):
             util.rmtree_(src_dir)
         shutil.copytree(arduino_project_dir, src_dir)
     return project_dir
Ejemplo n.º 10
0
def cli(ctx, environment, target, upload_port, project_dir, project_conf, jobs,
        silent, verbose, disable_auto_clean):
    # find project directory on upper level
    if isfile(project_dir):
        project_dir = find_project_dir_above(project_dir)

    with util.cd(project_dir):
        # clean obsolete build dir
        if not disable_auto_clean:
            try:
                clean_build_dir(get_project_build_dir())
            except:  # pylint: disable=bare-except
                click.secho(
                    "Can not remove temporary directory `%s`. Please remove "
                    "it manually to avoid build issues" %
                    get_project_build_dir(force=True),
                    fg="yellow")

        config = ProjectConfig.get_instance(
            project_conf or join(project_dir, "platformio.ini"))
        config.validate(environment)

        handle_legacy_libdeps(project_dir, config)

        results = []
        start_time = time()
        default_envs = config.default_envs()
        for envname in config.envs():
            skipenv = any([
                environment and envname not in environment, not environment
                and default_envs and envname not in default_envs
            ])
            if skipenv:
                results.append((envname, None))
                continue

            if not silent and any(status is not None
                                  for (_, status) in results):
                click.echo()

            ep = EnvironmentProcessor(ctx, envname, config, target,
                                      upload_port, silent, verbose, jobs)
            result = (envname, ep.process())
            results.append(result)

            if result[1] and "monitor" in ep.get_build_targets() and \
                    "nobuild" not in ep.get_build_targets():
                ctx.invoke(cmd_device_monitor,
                           environment=environment[0] if environment else None)

        found_error = any(status is False for (_, status) in results)

        if (found_error or not silent) and len(results) > 1:
            click.echo()
            print_summary(results, start_time)

        if found_error:
            raise exception.ReturnErrorCode(1)
        return True
Ejemplo n.º 11
0
def cli(
        ctx,
        environment,
        target,
        upload_port,  # pylint: disable=R0913,R0914
        project_dir,
        verbose,
        disable_auto_clean):
    with util.cd(project_dir):
        config = util.get_project_config()

        if not config.sections():
            raise exception.ProjectEnvsNotAvailable()

        known = set([s[4:] for s in config.sections() if s.startswith("env:")])
        unknown = set(environment) - known
        if unknown:
            raise exception.UnknownEnvNames(", ".join(unknown),
                                            ", ".join(known))

        # clean obsolete .pioenvs dir
        if not disable_auto_clean:
            try:
                _clean_pioenvs_dir(util.get_pioenvs_dir())
            except:  # pylint: disable=bare-except
                click.secho(
                    "Can not remove temporary directory `%s`. Please remove "
                    "`.pioenvs` directory from the project manually to avoid "
                    "build issues" % util.get_pioenvs_dir(),
                    fg="yellow")

        results = []
        for section in config.sections():
            # skip main configuration section
            if section == "platformio":
                continue

            if not section.startswith("env:"):
                raise exception.InvalidEnvName(section)

            envname = section[4:]
            if environment and envname not in environment:
                # echo("Skipped %s environment" % style(envname, fg="yellow"))
                continue

            if results:
                click.echo()

            options = {}
            for k, v in config.items(section):
                options[k] = v

            ep = EnvironmentProcessor(ctx, envname, options, target,
                                      upload_port, verbose)
            results.append(ep.process())

        if not all(results):
            raise exception.ReturnErrorCode()
Ejemplo n.º 12
0
def generate_user_kernel(kernel_user_dir, program_path):
    if not isdir(kernel_user_dir):
        makedirs(kernel_user_dir)
    args = [program_path]
    if "pulp-os" not in env.subst("$PIOFRAMEWORK"):
        args.append("-m")
    with util.cd(kernel_user_dir):
        env.Execute(env.VerboseAction(" ".join(args), "Running AutoTiler"))
    print("")
Ejemplo n.º 13
0
def get_first_board(project_dir):
    with util.cd(project_dir):
        config = util.get_project_config()
        for section in config.sections():
            if not section.startswith("env:"):
                continue
            elif config.has_option(section, "board"):
                return config.get(section, "board")
    return None
Ejemplo n.º 14
0
 def run(self):
     with util.cd(self.options['project_dir']):
         build_dir = get_project_build_dir()
     result = util.exec_command(
         [join(build_dir, self.env_name, "program")],
         stdout=LineBufferedAsyncPipe(self.on_run_out),
         stderr=LineBufferedAsyncPipe(self.on_run_out))
     assert "returncode" in result
     return result['returncode'] == 0 and not self._run_failed
Ejemplo n.º 15
0
def get_first_board(project_dir):
    with util.cd(project_dir):
        config = util.get_project_config()
        for section in config.sections():
            if not section.startswith("env:"):
                continue
            elif config.has_option(section, "board"):
                return config.get(section, "board")
    return None
Ejemplo n.º 16
0
 def process_extra_options(self):
     with util.cd(self.path):
         self.env.ProcessUnFlags(self.build_unflags)
         self.env.ProcessFlags(self.build_flags)
         if self.extra_script:
             self.env.SConscript(
                 realpath(self.extra_script),
                 exports={"env": self.env,
                          "pio_lib_builder": self})
Ejemplo n.º 17
0
    def __init__(self, project_dir, ide, env_name):
        self.project_dir = project_dir
        self.ide = ide
        self.env_name = env_name
        self._tplvars = {}

        with util.cd(self.project_dir):
            self.project_src_dir = util.get_projectsrc_dir()

        self._gather_tplvars()
Ejemplo n.º 18
0
    def __init__(self, project_dir, ide, board):
        self.project_dir = project_dir
        self.ide = ide
        self.board = board
        self._tplvars = {}

        with util.cd(self.project_dir):
            self.project_src_dir = util.get_projectsrc_dir()

        self._gather_tplvars()
Ejemplo n.º 19
0
    def __init__(self, project_dir, ide, board):
        self.project_dir = project_dir
        self.ide = ide
        self.board = board
        self._tplvars = {}

        with util.cd(self.project_dir):
            self.project_src_dir = util.get_projectsrc_dir()

        self._gather_tplvars()
Ejemplo n.º 20
0
    def __init__(self, project_dir, ide, env_name):
        self.project_dir = project_dir
        self.ide = ide
        self.env_name = env_name
        self._tplvars = {}

        with util.cd(self.project_dir):
            self.project_src_dir = util.get_projectsrc_dir()

        self._gather_tplvars()
Ejemplo n.º 21
0
 def process_extra_options(self):
     with util.cd(self.path):
         self.env.ProcessUnFlags(self.build_unflags)
         self.env.ProcessFlags(self.build_flags)
         if self.extra_script:
             self.env.SConscriptChdir(1)
             self.env.SConscript(
                 realpath(self.extra_script),
                 exports={"env": self.env,
                          "pio_lib_builder": self})
Ejemplo n.º 22
0
def GetExtraScripts(env, scope):
    items = []
    for item in env.get("EXTRA_SCRIPTS", []):
        if scope == "post" and ":" not in item:
            items.append(item)
        elif item.startswith("%s:" % scope):
            items.append(item[len(scope) + 1:])
    if not items:
        return items
    with util.cd(env.subst("$PROJECT_DIR")):
        return [realpath(item) for item in items]
Ejemplo n.º 23
0
def cli(ctx, environment, target, upload_port,  # pylint: disable=R0913,R0914
        project_dir, verbose, disable_auto_clean):
    with util.cd(project_dir):
        config = util.get_project_config()

        if not config.sections():
            raise exception.ProjectEnvsNotAvailable()

        known = set([s[4:] for s in config.sections()
                     if s.startswith("env:")])
        unknown = set(environment) - known
        if unknown:
            raise exception.UnknownEnvNames(
                ", ".join(unknown), ", ".join(known))

        # clean obsolete .pioenvs dir
        if not disable_auto_clean:
            try:
                _clean_pioenvs_dir(util.get_pioenvs_dir())
            except:  # pylint: disable=bare-except
                click.secho(
                    "Can not remove temporary directory `%s`. Please remove "
                    "`.pioenvs` directory from the project manually to avoid "
                    "build issues" % util.get_pioenvs_dir(),
                    fg="yellow"
                )

        results = []
        for section in config.sections():
            # skip main configuration section
            if section == "platformio":
                continue

            if not section.startswith("env:"):
                raise exception.InvalidEnvName(section)

            envname = section[4:]
            if environment and envname not in environment:
                # echo("Skipped %s environment" % style(envname, fg="yellow"))
                continue

            if results:
                click.echo()

            options = {}
            for k, v in config.items(section):
                options[k] = v

            ep = EnvironmentProcessor(
                ctx, envname, options, target, upload_port, verbose)
            results.append(ep.process())

        if not all(results):
            raise exception.ReturnErrorCode()
Ejemplo n.º 24
0
 def get_project_env(self):
     data = {"env_name": "PlatformIO"}
     with util.cd(self.project_dir):
         config = util.get_project_config()
         for section in config.sections():
             if not section.startswith("env:"):
                 continue
             data['env_name'] = section[4:]
             for k, v in config.items(section):
                 data[k] = v
     return data
Ejemplo n.º 25
0
def run(
        ctx=None,
        environment=(),
        target=(),
        upload_port=None,  # pylint: disable=R0913,R0914
        project_dir=os.getcwd(),
        verbose=3,
        disable_auto_clean=False):
    with util.cd(project_dir):
        config = util.get_project_config()

        if not config.sections():
            raise exception.ProjectEnvsNotAvailable()

        known = set([s[4:] for s in config.sections() if s.startswith("env:")])
        unknown = set(environment) - known
        if unknown:
            raise exception.UnknownEnvNames(", ".join(unknown),
                                            ", ".join(known))

        # clean obsolete .pioenvs dir
        if not disable_auto_clean:
            try:
                _clean_pioenvs_dir(util.get_pioenvs_dir())
            except Exception:
                raise exception.CleanPioenvsDirError(util.get_pioenvs_dir())

        results = []
        for section in config.sections():
            # skip main configuration section
            if section == "platformio":
                continue

            if not section.startswith("env:"):
                raise exception.InvalidEnvName(section)

            envname = section[4:]
            if environment and envname not in environment:
                # echo("Skipped %s environment" % style(envname, fg="yellow"))
                continue

            if results:
                click.echo()

            options = {}
            for k, v in config.items(section):
                options[k] = v

            ep = EnvironmentProcessor(ctx, envname, options, target,
                                      upload_port, verbose)
            results.append(ep.process(
            ))  # [JORGE_GARCIA] modified to get process description

        return results
Ejemplo n.º 26
0
 def get_project_env(self):
     data = {"env_name": "PlatformIO"}
     with util.cd(self.project_dir):
         config = util.get_project_config()
         for section in config.sections():
             if not section.startswith("env:"):
                 continue
             data['env_name'] = section[4:]
             for k, v in config.items(section):
                 data[k] = v
     return data
Ejemplo n.º 27
0
def GetExtraScripts(env, scope):
    items = []
    for item in env.get("EXTRA_SCRIPTS", []):
        if scope == "post" and ":" not in item:
            items.append(item)
        elif item.startswith("%s:" % scope):
            items.append(item[len(scope) + 1:])
    if not items:
        return items
    with util.cd(env.subst("$PROJECT_DIR")):
        return [realpath(item) for item in items]
Ejemplo n.º 28
0
def run(
    ctx=None,
    environment=(),
    target=(),
    upload_port=None,  # pylint: disable=R0913,R0914
    project_dir=os.getcwd(),
    verbose=3,
    disable_auto_clean=False,
):
    with util.cd(project_dir):
        config = util.get_project_config()

        if not config.sections():
            raise exception.ProjectEnvsNotAvailable()

        known = set([s[4:] for s in config.sections() if s.startswith("env:")])
        unknown = set(environment) - known
        if unknown:
            raise exception.UnknownEnvNames(", ".join(unknown), ", ".join(known))

        # clean obsolete .pioenvs dir
        if not disable_auto_clean:
            try:
                _clean_pioenvs_dir(util.get_pioenvs_dir())
            except Exception:
                raise exception.CleanPioenvsDirError(util.get_pioenvs_dir())

        results = []
        for section in config.sections():
            # skip main configuration section
            if section == "platformio":
                continue

            if not section.startswith("env:"):
                raise exception.InvalidEnvName(section)

            envname = section[4:]
            if environment and envname not in environment:
                # echo("Skipped %s environment" % style(envname, fg="yellow"))
                continue

            if results:
                click.echo()

            options = {}
            for k, v in config.items(section):
                options[k] = v

            ep = EnvironmentProcessor(ctx, envname, options, target, upload_port, verbose)
            results.append(ep.process())  # [JORGE_GARCIA] modified to get process description

        return results
Ejemplo n.º 29
0
 def get_project_env(self):
     data = {"env_name": "PlatformIO"}
     with util.cd(self.project_dir):
         config = util.get_project_config()
         for section in config.sections():
             if not section.startswith("env:"):
                 continue
             data = {"env_name": section[4:]}
             for k, v in config.items(section):
                 data[k] = v
             if self.board and self.board == data.get("board"):
                 break
     return data
Ejemplo n.º 30
0
 def get_project_env(self):
     data = {"env_name": "PlatformIO"}
     with util.cd(self.project_dir):
         config = util.get_project_config()
         for section in config.sections():
             if not section.startswith("env:"):
                 continue
             data = {"env_name": section[4:]}
             for k, v in config.items(section):
                 data[k] = v
             if self.board and self.board == data.get("board"):
                 break
     return data
Ejemplo n.º 31
0
def init_base_project(project_dir):
    ProjectConfig(join(project_dir, "platformio.ini")).save()
    with util.cd(project_dir):
        dir_to_readme = [
            (get_project_src_dir(), None),
            (get_project_include_dir(), init_include_readme),
            (get_project_lib_dir(), init_lib_readme),
            (get_project_test_dir(), init_test_readme),
        ]
        for (path, cb) in dir_to_readme:
            if isdir(path):
                continue
            makedirs(path)
            if cb:
                cb(path)
Ejemplo n.º 32
0
def init_base_project(project_dir):
    if not util.is_platformio_project(project_dir):
        copyfile(join(util.get_source_dir(), "projectconftpl.ini"),
                 join(project_dir, "platformio.ini"))

    with util.cd(project_dir):
        lib_dir = util.get_projectlib_dir()
        src_dir = util.get_projectsrc_dir()
        for d in (src_dir, lib_dir):
            if not isdir(d):
                makedirs(d)

    init_lib_readme(lib_dir)
    init_ci_conf(project_dir)
    init_cvs_ignore(project_dir)
Ejemplo n.º 33
0
    def add_project_items(self, psync):
        with util.cd(self.options["project_dir"]):
            cfg = ProjectConfig.get_instance(
                os.path.join(self.options["project_dir"], "platformio.ini"))
            psync.add_item(cfg.path, "platformio.ini")
            psync.add_item(cfg.get_optional_dir("shared"), "shared")
            psync.add_item(cfg.get_optional_dir("boards"), "boards")

            if self.options["force_remote"]:
                self._add_project_source_items(cfg, psync)
            else:
                self._add_project_binary_items(cfg, psync)

            if self.command == "test":
                psync.add_item(cfg.get_optional_dir("test"), "test")
Ejemplo n.º 34
0
def cli(
        ctx,
        environment,
        target,
        upload_port,  # pylint: disable=R0913,R0914
        project_dir,
        verbose):
    with util.cd(project_dir):
        config = util.get_project_config()

        if not config.sections():
            raise exception.ProjectEnvsNotAvailable()

        unknown = set(environment) - set([s[4:] for s in config.sections()])
        if unknown:
            raise exception.UnknownEnvNames(", ".join(unknown))

        # clean obsolete .pioenvs dir
        _clean_pioenvs_dir()

        results = []
        for section in config.sections():
            # skip main configuration section
            if section == "platformio":
                continue

            if not section.startswith("env:"):
                raise exception.InvalidEnvName(section)

            envname = section[4:]
            if environment and envname not in environment:
                # echo("Skipped %s environment" % style(envname, fg="yellow"))
                continue

            if results:
                click.echo()

            options = {}
            for k, v in config.items(section):
                options[k] = v

            ep = EnvironmentProcessor(ctx, envname, options, target,
                                      upload_port, verbose)
            results.append(ep.process())

        if not all(results):
            raise exception.ReturnErrorCode()
Ejemplo n.º 35
0
def cli(ctx, **options):
    storage_cmds = ("install", "uninstall", "update", "list")
    # skip commands that don't need storage folder
    if ctx.invoked_subcommand not in storage_cmds or \
            (len(ctx.args) == 2 and ctx.args[1] in ("-h", "--help")):
        return
    storage_dirs = list(options['storage_dir'])
    if options['global']:
        storage_dirs.append(get_project_global_lib_dir())
    if not storage_dirs:
        if is_platformio_project():
            storage_dirs = [get_project_dir()]
        elif is_ci():
            storage_dirs = [get_project_global_lib_dir()]
            click.secho(
                "Warning! Global library storage is used automatically. "
                "Please use `platformio lib --global %s` command to remove "
                "this warning." % ctx.invoked_subcommand,
                fg="yellow")

    if not storage_dirs:
        raise exception.NotGlobalLibDir(get_project_dir(),
                                        get_project_global_lib_dir(),
                                        ctx.invoked_subcommand)

    in_silence = PlatformioCLI.in_silence()
    ctx.meta[CTX_META_PROJECT_ENVIRONMENTS_KEY] = options['environment']
    ctx.meta[CTX_META_INPUT_DIRS_KEY] = storage_dirs
    ctx.meta[CTX_META_STORAGE_DIRS_KEY] = []
    ctx.meta[CTX_META_STORAGE_LIBDEPS_KEY] = {}
    for storage_dir in storage_dirs:
        if not is_platformio_project(storage_dir):
            ctx.meta[CTX_META_STORAGE_DIRS_KEY].append(storage_dir)
            continue
        with util.cd(storage_dir):
            libdeps_dir = get_project_libdeps_dir()
        config = ProjectConfig.get_instance(join(storage_dir,
                                                 "platformio.ini"))
        config.validate(options['environment'], silent=in_silence)
        for env in config.envs():
            if options['environment'] and env not in options['environment']:
                continue
            storage_dir = join(libdeps_dir, env)
            ctx.meta[CTX_META_STORAGE_DIRS_KEY].append(storage_dir)
            ctx.meta[CTX_META_STORAGE_LIBDEPS_KEY][storage_dir] = config.get(
                "env:" + env, "lib_deps", [])
Ejemplo n.º 36
0
 def _gather_tplvars(self):
     self._tplvars.update(self.get_project_env())
     self._tplvars.update(self.get_project_build_data())
     with util.cd(self.project_dir):
         self._tplvars.update({
             "project_name": self.get_project_name(),
             "src_files": self.get_src_files(),
             "user_home_dir": abspath(expanduser("~")),
             "project_dir": self.project_dir,
             "project_src_dir": util.get_projectsrc_dir(),
             "project_lib_dir": util.get_projectlib_dir(),
             "project_libdeps_dir": util.get_projectlibdeps_dir(),
             "systype": util.get_systype(),
             "platformio_path": self._fix_os_path(
                 util.where_is_program("platformio")),
             "env_pathsep": os.pathsep,
             "env_path": self._fix_os_path(os.getenv("PATH"))
         })  # yapf: disable
Ejemplo n.º 37
0
def init_base_project(project_dir):
    platformio_ini = join(project_dir, "platformio.ini")
    if not isfile(platformio_ini):
        copyfile(join(get_source_dir(), "projectconftpl.ini"), platformio_ini)

    lib_dir = join(project_dir, "lib")
    src_dir = join(project_dir, "src")
    with util.cd(project_dir):
        config = util.get_project_config()
        if config.has_option("platformio", "src_dir"):
            src_dir = join(project_dir, config.get("platformio", "src_dir"))

    for d in (src_dir, lib_dir):
        if not isdir(d):
            makedirs(d)

    init_lib_readme(lib_dir)
    init_ci_conf(project_dir)
    init_cvs_ignore(project_dir)
Ejemplo n.º 38
0
 def _gather_tplvars(self):
     self._tplvars.update(self.get_project_env())
     self._tplvars.update(self.get_project_build_data())
     with util.cd(self.project_dir):
         self._tplvars.update({
             "project_name": self.get_project_name(),
             "src_files": self.get_src_files(),
             "user_home_dir": abspath(expanduser("~")),
             "project_dir": self.project_dir,
             "project_src_dir": util.get_projectsrc_dir(),
             "project_lib_dir": util.get_projectlib_dir(),
             "project_libdeps_dir": util.get_projectlibdeps_dir(),
             "systype": util.get_systype(),
             "platformio_path": self._fix_os_path(
                 sys.argv[0] if isfile(sys.argv[0])
                 else util.where_is_program("platformio")),
             "env_pathsep": os.pathsep,
             "env_path": self._fix_os_path(os.getenv("PATH"))
         })  # yapf: disable
Ejemplo n.º 39
0
def init_base_project(project_dir):
    if util.is_platformio_project(project_dir):
        return

    copyfile(join(util.get_source_dir(), "projectconftpl.ini"),
             join(project_dir, "platformio.ini"))

    with util.cd(project_dir):
        dir_to_readme = [
            (util.get_projectsrc_dir(), None),
            (util.get_projectinclude_dir(), init_include_readme),
            (util.get_projectlib_dir(), init_lib_readme),
            (util.get_projecttest_dir(), init_test_readme),
        ]
        for (path, cb) in dir_to_readme:
            if isdir(path):
                continue
            makedirs(path)
            if cb:
                cb(path)
Ejemplo n.º 40
0
 def _generate_project_main(_, project_dir, framework):
     main_content = None
     if framework == "arduino":
         main_content = "\n".join([
             "#include <Arduino.h>",
             "",
             "void setup() {",
             "  // put your setup code here, to run once:",
             "}",
             "",
             "void loop() {",
             "  // put your main code here, to run repeatedly:",
             "}"
             ""
         ])   # yapf: disable
     elif framework == "mbed":
         main_content = "\n".join([
             "#include <mbed.h>",
             "",
             "int main() {",
             "",
             "  // put your setup code here, to run once:",
             "",
             "  while(1) {",
             "    // put your main code here, to run repeatedly:",
             "  }",
             "}",
             ""
         ])   # yapf: disable
     if not main_content:
         return project_dir
     with util.cd(project_dir):
         src_dir = get_project_src_dir()
         main_path = join(src_dir, "main.cpp")
         if isfile(main_path):
             return project_dir
         if not isdir(src_dir):
             os.makedirs(src_dir)
         with open(main_path, "w") as f:
             f.write(main_content.strip())
     return project_dir
Ejemplo n.º 41
0
def cli(ctx, environment, target, upload_port, project_dir, verbose, disable_auto_clean):  # pylint: disable=R0913,R0914
    with util.cd(project_dir):
        config = util.get_project_config()

        if not config.sections():
            raise exception.ProjectEnvsNotAvailable()

        unknown = set(environment) - set([s[4:] for s in config.sections()])
        if unknown:
            raise exception.UnknownEnvNames(", ".join(unknown))

        # clean obsolete .pioenvs dir
        if not disable_auto_clean:
            _clean_pioenvs_dir()

        results = []
        for section in config.sections():
            # skip main configuration section
            if section == "platformio":
                continue

            if not section.startswith("env:"):
                raise exception.InvalidEnvName(section)

            envname = section[4:]
            if environment and envname not in environment:
                # echo("Skipped %s environment" % style(envname, fg="yellow"))
                continue

            if results:
                click.echo()

            options = {}
            for k, v in config.items(section):
                options[k] = v

            ep = EnvironmentProcessor(ctx, envname, options, target, upload_port, verbose)
            results.append(ep.process())

        if not all(results):
            raise exception.ReturnErrorCode()
Ejemplo n.º 42
0
def init_base_project(project_dir):
    if util.is_platformio_project(project_dir):
        return

    copyfile(
        join(util.get_source_dir(), "projectconftpl.ini"),
        join(project_dir, "platformio.ini"))

    with util.cd(project_dir):
        dir_to_readme = [
            (util.get_projectsrc_dir(), None),
            (util.get_projectinclude_dir(), init_include_readme),
            (util.get_projectlib_dir(), init_lib_readme),
            (util.get_projecttest_dir(), init_test_readme),
        ]
        for (path, cb) in dir_to_readme:
            if isdir(path):
                continue
            makedirs(path)
            if cb:
                cb(path)
Ejemplo n.º 43
0
def extract_files(cppdefines):
    for define in cppdefines:
        if "COMPONENT_EMBED_TXTFILES" not in define:
            continue

        if not isinstance(define, tuple):
            print("Warning! COMPONENT_EMBED_TXTFILES macro cannot be empty!")
            return []

        with cd(env.subst("$PROJECT_DIR")):
            value = define[1]
            if not isinstance(value, str):
                print("Warning! COMPONENT_EMBED_TXTFILES macro must contain "
                      "a list of files separated by ':'")
                return []

            result = []
            for f in value.split(':'):
                if not isfile(f):
                    print("Warning! Could not find file %s" % f)
                    continue
                result.append(join("$PROJECT_DIR", f))

            return result
Ejemplo n.º 44
0
    def _get_build_options(board):
        """
        :type board: str
            """
        with util.cd(pm.PLATFORMIO_WORKSPACE_PATH):
            config = util.get_project_config()

            if not config.sections():
                raise exception.ProjectEnvsNotAvailable()

            known = set([s[4:] for s in config.sections()
                         if s.startswith("env:")])
            unknown = set((board,)) - known
            if unknown:
                return None

            for section in config.sections():
                envName = section[4:]
                if board and envName and envName == board:
                    build_options = {k: v for k, v in config.items(section)}
                    build_options["boardData"] = get_boards(build_options["board"])
                    return build_options

            raise CompilerException(ERROR_BOARD_NOT_SUPPORTED, board)
Ejemplo n.º 45
0
def cli(ctx, environment, target, upload_port, project_dir, silent, verbose,
        disable_auto_clean):
    # find project directory on upper level
    if isfile(project_dir):
        project_dir = util.find_project_dir_above(project_dir)

    if not util.is_platformio_project(project_dir):
        raise exception.NotPlatformIOProject(project_dir)

    with util.cd(project_dir):
        # clean obsolete .pioenvs dir
        if not disable_auto_clean:
            try:
                _clean_pioenvs_dir(util.get_projectpioenvs_dir())
            except:  # pylint: disable=bare-except
                click.secho(
                    "Can not remove temporary directory `%s`. Please remove "
                    "`.pioenvs` directory from the project manually to avoid "
                    "build issues" % util.get_projectpioenvs_dir(force=True),
                    fg="yellow")

        config = util.load_project_config()
        check_project_defopts(config)
        assert check_project_envs(config, environment)

        env_default = None
        if config.has_option("platformio", "env_default"):
            env_default = [
                e.strip()
                for e in config.get("platformio", "env_default").split(", ")
            ]

        results = []
        start_time = time()
        for section in config.sections():
            if not section.startswith("env:"):
                continue

            envname = section[4:]
            skipenv = any([
                environment and envname not in environment, not environment
                and env_default and envname not in env_default
            ])
            if skipenv:
                results.append((envname, None))
                continue

            if not silent and results:
                click.echo()

            options = {}
            for k, v in config.items(section):
                options[k] = v
            if "piotest" not in options and "piotest" in ctx.meta:
                options['piotest'] = ctx.meta['piotest']

            ep = EnvironmentProcessor(ctx, envname, options, target,
                                      upload_port, silent, verbose)
            result = (envname, ep.process())
            results.append(result)
            if result[1] and "monitor" in ep.get_build_targets() and \
                    "nobuild" not in ep.get_build_targets():
                ctx.invoke(cmd_device_monitor)

        found_error = any([status is False for (_, status) in results])

        if (found_error or not silent) and len(results) > 1:
            click.echo()
            print_summary(results, start_time)

        if found_error:
            raise exception.ReturnErrorCode(1)
        return True
Ejemplo n.º 46
0
def cli(ctx, environment, target, upload_port, project_dir, silent, verbose, disable_auto_clean):
    # find project directory on upper level
    if isfile(project_dir):
        project_dir = util.find_project_dir_above(project_dir)

    if not util.is_platformio_project(project_dir):
        raise exception.NotPlatformIOProject(project_dir)

    with util.cd(project_dir):
        # clean obsolete .pioenvs dir
        if not disable_auto_clean:
            try:
                _clean_pioenvs_dir(util.get_projectpioenvs_dir())
            except:  # pylint: disable=bare-except
                click.secho(
                    "Can not remove temporary directory `%s`. Please remove "
                    "`.pioenvs` directory from the project manually to avoid "
                    "build issues" % util.get_projectpioenvs_dir(force=True),
                    fg="yellow",
                )

        config = util.load_project_config()
        check_project_defopts(config)
        assert check_project_envs(config, environment)

        env_default = None
        if config.has_option("platformio", "env_default"):
            env_default = [e.strip() for e in config.get("platformio", "env_default").split(",")]

        results = []
        start_time = time()
        for section in config.sections():
            if not section.startswith("env:"):
                continue

            envname = section[4:]
            skipenv = any(
                [
                    environment and envname not in environment,
                    not environment and env_default and envname not in env_default,
                ]
            )
            if skipenv:
                results.append((envname, None))
                continue

            if results:
                click.echo()

            options = {}
            for k, v in config.items(section):
                options[k] = v
            if "piotest" not in options and "piotest" in ctx.meta:
                options["piotest"] = ctx.meta["piotest"]

            ep = EnvironmentProcessor(ctx, envname, options, target, upload_port, silent, verbose)
            results.append((envname, ep.process()))

        if len(results) > 1:
            click.echo()
            print_summary(results, start_time)

        if any([status is False for (_, status) in results]):
            raise exception.ReturnErrorCode(1)
        return True
Ejemplo n.º 47
0
def cli(ctx, environment, target, upload_port, project_dir, silent, verbose,
        disable_auto_clean):
    # find project directory on upper level
    if isfile(project_dir):
        project_dir = util.find_project_dir_above(project_dir)

    if not util.is_platformio_project(project_dir):
        raise exception.NotPlatformIOProject(project_dir)

    with util.cd(project_dir):
        # clean obsolete build dir
        if not disable_auto_clean:
            try:
                _clean_build_dir(util.get_projectbuild_dir())
            except:  # pylint: disable=bare-except
                click.secho(
                    "Can not remove temporary directory `%s`. Please remove "
                    "it manually to avoid build issues" %
                    util.get_projectbuild_dir(force=True),
                    fg="yellow")

        config = util.load_project_config()
        env_default = None
        if config.has_option("platformio", "env_default"):
            env_default = util.parse_conf_multi_values(
                config.get("platformio", "env_default"))

        check_project_defopts(config)
        check_project_envs(config, environment or env_default)

        results = []
        start_time = time()
        for section in config.sections():
            if not section.startswith("env:"):
                continue

            envname = section[4:]
            skipenv = any([
                environment and envname not in environment, not environment
                and env_default and envname not in env_default
            ])
            if skipenv:
                results.append((envname, None))
                continue

            if not silent and results:
                click.echo()

            options = {}
            for k, v in config.items(section):
                options[k] = v
            if "piotest" not in options and "piotest" in ctx.meta:
                options['piotest'] = ctx.meta['piotest']

            ep = EnvironmentProcessor(ctx, envname, options, target,
                                      upload_port, silent, verbose)
            result = (envname, ep.process())
            results.append(result)
            if result[1] and "monitor" in ep.get_build_targets() and \
                    "nobuild" not in ep.get_build_targets():
                ctx.invoke(
                    cmd_device_monitor,
                    environment=environment[0] if environment else None)

        found_error = any(status is False for (_, status) in results)

        if (found_error or not silent) and len(results) > 1:
            click.echo()
            print_summary(results, start_time)

        if found_error:
            raise exception.ReturnErrorCode(1)
        return True