예제 #1
0
    def _call_generator(args, options=None):
        for i, arg in enumerate(args):
            if isinstance(arg, string_types):
                args[i] = arg.encode(get_filesystem_encoding()) if PY2 else arg
            else:
                args[i] = str(arg)

        to_json = "--json-output" in args

        try:
            if args and args[0] in ("account", "remote"):
                result = yield PIOCoreRPC._call_subprocess(args, options)
                defer.returnValue(PIOCoreRPC._process_result(result, to_json))
            else:
                result = yield PIOCoreRPC._call_inline(args, options)
                try:
                    defer.returnValue(
                        PIOCoreRPC._process_result(result, to_json))
                except ValueError:
                    # fall-back to subprocess method
                    result = yield PIOCoreRPC._call_subprocess(args, options)
                    defer.returnValue(
                        PIOCoreRPC._process_result(result, to_json))
        except Exception as e:  # pylint: disable=bare-except
            raise jsonrpc.exceptions.JSONRPCDispatchException(
                code=4003, message="PIO Core Call Error", data=str(e))
예제 #2
0
 def read_safe_contents(self, path):
     error_reported = False
     for encoding in (
             "utf-8",
             None,
             get_filesystem_encoding(),
             get_locale_encoding(),
             "latin-1",
     ):
         try:
             with io.open(path, encoding=encoding) as fp:
                 contents = fp.read()
                 self._safe_encoding = encoding
                 return contents
         except UnicodeDecodeError:
             if not error_reported:
                 error_reported = True
                 click.secho(
                     "Unicode decode error has occurred, please remove invalid "
                     "(non-ASCII or non-UTF8) characters from %s file or convert it to UTF-8"
                     % path,
                     fg="yellow",
                     err=True,
                 )
     return ""
예제 #3
0
def exec_command(*args, **kwargs):
    result = {"out": None, "err": None, "returncode": None}

    default = dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    default.update(kwargs)
    kwargs = default

    p = subprocess.Popen(*args, **kwargs)
    try:
        result["out"], result["err"] = p.communicate()
        result["returncode"] = p.returncode
    except KeyboardInterrupt:
        raise exception.AbortedByUser()
    finally:
        for s in ("stdout", "stderr"):
            if isinstance(kwargs[s], AsyncPipeBase):
                kwargs[s].close()

    for s in ("stdout", "stderr"):
        if isinstance(kwargs[s], AsyncPipeBase):
            result[s[3:]] = kwargs[s].get_buffer()

    for k, v in result.items():
        if PY2 and isinstance(v, unicode):  # pylint: disable=undefined-variable
            result[k] = v.encode()
        elif not PY2 and isinstance(result[k], bytes):
            try:
                result[k] = result[k].decode(get_locale_encoding()
                                             or get_filesystem_encoding())
            except UnicodeDecodeError:
                result[k] = result[k].decode("latin-1")
        if v and isinstance(v, string_types):
            result[k] = result[k].strip()

    return result
예제 #4
0
    def call(args, options=None):
        PIOCoreRPC.setup_multithreading_std_streams()
        cwd = (options or {}).get("cwd") or os.getcwd()
        for i, arg in enumerate(args):
            if isinstance(arg, string_types):
                args[i] = arg.encode(get_filesystem_encoding()) if PY2 else arg
            else:
                args[i] = str(arg)

        def _call_inline():
            with util.cd(cwd):
                exit_code = __main__.main(["-c"] + args)
            return (PIOCoreRPC.thread_stdout.get_value_and_reset(),
                    PIOCoreRPC.thread_stderr.get_value_and_reset(), exit_code)

        if args and args[0] in ("account", "remote"):
            d = utils.getProcessOutputAndValue(
                helpers.get_core_fullpath(),
                args,
                path=cwd,
                env={k: v
                     for k, v in os.environ.items() if "%" not in k})
        else:
            d = threads.deferToThread(_call_inline)

        d.addCallback(PIOCoreRPC._call_callback, "--json-output" in args)
        d.addErrback(PIOCoreRPC._call_errback)
        return d
예제 #5
0
def system_info(json_output):
    project_config = ProjectConfig()
    data = {}
    data["core_version"] = {"title": "PlatformIO Core", "value": __version__}
    data["python_version"] = {
        "title": "Python",
        "value": "{0}.{1}.{2}-{3}.{4}".format(*list(sys.version_info)),
    }
    data["system"] = {"title": "System Type", "value": util.get_systype()}
    data["platform"] = {
        "title": "Platform",
        "value": platform.platform(terse=True)
    }
    data["filesystem_encoding"] = {
        "title": "File System Encoding",
        "value": compat.get_filesystem_encoding(),
    }
    data["locale_encoding"] = {
        "title": "Locale Encoding",
        "value": compat.get_locale_encoding(),
    }
    data["core_dir"] = {
        "title": "PlatformIO Core Directory",
        "value": project_config.get_optional_dir("core"),
    }
    data["platformio_exe"] = {
        "title":
        "PlatformIO Core Executable",
        "value":
        proc.where_is_program(
            "platformio.exe" if proc.WINDOWS else "platformio"),
    }
    data["python_exe"] = {
        "title": "Python Executable",
        "value": proc.get_pythonexe_path(),
    }
    data["global_lib_nums"] = {
        "title": "Global Libraries",
        "value": len(LibraryPackageManager().get_installed()),
    }
    data["dev_platform_nums"] = {
        "title": "Development Platforms",
        "value": len(PlatformPackageManager().get_installed()),
    }
    data["package_tool_nums"] = {
        "title":
        "Tools & Toolchains",
        "value":
        len(
            ToolPackageManager(
                project_config.get_optional_dir("packages")).get_installed()),
    }

    click.echo(
        json.dumps(data) if json_output else tabulate([(
            item["title"], item["value"]) for item in data.values()]))
예제 #6
0
    def import_arduino(self, board, use_arduino_libs, arduino_project_dir):
        board = str(board)
        if arduino_project_dir and PY2:
            arduino_project_dir = arduino_project_dir.encode(
                get_filesystem_encoding())
        # don't import PIO Project
        if is_platformio_project(arduino_project_dir):
            return arduino_project_dir

        is_arduino_project = any([
            os.path.isfile(
                os.path.join(
                    arduino_project_dir,
                    "%s.%s" % (os.path.basename(arduino_project_dir), ext),
                )) for ext in ("ino", "pde")
        ])
        if not is_arduino_project:
            raise jsonrpc.exceptions.JSONRPCDispatchException(
                code=4000,
                message="Not an Arduino project: %s" % arduino_project_dir)

        state = AppRPC.load_state()
        project_dir = os.path.join(state["storage"]["projectsDir"],
                                   time.strftime("%y%m%d-%H%M%S-") + board)
        if not os.path.isdir(project_dir):
            os.makedirs(project_dir)
        args = ["init", "--board", board]
        args.extend(["--project-option", "framework = arduino"])
        if use_arduino_libs:
            args.extend([
                "--project-option",
                "lib_extra_dirs = ~/Documents/Arduino/libraries"
            ])
        if (state["storage"]["coreCaller"] and state["storage"]["coreCaller"]
                in ProjectGenerator.get_supported_ides()):
            args.extend(["--ide", state["storage"]["coreCaller"]])
        d = PIOCoreRPC.call(args,
                            options={
                                "cwd": project_dir,
                                "force_subprocess": True
                            })
        d.addCallback(self._finalize_arduino_import, project_dir,
                      arduino_project_dir)
        return d
예제 #7
0
 def open_file(path):
     return click.launch(
         path.encode(get_filesystem_encoding()) if PY2 else path)
예제 #8
0
 def reveal_file(path):
     return click.launch(
         path.encode(get_filesystem_encoding()) if PY2 else path,
         locate=True)