diff --git a/platformio/__main__.py b/platformio/__main__.py index 0dc0cca1..f8358867 100644 --- a/platformio/__main__.py +++ b/platformio/__main__.py @@ -23,15 +23,13 @@ from platformio.commands import PlatformioCLI from platformio.compat import CYGWIN -@click.command( - cls=PlatformioCLI, - context_settings=dict(help_option_names=["-h", "--help"])) +@click.command(cls=PlatformioCLI, + context_settings=dict(help_option_names=["-h", "--help"])) @click.version_option(__version__, prog_name="PlatformIO") -@click.option( - "--force", - "-f", - is_flag=True, - help="Force to accept any confirmation prompts.") +@click.option("--force", + "-f", + is_flag=True, + help="Force to accept any confirmation prompts.") @click.option("--caller", "-c", help="Caller ID (service).") @click.pass_context def cli(ctx, force, caller): diff --git a/platformio/builder/tools/pioide.py b/platformio/builder/tools/pioide.py index 4c42ee88..1814f1b9 100644 --- a/platformio/builder/tools/pioide.py +++ b/platformio/builder/tools/pioide.py @@ -72,8 +72,9 @@ def _get_gcc_defines(env): try: sysenv = environ.copy() sysenv['PATH'] = str(env['ENV']['PATH']) - result = exec_command( - "echo | %s -dM -E -" % env.subst("$CC"), env=sysenv, shell=True) + result = exec_command("echo | %s -dM -E -" % env.subst("$CC"), + env=sysenv, + shell=True) except OSError: return items if result['returncode'] != 0: diff --git a/platformio/builder/tools/piolib.py b/platformio/builder/tools/piolib.py index dba7d108..5b2c2e2b 100644 --- a/platformio/builder/tools/piolib.py +++ b/platformio/builder/tools/piolib.py @@ -54,8 +54,9 @@ class LibBuilderFactory(object): elif used_frameworks: clsname = "%sLibBuilder" % used_frameworks[0].title() - obj = getattr(sys.modules[__name__], clsname)( - env, path, verbose=verbose) + obj = getattr(sys.modules[__name__], clsname)(env, + path, + verbose=verbose) assert isinstance(obj, LibBuilderBase) return obj @@ -69,8 +70,8 @@ class LibBuilderFactory(object): if isfile(join(path, "module.json")): return ["mbed"] - include_re = re.compile( - r'^#include\s+(<|")(Arduino|mbed)\.h(<|")', flags=re.MULTILINE) + include_re = re.compile(r'^#include\s+(<|")(Arduino|mbed)\.h(<|")', + flags=re.MULTILINE) # check source files for root, _, files in os.walk(path, followlinks=True): @@ -270,12 +271,11 @@ class LibBuilderBase(object): 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 - }) + self.env.SConscript(realpath(self.extra_script), + exports={ + "env": self.env, + "pio_lib_builder": self + }) self.env.ProcessUnFlags(self.build_unflags) def process_dependencies(self): @@ -290,8 +290,9 @@ class LibBuilderBase(object): if (key in item and not util.items_in_list(self.env[env_key], item[key])): if self.verbose: - sys.stderr.write("Skip %s incompatible dependency %s\n" - % (key[:-1], item)) + sys.stderr.write( + "Skip %s incompatible dependency %s\n" % + (key[:-1], item)) skip = True if skip: continue @@ -404,9 +405,9 @@ class LibBuilderBase(object): if self != lb: if _already_depends(lb): if self.verbose: - sys.stderr.write( - "Warning! Circular dependencies detected " - "between `%s` and `%s`\n" % (self.path, lb.path)) + sys.stderr.write("Warning! Circular dependencies detected " + "between `%s` and `%s`\n" % + (self.path, lb.path)) self._circular_deps.append(lb) elif lb not in self._depbuilders: self._depbuilders.append(lb) @@ -648,8 +649,8 @@ class MbedLibBuilder(LibBuilderBase): for key, options in manifest.get("config", {}).items(): if "value" not in options: continue - macros[key] = dict( - name=options.get("macro_name"), value=options.get("value")) + macros[key] = dict(name=options.get("macro_name"), + value=options.get("value")) # overrode items per target for target, options in manifest.get("target_overrides", {}).items(): @@ -669,8 +670,10 @@ class MbedLibBuilder(LibBuilderBase): if "." not in macro['name']: macro['name'] = "%s.%s" % (manifest.get("name"), macro['name']) - macro['name'] = re.sub( - r"[^a-z\d]+", "_", macro['name'], flags=re.I).upper() + macro['name'] = re.sub(r"[^a-z\d]+", + "_", + macro['name'], + flags=re.I).upper() macro['name'] = "MBED_CONF_" + macro['name'] if isinstance(macro['value'], bool): macro['value'] = 1 if macro['value'] else 0 @@ -686,8 +689,8 @@ class MbedLibBuilder(LibBuilderBase): lines.append( "// PlatformIO Library Dependency Finder (LDF)") lines.extend([ - "#define %s %s" % (name, - value if value is not None else "") + "#define %s %s" % + (name, value if value is not None else "") for name, value in macros.items() ]) lines.append("") @@ -919,9 +922,8 @@ def GetLibSourceDirs(env): def GetLibBuilders(env): # pylint: disable=too-many-branches if "__PIO_LIB_BUILDERS" in DefaultEnvironment(): - return sorted( - DefaultEnvironment()['__PIO_LIB_BUILDERS'], - key=lambda lb: 0 if lb.dependent else 1) + return sorted(DefaultEnvironment()['__PIO_LIB_BUILDERS'], + key=lambda lb: 0 if lb.dependent else 1) items = [] verbose = int(ARGUMENTS.get("PIOVERBOSE", @@ -936,14 +938,14 @@ def GetLibBuilders(env): # pylint: disable=too-many-branches if compat_mode == "strict" and not lb.is_platforms_compatible( env['PIOPLATFORM']): if verbose: - sys.stderr.write( - "Platform incompatible library %s\n" % lb.path) + sys.stderr.write("Platform incompatible library %s\n" % + lb.path) return False if compat_mode == "soft" and "PIOFRAMEWORK" in env and \ not lb.is_frameworks_compatible(env.get("PIOFRAMEWORK", [])): if verbose: - sys.stderr.write( - "Framework incompatible library %s\n" % lb.path) + sys.stderr.write("Framework incompatible library %s\n" % + lb.path) return False return True @@ -956,12 +958,14 @@ def GetLibBuilders(env): # pylint: disable=too-many-branches if item == "__cores__" or not isdir(join(libs_dir, item)): continue try: - lb = LibBuilderFactory.new( - env, join(libs_dir, item), verbose=verbose) + lb = LibBuilderFactory.new(env, + join(libs_dir, item), + verbose=verbose) except exception.InvalidJSONFile: if verbose: - sys.stderr.write("Skip library with broken manifest: %s\n" - % join(libs_dir, item)) + sys.stderr.write( + "Skip library with broken manifest: %s\n" % + join(libs_dir, item)) continue if _check_lib_builder(lb): items.append(lb) diff --git a/platformio/builder/tools/piomisc.py b/platformio/builder/tools/piomisc.py index 3d434955..cf538812 100644 --- a/platformio/builder/tools/piomisc.py +++ b/platformio/builder/tools/piomisc.py @@ -190,8 +190,8 @@ class InoToCPPConverter(object): def ConvertInoToCpp(env): src_dir = glob_escape(env.subst("$PROJECTSRC_DIR")) - ino_nodes = ( - env.Glob(join(src_dir, "*.ino")) + env.Glob(join(src_dir, "*.pde"))) + ino_nodes = (env.Glob(join(src_dir, "*.ino")) + + env.Glob(join(src_dir, "*.pde"))) if not ino_nodes: return c = InoToCPPConverter(env) @@ -297,8 +297,8 @@ def PioClean(env, clean_dir): def ProcessDebug(env): if not env.subst("$PIODEBUGFLAGS"): env.Replace(PIODEBUGFLAGS=["-Og", "-g3", "-ggdb3"]) - env.Append( - BUILD_FLAGS=list(env['PIODEBUGFLAGS']) + ["-D__PLATFORMIO_DEBUG__"]) + env.Append(BUILD_FLAGS=list(env['PIODEBUGFLAGS']) + + ["-D__PLATFORMIO_DEBUG__"]) unflags = ["-Os"] for level in [0, 1, 2]: for flag in ("O", "g", "ggdb"): @@ -307,11 +307,10 @@ def ProcessDebug(env): def ProcessTest(env): - env.Append( - CPPDEFINES=["UNIT_TEST", "UNITY_INCLUDE_CONFIG_H"], - CPPPATH=[join("$BUILD_DIR", "UnityTestLib")]) - unitylib = env.BuildLibrary( - join("$BUILD_DIR", "UnityTestLib"), get_core_package_dir("tool-unity")) + env.Append(CPPDEFINES=["UNIT_TEST", "UNITY_INCLUDE_CONFIG_H"], + CPPPATH=[join("$BUILD_DIR", "UnityTestLib")]) + unitylib = env.BuildLibrary(join("$BUILD_DIR", "UnityTestLib"), + get_core_package_dir("tool-unity")) env.Prepend(LIBS=[unitylib]) src_filter = ["+<*.cpp>", "+<*.c>"] diff --git a/platformio/builder/tools/pioplatform.py b/platformio/builder/tools/pioplatform.py index 144f1f4b..6d0d1c59 100644 --- a/platformio/builder/tools/pioplatform.py +++ b/platformio/builder/tools/pioplatform.py @@ -138,8 +138,8 @@ def PrintConfiguration(env): ram = board_config.get("upload", {}).get("maximum_ram_size") flash = board_config.get("upload", {}).get("maximum_size") hardware_data.append( - "%s RAM (%s Flash)" % (util.format_filesize(ram), - util.format_filesize(flash))) + "%s RAM (%s Flash)" % + (util.format_filesize(ram), util.format_filesize(flash))) configuration_data.append( "https://docs.platformio.org/page/boards/%s/%s.html" % (platform.name, board_config.id)) @@ -153,8 +153,8 @@ def PrintConfiguration(env): return data = [ - "CURRENT(%s)" % board_config.get_debug_tool_name( - env.GetProjectOption("debug_tool")) + "CURRENT(%s)" % + board_config.get_debug_tool_name(env.GetProjectOption("debug_tool")) ] onboard = [] external = [] diff --git a/platformio/builder/tools/pioupload.py b/platformio/builder/tools/pioupload.py index 6db94bfc..dd03894a 100644 --- a/platformio/builder/tools/pioupload.py +++ b/platformio/builder/tools/pioupload.py @@ -198,10 +198,9 @@ def CheckUploadSize(_, target, source, env): return def _configure_defaults(): - env.Replace( - SIZECHECKCMD="$SIZETOOL -B -d $SOURCES", - SIZEPROGREGEXP=r"^(\d+)\s+(\d+)\s+\d+\s", - SIZEDATAREGEXP=r"^\d+\s+(\d+)\s+(\d+)\s+\d+") + env.Replace(SIZECHECKCMD="$SIZETOOL -B -d $SOURCES", + SIZEPROGREGEXP=r"^(\d+)\s+(\d+)\s+\d+\s", + SIZEDATAREGEXP=r"^\d+\s+(\d+)\s+(\d+)\s+\d+") def _get_size_output(): cmd = env.get("SIZECHECKCMD") @@ -251,8 +250,8 @@ def CheckUploadSize(_, target, source, env): if data_max_size and data_size > -1: print("DATA: %s" % _format_availale_bytes(data_size, data_max_size)) if program_size > -1: - print("PROGRAM: %s" % _format_availale_bytes(program_size, - program_max_size)) + print("PROGRAM: %s" % + _format_availale_bytes(program_size, program_max_size)) if int(ARGUMENTS.get("PIOVERBOSE", 0)): print(output) @@ -273,8 +272,8 @@ def PrintUploadInfo(env): configured = env.subst("$UPLOAD_PROTOCOL") available = [configured] if configured else [] if "BOARD" in env: - available.extend(env.BoardConfig().get("upload", {}).get( - "protocols", [])) + available.extend(env.BoardConfig().get("upload", + {}).get("protocols", [])) if available: print("AVAILABLE: %s" % ", ".join(sorted(set(available)))) if configured: diff --git a/platformio/builder/tools/platformio.py b/platformio/builder/tools/platformio.py index 2d1fc0fd..f8f3656c 100644 --- a/platformio/builder/tools/platformio.py +++ b/platformio/builder/tools/platformio.py @@ -132,8 +132,8 @@ def BuildProgram(env): env.Prepend(_LIBFLAGS="-Wl,--start-group ") env.Append(_LIBFLAGS=" -Wl,--end-group") - program = env.Program( - join("$BUILD_DIR", env.subst("$PROGNAME")), env['PIOBUILDFILES']) + program = env.Program(join("$BUILD_DIR", env.subst("$PROGNAME")), + env['PIOBUILDFILES']) env.Replace(PIOMAINPROG=program) AlwaysBuild( diff --git a/platformio/commands/boards.py b/platformio/commands/boards.py index 5764b9f8..b48be4df 100644 --- a/platformio/commands/boards.py +++ b/platformio/commands/boards.py @@ -51,24 +51,22 @@ def print_boards(boards): BOARDLIST_TPL = ("{type:<30} {mcu:<14} {frequency:<8} " " {flash:<7} {ram:<6} {name}") click.echo( - BOARDLIST_TPL.format( - type=click.style("ID", fg="cyan"), - mcu="MCU", - frequency="Frequency", - flash="Flash", - ram="RAM", - name="Name")) + BOARDLIST_TPL.format(type=click.style("ID", fg="cyan"), + mcu="MCU", + frequency="Frequency", + flash="Flash", + ram="RAM", + name="Name")) click.echo("-" * terminal_width) for board in boards: click.echo( - BOARDLIST_TPL.format( - type=click.style(board['id'], fg="cyan"), - mcu=board['mcu'], - frequency="%dMHz" % (board['fcpu'] / 1000000), - flash=util.format_filesize(board['rom']), - ram=util.format_filesize(board['ram']), - name=board['name'])) + BOARDLIST_TPL.format(type=click.style(board['id'], fg="cyan"), + mcu=board['mcu'], + frequency="%dMHz" % (board['fcpu'] / 1000000), + flash=util.format_filesize(board['rom']), + ram=util.format_filesize(board['ram']), + name=board['name'])) def _get_boards(installed=False): diff --git a/platformio/commands/ci.py b/platformio/commands/ci.py index 7d97eb48..55ef07ad 100644 --- a/platformio/commands/ci.py +++ b/platformio/commands/ci.py @@ -48,26 +48,31 @@ def validate_path(ctx, param, value): # pylint: disable=unused-argument @click.command("ci", short_help="Continuous Integration") @click.argument("src", nargs=-1, callback=validate_path) -@click.option( - "-l", "--lib", multiple=True, callback=validate_path, metavar="DIRECTORY") +@click.option("-l", + "--lib", + multiple=True, + callback=validate_path, + metavar="DIRECTORY") @click.option("--exclude", multiple=True) -@click.option( - "-b", "--board", multiple=True, metavar="ID", callback=validate_boards) -@click.option( - "--build-dir", - default=mkdtemp, - type=click.Path( - file_okay=False, dir_okay=True, writable=True, resolve_path=True)) +@click.option("-b", + "--board", + multiple=True, + metavar="ID", + callback=validate_boards) +@click.option("--build-dir", + default=mkdtemp, + type=click.Path(file_okay=False, + dir_okay=True, + writable=True, + resolve_path=True)) @click.option("--keep-build-dir", is_flag=True) -@click.option( - "-c", - "--project-conf", - type=click.Path( - exists=True, - file_okay=True, - dir_okay=False, - readable=True, - resolve_path=True)) +@click.option("-c", + "--project-conf", + type=click.Path(exists=True, + file_okay=True, + dir_okay=False, + readable=True, + resolve_path=True)) @click.option("-O", "--project-option", multiple=True) @click.option("-v", "--verbose", is_flag=True) @click.pass_context @@ -105,11 +110,10 @@ def cli( # pylint: disable=too-many-arguments, too-many-branches _exclude_contents(build_dir, exclude) # initialise project - ctx.invoke( - cmd_init, - project_dir=build_dir, - board=board, - project_option=project_option) + ctx.invoke(cmd_init, + project_dir=build_dir, + board=board, + project_option=project_option) # process project ctx.invoke(cmd_run, project_dir=build_dir, verbose=verbose) diff --git a/platformio/commands/debug/client.py b/platformio/commands/debug/client.py index 4a950a7a..2631621e 100644 --- a/platformio/commands/debug/client.py +++ b/platformio/commands/debug/client.py @@ -52,8 +52,8 @@ class GDBClient(BaseProcess): # pylint: disable=too-many-instance-attributes if not isdir(get_project_cache_dir()): os.makedirs(get_project_cache_dir()) - self._gdbsrc_dir = mkdtemp( - dir=get_project_cache_dir(), prefix=".piodebug-") + self._gdbsrc_dir = mkdtemp(dir=get_project_cache_dir(), + prefix=".piodebug-") self._target_is_run = False self._last_server_activity = 0 @@ -98,8 +98,11 @@ class GDBClient(BaseProcess): # pylint: disable=too-many-instance-attributes args.extend(["--data-directory", gdb_data_dir]) args.append(patterns['PROG_PATH']) - return reactor.spawnProcess( - self, gdb_path, args, path=self.project_dir, env=os.environ) + return reactor.spawnProcess(self, + gdb_path, + args, + path=self.project_dir, + env=os.environ) @staticmethod def _get_data_dir(gdb_path): @@ -109,8 +112,8 @@ class GDBClient(BaseProcess): # pylint: disable=too-many-instance-attributes return gdb_data_dir if isdir(gdb_data_dir) else None def generate_pioinit(self, dst_dir, patterns): - server_exe = (self.debug_options.get("server") or {}).get( - "executable", "").lower() + server_exe = (self.debug_options.get("server") + or {}).get("executable", "").lower() if "jlink" in server_exe: cfg = initcfgs.GDB_JLINK_INIT_CONFIG elif "st-util" in server_exe: diff --git a/platformio/commands/debug/command.py b/platformio/commands/debug/command.py index 153f1e74..129383d8 100644 --- a/platformio/commands/debug/command.py +++ b/platformio/commands/debug/command.py @@ -27,29 +27,24 @@ from platformio.project.config import ProjectConfig from platformio.project.helpers import is_platformio_project -@click.command( - "debug", - context_settings=dict(ignore_unknown_options=True), - short_help="PIO Unified Debugger") -@click.option( - "-d", - "--project-dir", - default=os.getcwd, - type=click.Path( - exists=True, - file_okay=False, - dir_okay=True, - writable=True, - resolve_path=True)) -@click.option( - "-c", - "--project-conf", - type=click.Path( - exists=True, - file_okay=True, - dir_okay=False, - readable=True, - resolve_path=True)) +@click.command("debug", + context_settings=dict(ignore_unknown_options=True), + short_help="PIO Unified Debugger") +@click.option("-d", + "--project-dir", + default=os.getcwd, + type=click.Path(exists=True, + file_okay=False, + dir_okay=True, + writable=True, + resolve_path=True)) +@click.option("-c", + "--project-conf", + type=click.Path(exists=True, + file_okay=True, + dir_okay=False, + readable=True, + resolve_path=True)) @click.option("--environment", "-e", metavar="") @click.option("--verbose", "-v", is_flag=True) @click.option("--interface", type=click.Choice(["gdb"])) diff --git a/platformio/commands/debug/helpers.py b/platformio/commands/debug/helpers.py index 139411ea..88b4f64a 100644 --- a/platformio/commands/debug/helpers.py +++ b/platformio/commands/debug/helpers.py @@ -63,16 +63,15 @@ def validate_debug_options(cmd_ctx, env_options): try: platform = PlatformFactory.newPlatform(env_options['platform']) except exception.UnknownPlatform: - cmd_ctx.invoke( - cmd_platform_install, - platforms=[env_options['platform']], - skip_default_package=True) + cmd_ctx.invoke(cmd_platform_install, + platforms=[env_options['platform']], + skip_default_package=True) platform = PlatformFactory.newPlatform(env_options['platform']) board_config = platform.board_config(env_options['board']) tool_name = board_config.get_debug_tool_name(env_options.get("debug_tool")) - tool_settings = board_config.get("debug", {}).get("tools", {}).get( - tool_name, {}) + tool_settings = board_config.get("debug", {}).get("tools", + {}).get(tool_name, {}) server_options = None # specific server per a system @@ -102,10 +101,9 @@ def validate_debug_options(cmd_ctx, env_options): server_package_dir = platform.get_package_dir( server_package) if server_package else None if server_package and not server_package_dir: - platform.install_packages( - with_packages=[server_package], - skip_default_package=True, - silent=True) + platform.install_packages(with_packages=[server_package], + skip_default_package=True, + silent=True) server_package_dir = platform.get_package_dir(server_package) server_options = dict( cwd=server_package_dir if server_package else None, @@ -143,12 +141,11 @@ def validate_debug_options(cmd_ctx, env_options): def predebug_project(ctx, project_dir, env_name, preload, verbose): - ctx.invoke( - cmd_run, - project_dir=project_dir, - environment=[env_name], - target=["__debug"] + (["upload"] if preload else []), - verbose=verbose) + ctx.invoke(cmd_run, + project_dir=project_dir, + environment=[env_name], + target=["__debug"] + (["upload"] if preload else []), + verbose=verbose) if preload: time.sleep(5) @@ -167,11 +164,10 @@ def capture_std_streams(stdout, stderr=None): def load_configuration(ctx, project_dir, env_name): output = BytesIO() with capture_std_streams(output): - ctx.invoke( - cmd_run, - project_dir=project_dir, - environment=[env_name], - target=["idedata"]) + ctx.invoke(cmd_run, + project_dir=project_dir, + environment=[env_name], + target=["idedata"]) result = output.getvalue().decode() output.close() if '"includes":' not in result: diff --git a/platformio/commands/device.py b/platformio/commands/device.py index 992ad9b2..7876fae7 100644 --- a/platformio/commands/device.py +++ b/platformio/commands/device.py @@ -101,63 +101,57 @@ def device_list( # pylint: disable=too-many-branches @cli.command("monitor", short_help="Monitor device (Serial)") @click.option("--port", "-p", help="Port, a number or a device name") @click.option("--baud", "-b", type=int, help="Set baud rate, default=9600") -@click.option( - "--parity", - default="N", - type=click.Choice(["N", "E", "O", "S", "M"]), - help="Set parity, default=N") -@click.option( - "--rtscts", is_flag=True, help="Enable RTS/CTS flow control, default=Off") -@click.option( - "--xonxoff", - is_flag=True, - help="Enable software flow control, default=Off") -@click.option( - "--rts", - default=None, - type=click.IntRange(0, 1), - help="Set initial RTS line state") -@click.option( - "--dtr", - default=None, - type=click.IntRange(0, 1), - help="Set initial DTR line state") +@click.option("--parity", + default="N", + type=click.Choice(["N", "E", "O", "S", "M"]), + help="Set parity, default=N") +@click.option("--rtscts", + is_flag=True, + help="Enable RTS/CTS flow control, default=Off") +@click.option("--xonxoff", + is_flag=True, + help="Enable software flow control, default=Off") +@click.option("--rts", + default=None, + type=click.IntRange(0, 1), + help="Set initial RTS line state") +@click.option("--dtr", + default=None, + type=click.IntRange(0, 1), + help="Set initial DTR line state") @click.option("--echo", is_flag=True, help="Enable local echo, default=Off") -@click.option( - "--encoding", - default="UTF-8", - help="Set the encoding for the serial port (e.g. hexlify, " - "Latin1, UTF-8), default: UTF-8") +@click.option("--encoding", + default="UTF-8", + help="Set the encoding for the serial port (e.g. hexlify, " + "Latin1, UTF-8), default: UTF-8") @click.option("--filter", "-f", multiple=True, help="Add text transformation") -@click.option( - "--eol", - default="CRLF", - type=click.Choice(["CR", "LF", "CRLF"]), - help="End of line mode, default=CRLF") -@click.option( - "--raw", is_flag=True, help="Do not apply any encodings/transformations") -@click.option( - "--exit-char", - type=int, - default=3, - help="ASCII code of special character that is used to exit " - "the application, default=3 (Ctrl+C)") -@click.option( - "--menu-char", - type=int, - default=20, - help="ASCII code of special character that is used to " - "control miniterm (menu), default=20 (DEC)") -@click.option( - "--quiet", - is_flag=True, - help="Diagnostics: suppress non-error messages, default=Off") -@click.option( - "-d", - "--project-dir", - default=getcwd, - type=click.Path( - exists=True, file_okay=False, dir_okay=True, resolve_path=True)) +@click.option("--eol", + default="CRLF", + type=click.Choice(["CR", "LF", "CRLF"]), + help="End of line mode, default=CRLF") +@click.option("--raw", + is_flag=True, + help="Do not apply any encodings/transformations") +@click.option("--exit-char", + type=int, + default=3, + help="ASCII code of special character that is used to exit " + "the application, default=3 (Ctrl+C)") +@click.option("--menu-char", + type=int, + default=20, + help="ASCII code of special character that is used to " + "control miniterm (menu), default=20 (DEC)") +@click.option("--quiet", + is_flag=True, + help="Diagnostics: suppress non-error messages, default=Off") +@click.option("-d", + "--project-dir", + default=getcwd, + type=click.Path(exists=True, + file_okay=False, + dir_okay=True, + resolve_path=True)) @click.option( "-e", "--environment", @@ -206,11 +200,10 @@ def device_monitor(**kwargs): # pylint: disable=too-many-branches break try: - miniterm.main( - default_port=kwargs['port'], - default_baudrate=kwargs['baud'] or 9600, - default_rts=kwargs['rts'], - default_dtr=kwargs['dtr']) + miniterm.main(default_port=kwargs['port'], + default_baudrate=kwargs['baud'] or 9600, + default_rts=kwargs['rts'], + default_dtr=kwargs['dtr']) except Exception as e: raise exception.MinitermException(e) diff --git a/platformio/commands/home/helpers.py b/platformio/commands/home/helpers.py index a4dd142a..a8ff898f 100644 --- a/platformio/commands/home/helpers.py +++ b/platformio/commands/home/helpers.py @@ -60,8 +60,9 @@ def is_twitter_blocked(): timeout = 2 try: if os.getenv("HTTP_PROXY", os.getenv("HTTPS_PROXY")): - requests.get( - "http://%s" % ip, allow_redirects=False, timeout=timeout) + requests.get("http://%s" % ip, + allow_redirects=False, + timeout=timeout) else: socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((ip, 80)) return False diff --git a/platformio/commands/home/rpc/handlers/misc.py b/platformio/commands/home/rpc/handlers/misc.py index d3b53383..8de0e195 100644 --- a/platformio/commands/home/rpc/handlers/misc.py +++ b/platformio/commands/home/rpc/handlers/misc.py @@ -67,11 +67,11 @@ class MiscRPC(object): html_or_json = json.loads(html_or_json) assert "items_html" in html_or_json soup = BeautifulSoup(html_or_json['items_html'], "html.parser") - tweet_nodes = soup.find_all( - "div", attrs={ - "class": "tweet", - "data-tweet-id": True - }) + tweet_nodes = soup.find_all("div", + attrs={ + "class": "tweet", + "data-tweet-id": True + }) result = yield defer.DeferredList( [self._parse_tweet_node(node, username) for node in tweet_nodes], consumeErrors=True) @@ -97,13 +97,14 @@ class MiscRPC(object): node.get("data-expanded-url") for node in (quote_text_node or text_node).find_all( class_="twitter-timeline-link", - attrs={"data-expanded-url": True}) - ] + attrs={"data-expanded-url": True} + ) + ] # yapf: disable # fetch data from iframe card if (not photos or not urls) and tweet.get("data-card2-type"): - iframe_node = tweet.find( - "div", attrs={"data-full-card-iframe-url": True}) + iframe_node = tweet.find("div", + attrs={"data-full-card-iframe-url": True}) if iframe_node: iframe_card = yield self._fetch_iframe_card( twitter_url + iframe_node.get("data-full-card-iframe-url"), @@ -161,8 +162,8 @@ class MiscRPC(object): url_node = soup.find("a", class_="TwitterCard-container") text_node = soup.find("div", class_="SummaryCard-content") if text_node: - text_node.find( - "span", class_="SummaryCard-destination").decompose() + text_node.find("span", + class_="SummaryCard-destination").decompose() defer.returnValue({ "photo": photo_node.get("data-src") if photo_node else None, diff --git a/platformio/commands/home/rpc/handlers/os.py b/platformio/commands/home/rpc/handlers/os.py index 8b263632..c394d935 100644 --- a/platformio/commands/home/rpc/handlers/os.py +++ b/platformio/commands/home/rpc/handlers/os.py @@ -54,8 +54,10 @@ class OSRPC(object): session = helpers.requests_session() if data: - r = yield session.post( - uri, data=data, headers=headers, timeout=timeout) + r = yield session.post(uri, + data=data, + headers=headers, + timeout=timeout) else: r = yield session.get(uri, headers=headers, timeout=timeout) diff --git a/platformio/commands/home/rpc/handlers/project.py b/platformio/commands/home/rpc/handlers/project.py index 2b396094..e9435d35 100644 --- a/platformio/commands/home/rpc/handlers/project.py +++ b/platformio/commands/home/rpc/handlers/project.py @@ -29,8 +29,9 @@ from platformio.compat import get_filesystem_encoding from platformio.ide.projectgenerator import ProjectGenerator from platformio.managers.platform import PlatformManager from platformio.project.config import ProjectConfig -from platformio.project.helpers import ( - get_project_libdeps_dir, get_project_src_dir, is_platformio_project) +from platformio.project.helpers import (get_project_libdeps_dir, + get_project_src_dir, + is_platformio_project) class ProjectRPC(object): diff --git a/platformio/commands/home/rpc/server.py b/platformio/commands/home/rpc/server.py index bf339994..d62faa3d 100644 --- a/platformio/commands/home/rpc/server.py +++ b/platformio/commands/home/rpc/server.py @@ -48,8 +48,8 @@ class JSONRPCServerProtocol(WebSocketServerProtocol): if isinstance(failure.value, JSONRPCDispatchException): e = failure.value else: - e = JSONRPCDispatchException( - code=4999, message=failure.getErrorMessage()) + e = JSONRPCDispatchException(code=4999, + message=failure.getErrorMessage()) del response["result"] response['error'] = e.error._data # pylint: disable=protected-access print(response['error']) diff --git a/platformio/commands/init.py b/platformio/commands/init.py index 35e459bf..d3d8f52f 100644 --- a/platformio/commands/init.py +++ b/platformio/commands/init.py @@ -25,9 +25,11 @@ from platformio.commands.platform import \ from platformio.ide.projectgenerator import ProjectGenerator from platformio.managers.platform import PlatformManager from platformio.project.config import ProjectConfig -from platformio.project.helpers import ( - get_project_include_dir, get_project_lib_dir, get_project_src_dir, - get_project_test_dir, is_platformio_project) +from platformio.project.helpers import (get_project_include_dir, + get_project_lib_dir, + get_project_src_dir, + get_project_test_dir, + is_platformio_project) def validate_boards(ctx, param, value): # pylint: disable=W0613 @@ -42,22 +44,23 @@ def validate_boards(ctx, param, value): # pylint: disable=W0613 return value -@click.command( - "init", short_help="Initialize PlatformIO project or update existing") -@click.option( - "--project-dir", - "-d", - default=getcwd, - type=click.Path( - exists=True, - file_okay=False, - dir_okay=True, - writable=True, - resolve_path=True)) -@click.option( - "-b", "--board", multiple=True, metavar="ID", callback=validate_boards) -@click.option( - "--ide", type=click.Choice(ProjectGenerator.get_supported_ides())) +@click.command("init", + short_help="Initialize PlatformIO project or update existing") +@click.option("--project-dir", + "-d", + default=getcwd, + type=click.Path(exists=True, + file_okay=False, + dir_okay=True, + writable=True, + resolve_path=True)) +@click.option("-b", + "--board", + multiple=True, + metavar="ID", + callback=validate_boards) +@click.option("--ide", + type=click.Choice(ProjectGenerator.get_supported_ides())) @click.option("-O", "--project-option", multiple=True) @click.option("--env-prefix", default="") @click.option("-s", "--silent", is_flag=True) @@ -72,22 +75,23 @@ def cli( silent): if not silent: if project_dir == getcwd(): - click.secho( - "\nThe current working directory", fg="yellow", nl=False) + click.secho("\nThe current working directory", + fg="yellow", + nl=False) click.secho(" %s " % project_dir, fg="cyan", nl=False) click.secho("will be used for the project.", fg="yellow") click.echo("") click.echo("The next files/directories have been created in %s" % click.style(project_dir, fg="cyan")) - click.echo("%s - Put project header files here" % click.style( - "include", fg="cyan")) + click.echo("%s - Put project header files here" % + click.style("include", fg="cyan")) click.echo("%s - Put here project specific (private) libraries" % click.style("lib", fg="cyan")) - click.echo("%s - Put project source files here" % click.style( - "src", fg="cyan")) - click.echo("%s - Project Configuration File" % click.style( - "platformio.ini", fg="cyan")) + click.echo("%s - Put project source files here" % + click.style("src", fg="cyan")) + click.echo("%s - Project Configuration File" % + click.style("platformio.ini", fg="cyan")) is_new_project = not is_platformio_project(project_dir) if is_new_project: @@ -112,8 +116,8 @@ def cli( if ide: click.secho( "\nProject has been successfully %s including configuration files " - "for `%s` IDE." % ("initialized" if is_new_project else "updated", - ide), + "for `%s` IDE." % + ("initialized" if is_new_project else "updated", ide), fg="green") else: click.secho( @@ -363,8 +367,8 @@ def init_cvs_ignore(project_dir): def fill_project_envs(ctx, project_dir, board_ids, project_option, env_prefix, force_download): - config = ProjectConfig( - join(project_dir, "platformio.ini"), parse_extra=False) + config = ProjectConfig(join(project_dir, "platformio.ini"), + parse_extra=False) used_boards = [] for section in config.sections(): cond = [ @@ -417,6 +421,5 @@ def _install_dependent_platforms(ctx, platforms): ] if set(platforms) <= set(installed_platforms): return - ctx.invoke( - cli_platform_install, - platforms=list(set(platforms) - set(installed_platforms))) + ctx.invoke(cli_platform_install, + platforms=list(set(platforms) - set(installed_platforms))) diff --git a/platformio/commands/lib.py b/platformio/commands/lib.py index 63b89950..23094f43 100644 --- a/platformio/commands/lib.py +++ b/platformio/commands/lib.py @@ -26,9 +26,10 @@ from platformio.managers.lib import (LibraryManager, get_builtin_libs, is_builtin_lib) from platformio.proc import is_ci from platformio.project.config import ProjectConfig -from platformio.project.helpers import ( - get_project_dir, get_project_global_lib_dir, get_project_libdeps_dir, - is_platformio_project) +from platformio.project.helpers import (get_project_dir, + get_project_global_lib_dir, + get_project_libdeps_dir, + is_platformio_project) try: from urllib.parse import quote @@ -42,23 +43,20 @@ CTX_META_STORAGE_LIBDEPS_KEY = __name__ + ".storage_lib_deps" @click.group(short_help="Library Manager") -@click.option( - "-d", - "--storage-dir", - multiple=True, - default=None, - type=click.Path( - exists=True, - file_okay=False, - dir_okay=True, - writable=True, - resolve_path=True), - help="Manage custom library storage") -@click.option( - "-g", - "--global", - is_flag=True, - help="Manage global PlatformIO library storage") +@click.option("-d", + "--storage-dir", + multiple=True, + default=None, + type=click.Path(exists=True, + file_okay=False, + dir_okay=True, + writable=True, + resolve_path=True), + help="Manage custom library storage") +@click.option("-g", + "--global", + is_flag=True, + help="Manage global PlatformIO library storage") @click.option( "-e", "--environment", @@ -101,8 +99,8 @@ def cli(ctx, **options): continue with util.cd(storage_dir): libdeps_dir = get_project_libdeps_dir() - config = ProjectConfig.get_instance( - join(storage_dir, "platformio.ini")) + config = ProjectConfig.get_instance(join(storage_dir, + "platformio.ini")) config.validate(options['environment']) for env in config.envs(): if options['environment'] and env not in options['environment']: @@ -119,17 +117,17 @@ def cli(ctx, **options): "--save", is_flag=True, help="Save installed libraries into the `platformio.ini` dependency list") -@click.option( - "-s", "--silent", is_flag=True, help="Suppress progress reporting") -@click.option( - "--interactive", - is_flag=True, - help="Allow to make a choice for all prompts") -@click.option( - "-f", - "--force", - is_flag=True, - help="Reinstall/redownload library if exists") +@click.option("-s", + "--silent", + is_flag=True, + help="Suppress progress reporting") +@click.option("--interactive", + is_flag=True, + help="Allow to make a choice for all prompts") +@click.option("-f", + "--force", + is_flag=True, + help="Reinstall/redownload library if exists") @click.pass_context def lib_install( # pylint: disable=too-many-arguments ctx, libraries, save, silent, interactive, force): @@ -143,20 +141,18 @@ def lib_install( # pylint: disable=too-many-arguments lm = LibraryManager(storage_dir) if libraries: for library in libraries: - pkg_dir = lm.install( - library, - silent=silent, - interactive=interactive, - force=force) + pkg_dir = lm.install(library, + silent=silent, + interactive=interactive, + force=force) installed_manifests[library] = lm.load_manifest(pkg_dir) elif storage_dir in storage_libdeps: for library in storage_libdeps[storage_dir]: try: - pkg_dir = lm.install( - library, - silent=silent, - interactive=interactive, - force=force) + pkg_dir = lm.install(library, + silent=silent, + interactive=interactive, + force=force) installed_manifests[library] = lm.load_manifest(pkg_dir) except exception.LibNotFound as e: if not silent or not is_builtin_lib(library): @@ -203,15 +199,13 @@ def lib_uninstall(ctx, libraries): @cli.command("update", short_help="Update installed libraries") @click.argument("libraries", required=False, nargs=-1, metavar="[LIBRARY...]") -@click.option( - "-c", - "--only-check", - is_flag=True, - help="DEPRECATED. Please use `--dry-run` instead") -@click.option( - "--dry-run", - is_flag=True, - help="Do not update, only check for the new versions") +@click.option("-c", + "--only-check", + is_flag=True, + help="DEPRECATED. Please use `--dry-run` instead") +@click.option("--dry-run", + is_flag=True, + help="Do not update, only check for the new versions") @click.option("--json-output", is_flag=True) @click.pass_context def lib_update(ctx, libraries, only_check, dry_run, json_output): @@ -297,10 +291,9 @@ def lib_list(ctx, json_output): @click.option("-f", "--framework", multiple=True) @click.option("-p", "--platform", multiple=True) @click.option("-i", "--header", multiple=True) -@click.option( - "--noninteractive", - is_flag=True, - help="Do not prompt, automatically paginate with delay") +@click.option("--noninteractive", + is_flag=True, + help="Do not prompt, automatically paginate with delay") def lib_search(query, json_output, page, noninteractive, **filters): if not query: query = [] @@ -311,10 +304,9 @@ def lib_search(query, json_output, page, noninteractive, **filters): for value in values: query.append('%s:"%s"' % (key, value)) - result = util.get_api_result( - "/v2/lib/search", - dict(query=" ".join(query), page=page), - cache_valid="1d") + result = util.get_api_result("/v2/lib/search", + dict(query=" ".join(query), page=page), + cache_valid="1d") if json_output: click.echo(json.dumps(result)) @@ -336,9 +328,8 @@ def lib_search(query, json_output, page, noninteractive, **filters): fg="cyan") return - click.secho( - "Found %d libraries:\n" % result['total'], - fg="green" if result['total'] else "yellow") + click.secho("Found %d libraries:\n" % result['total'], + fg="green" if result['total'] else "yellow") while True: for item in result['items']: @@ -350,20 +341,18 @@ def lib_search(query, json_output, page, noninteractive, **filters): if noninteractive: click.echo() - click.secho( - "Loading next %d libraries... Press Ctrl+C to stop!" % - result['perpage'], - fg="yellow") + click.secho("Loading next %d libraries... Press Ctrl+C to stop!" % + result['perpage'], + fg="yellow") click.echo() time.sleep(5) elif not click.confirm("Show next libraries?"): break - result = util.get_api_result( - "/v2/lib/search", { - "query": " ".join(query), - "page": int(result['page']) + 1 - }, - cache_valid="1d") + result = util.get_api_result("/v2/lib/search", { + "query": " ".join(query), + "page": int(result['page']) + 1 + }, + cache_valid="1d") @cli.command("builtin", short_help="List built-in libraries") @@ -475,13 +464,12 @@ def lib_register(config_url): and not config_url.startswith("https://")): raise exception.InvalidLibConfURL(config_url) - result = util.get_api_result( - "/lib/register", data=dict(config_url=config_url)) + result = util.get_api_result("/lib/register", + data=dict(config_url=config_url)) if "message" in result and result['message']: - click.secho( - result['message'], - fg="green" - if "successed" in result and result['successed'] else "red") + click.secho(result['message'], + fg="green" if "successed" in result and result['successed'] + else "red") @cli.command("stats", short_help="Library Registry Statistics") @@ -512,10 +500,9 @@ def lib_stats(json_output): date = str( time.strftime("%c", util.parse_date(item['date'])) if "date" in item else "") - url = click.style( - "https://platformio.org/lib/show/%s/%s" % (item['id'], - quote(item['name'])), - fg="blue") + url = click.style("https://platformio.org/lib/show/%s/%s" % + (item['id'], quote(item['name'])), + fg="blue") click.echo( (printitemdate_tpl if "date" in item else printitem_tpl).format( name=click.style(item['name'], fg="cyan"), date=date, url=url)) @@ -524,10 +511,9 @@ def lib_stats(json_output): click.echo( printitem_tpl.format( name=click.style(name, fg="cyan"), - url=click.style( - "https://platformio.org/lib/search?query=" + quote( - "keyword:%s" % name), - fg="blue"))) + url=click.style("https://platformio.org/lib/search?query=" + + quote("keyword:%s" % name), + fg="blue"))) for key in ("updated", "added"): _print_title("Recently " + key) diff --git a/platformio/commands/platform.py b/platformio/commands/platform.py index 70612f51..9f56f8d6 100644 --- a/platformio/commands/platform.py +++ b/platformio/commands/platform.py @@ -29,9 +29,9 @@ def cli(): def _print_platforms(platforms): for platform in platforms: - click.echo("{name} ~ {title}".format( - name=click.style(platform['name'], fg="cyan"), - title=platform['title'])) + click.echo("{name} ~ {title}".format(name=click.style(platform['name'], + fg="cyan"), + title=platform['title'])) click.echo("=" * (3 + len(platform['name'] + platform['title']))) click.echo(platform['description']) click.echo() @@ -65,19 +65,18 @@ def _get_installed_platform_data(platform, with_boards=True, expose_packages=True): p = PlatformFactory.newPlatform(platform) - data = dict( - name=p.name, - title=p.title, - description=p.description, - version=p.version, - homepage=p.homepage, - repository=p.repository_url, - url=p.vendor_url, - docs=p.docs_url, - license=p.license, - forDesktop=not p.is_embedded(), - frameworks=sorted(list(p.frameworks) if p.frameworks else []), - packages=list(p.packages) if p.packages else []) + data = dict(name=p.name, + title=p.title, + description=p.description, + version=p.version, + homepage=p.homepage, + repository=p.repository_url, + url=p.vendor_url, + docs=p.docs_url, + license=p.license, + forDesktop=not p.is_embedded(), + frameworks=sorted(list(p.frameworks) if p.frameworks else []), + packages=list(p.packages) if p.packages else []) # if dump to API # del data['version'] @@ -99,11 +98,10 @@ def _get_installed_platform_data(platform, data['packages'] = [] installed_pkgs = p.get_installed_packages() for name, opts in p.packages.items(): - item = dict( - name=name, - type=p.get_package_type(name), - requirements=opts.get("version"), - optional=opts.get("optional") is True) + item = dict(name=name, + type=p.get_package_type(name), + requirements=opts.get("version"), + optional=opts.get("optional") is True) if name in installed_pkgs: for key, value in installed_pkgs[name].items(): if key not in ("url", "version", "description"): @@ -129,18 +127,17 @@ def _get_registry_platform_data( # pylint: disable=unused-argument if not _data: return None - data = dict( - name=_data['name'], - title=_data['title'], - description=_data['description'], - homepage=_data['homepage'], - repository=_data['repository'], - url=_data['url'], - license=_data['license'], - forDesktop=_data['forDesktop'], - frameworks=_data['frameworks'], - packages=_data['packages'], - versions=_data['versions']) + data = dict(name=_data['name'], + title=_data['title'], + description=_data['description'], + homepage=_data['homepage'], + repository=_data['repository'], + url=_data['url'], + license=_data['license'], + forDesktop=_data['forDesktop'], + frameworks=_data['frameworks'], + packages=_data['packages'], + versions=_data['versions']) if with_boards: data['boards'] = [ @@ -163,8 +160,9 @@ def platform_search(query, json_output): if query and query.lower() not in search_data.lower(): continue platforms.append( - _get_registry_platform_data( - platform['name'], with_boards=False, expose_packages=False)) + _get_registry_platform_data(platform['name'], + with_boards=False, + expose_packages=False)) if json_output: click.echo(json.dumps(platforms)) @@ -183,8 +181,8 @@ def platform_frameworks(query, json_output): search_data = json.dumps(framework) if query and query.lower() not in search_data.lower(): continue - framework['homepage'] = ( - "https://platformio.org/frameworks/" + framework['name']) + framework['homepage'] = ("https://platformio.org/frameworks/" + + framework['name']) framework['platforms'] = [ platform['name'] for platform in _get_registry_platforms() if framework['name'] in platform['frameworks'] @@ -205,10 +203,9 @@ def platform_list(json_output): pm = PlatformManager() for manifest in pm.get_installed(): platforms.append( - _get_installed_platform_data( - manifest['__pkg_dir'], - with_boards=False, - expose_packages=False)) + _get_installed_platform_data(manifest['__pkg_dir'], + with_boards=False, + expose_packages=False)) platforms = sorted(platforms, key=lambda manifest: manifest['name']) if json_output: @@ -227,8 +224,9 @@ def platform_show(platform, json_output): # pylint: disable=too-many-branches if json_output: return click.echo(json.dumps(data)) - click.echo("{name} ~ {title}".format( - name=click.style(data['name'], fg="cyan"), title=data['title'])) + click.echo("{name} ~ {title}".format(name=click.style(data['name'], + fg="cyan"), + title=data['title'])) click.echo("=" * (3 + len(data['name'] + data['title']))) click.echo(data['description']) click.echo() @@ -293,17 +291,15 @@ def platform_install(platforms, with_package, without_package, skip_default_package, force): pm = PlatformManager() for platform in platforms: - if pm.install( - name=platform, - with_packages=with_package, - without_packages=without_package, - skip_default_package=skip_default_package, - force=force): - click.secho( - "The platform '%s' has been successfully installed!\n" - "The rest of packages will be installed automatically " - "depending on your build environment." % platform, - fg="green") + if pm.install(name=platform, + with_packages=with_package, + without_packages=without_package, + skip_default_package=skip_default_package, + force=force): + click.secho("The platform '%s' has been successfully installed!\n" + "The rest of packages will be installed automatically " + "depending on your build environment." % platform, + fg="green") @cli.command("uninstall", short_help="Uninstall development platform") @@ -312,28 +308,24 @@ def platform_uninstall(platforms): pm = PlatformManager() for platform in platforms: if pm.uninstall(platform): - click.secho( - "The platform '%s' has been successfully " - "uninstalled!" % platform, - fg="green") + click.secho("The platform '%s' has been successfully " + "uninstalled!" % platform, + fg="green") @cli.command("update", short_help="Update installed development platforms") @click.argument("platforms", nargs=-1, required=False, metavar="[PLATFORM...]") -@click.option( - "-p", - "--only-packages", - is_flag=True, - help="Update only the platform packages") -@click.option( - "-c", - "--only-check", - is_flag=True, - help="DEPRECATED. Please use `--dry-run` instead") -@click.option( - "--dry-run", - is_flag=True, - help="Do not update, only check for the new versions") +@click.option("-p", + "--only-packages", + is_flag=True, + help="Update only the platform packages") +@click.option("-c", + "--only-check", + is_flag=True, + help="DEPRECATED. Please use `--dry-run` instead") +@click.option("--dry-run", + is_flag=True, + help="Do not update, only check for the new versions") @click.option("--json-output", is_flag=True) def platform_update( # pylint: disable=too-many-locals platforms, only_packages, only_check, dry_run, json_output): @@ -363,8 +355,9 @@ def platform_update( # pylint: disable=too-many-locals if (not latest and not PlatformFactory.newPlatform( pkg_dir).are_outdated_packages()): continue - data = _get_installed_platform_data( - pkg_dir, with_boards=False, expose_packages=False) + data = _get_installed_platform_data(pkg_dir, + with_boards=False, + expose_packages=False) if latest: data['versionLatest'] = latest result.append(data) @@ -373,8 +366,9 @@ def platform_update( # pylint: disable=too-many-locals # cleanup cached board and platform lists app.clean_cache() for platform in platforms: - click.echo("Platform %s" % click.style( - pkg_dir_to_name.get(platform, platform), fg="cyan")) + click.echo( + "Platform %s" % + click.style(pkg_dir_to_name.get(platform, platform), fg="cyan")) click.echo("--------") pm.update(platform, only_packages=only_packages, only_check=only_check) click.echo() diff --git a/platformio/commands/remote.py b/platformio/commands/remote.py index ded45eda..8dcdf9a2 100644 --- a/platformio/commands/remote.py +++ b/platformio/commands/remote.py @@ -43,12 +43,13 @@ def remote_agent(): @remote_agent.command("start", short_help="Start agent") @click.option("-n", "--name") @click.option("-s", "--share", multiple=True, metavar="E-MAIL") -@click.option( - "-d", - "--working-dir", - envvar="PLATFORMIO_REMOTE_AGENT_DIR", - type=click.Path( - file_okay=False, dir_okay=True, writable=True, resolve_path=True)) +@click.option("-d", + "--working-dir", + envvar="PLATFORMIO_REMOTE_AGENT_DIR", + type=click.Path(file_okay=False, + dir_okay=True, + writable=True, + resolve_path=True)) def remote_agent_start(**kwargs): pioplus_call(sys.argv[1:]) @@ -63,17 +64,15 @@ def remote_agent_list(): pioplus_call(sys.argv[1:]) -@cli.command( - "update", short_help="Update installed Platforms, Packages and Libraries") -@click.option( - "-c", - "--only-check", - is_flag=True, - help="DEPRECATED. Please use `--dry-run` instead") -@click.option( - "--dry-run", - is_flag=True, - help="Do not update, only check for the new versions") +@cli.command("update", + short_help="Update installed Platforms, Packages and Libraries") +@click.option("-c", + "--only-check", + is_flag=True, + help="DEPRECATED. Please use `--dry-run` instead") +@click.option("--dry-run", + is_flag=True, + help="Do not update, only check for the new versions") def remote_update(only_check, dry_run): pioplus_call(sys.argv[1:]) @@ -82,16 +81,14 @@ def remote_update(only_check, dry_run): @click.option("-e", "--environment", multiple=True) @click.option("-t", "--target", multiple=True) @click.option("--upload-port") -@click.option( - "-d", - "--project-dir", - default=getcwd, - type=click.Path( - exists=True, - file_okay=True, - dir_okay=True, - writable=True, - resolve_path=True)) +@click.option("-d", + "--project-dir", + default=getcwd, + type=click.Path(exists=True, + file_okay=True, + dir_okay=True, + writable=True, + resolve_path=True)) @click.option("--disable-auto-clean", is_flag=True) @click.option("-r", "--force-remote", is_flag=True) @click.option("-s", "--silent", is_flag=True) @@ -105,16 +102,14 @@ def remote_run(**kwargs): @click.option("--ignore", "-i", multiple=True, metavar="") @click.option("--upload-port") @click.option("--test-port") -@click.option( - "-d", - "--project-dir", - default=getcwd, - type=click.Path( - exists=True, - file_okay=False, - dir_okay=True, - writable=True, - resolve_path=True)) +@click.option("-d", + "--project-dir", + default=getcwd, + type=click.Path(exists=True, + file_okay=False, + dir_okay=True, + writable=True, + resolve_path=True)) @click.option("-r", "--force-remote", is_flag=True) @click.option("--without-building", is_flag=True) @click.option("--without-uploading", is_flag=True) @@ -136,59 +131,55 @@ def device_list(json_output): @remote_device.command("monitor", short_help="Monitor remote device") @click.option("--port", "-p", help="Port, a number or a device name") -@click.option( - "--baud", "-b", type=int, default=9600, help="Set baud rate, default=9600") -@click.option( - "--parity", - default="N", - type=click.Choice(["N", "E", "O", "S", "M"]), - help="Set parity, default=N") -@click.option( - "--rtscts", is_flag=True, help="Enable RTS/CTS flow control, default=Off") -@click.option( - "--xonxoff", - is_flag=True, - help="Enable software flow control, default=Off") -@click.option( - "--rts", - default=None, - type=click.IntRange(0, 1), - help="Set initial RTS line state") -@click.option( - "--dtr", - default=None, - type=click.IntRange(0, 1), - help="Set initial DTR line state") +@click.option("--baud", + "-b", + type=int, + default=9600, + help="Set baud rate, default=9600") +@click.option("--parity", + default="N", + type=click.Choice(["N", "E", "O", "S", "M"]), + help="Set parity, default=N") +@click.option("--rtscts", + is_flag=True, + help="Enable RTS/CTS flow control, default=Off") +@click.option("--xonxoff", + is_flag=True, + help="Enable software flow control, default=Off") +@click.option("--rts", + default=None, + type=click.IntRange(0, 1), + help="Set initial RTS line state") +@click.option("--dtr", + default=None, + type=click.IntRange(0, 1), + help="Set initial DTR line state") @click.option("--echo", is_flag=True, help="Enable local echo, default=Off") -@click.option( - "--encoding", - default="UTF-8", - help="Set the encoding for the serial port (e.g. hexlify, " - "Latin1, UTF-8), default: UTF-8") +@click.option("--encoding", + default="UTF-8", + help="Set the encoding for the serial port (e.g. hexlify, " + "Latin1, UTF-8), default: UTF-8") @click.option("--filter", "-f", multiple=True, help="Add text transformation") -@click.option( - "--eol", - default="CRLF", - type=click.Choice(["CR", "LF", "CRLF"]), - help="End of line mode, default=CRLF") -@click.option( - "--raw", is_flag=True, help="Do not apply any encodings/transformations") -@click.option( - "--exit-char", - type=int, - default=3, - help="ASCII code of special character that is used to exit " - "the application, default=3 (Ctrl+C)") -@click.option( - "--menu-char", - type=int, - default=20, - help="ASCII code of special character that is used to " - "control miniterm (menu), default=20 (DEC)") -@click.option( - "--quiet", - is_flag=True, - help="Diagnostics: suppress non-error messages, default=Off") +@click.option("--eol", + default="CRLF", + type=click.Choice(["CR", "LF", "CRLF"]), + help="End of line mode, default=CRLF") +@click.option("--raw", + is_flag=True, + help="Do not apply any encodings/transformations") +@click.option("--exit-char", + type=int, + default=3, + help="ASCII code of special character that is used to exit " + "the application, default=3 (Ctrl+C)") +@click.option("--menu-char", + type=int, + default=20, + help="ASCII code of special character that is used to " + "control miniterm (menu), default=20 (DEC)") +@click.option("--quiet", + is_flag=True, + help="Diagnostics: suppress non-error messages, default=Off") @click.pass_context def device_monitor(ctx, **kwargs): diff --git a/platformio/commands/run/command.py b/platformio/commands/run/command.py index 1913314b..23ca09d4 100644 --- a/platformio/commands/run/command.py +++ b/platformio/commands/run/command.py @@ -20,8 +20,9 @@ import click from platformio import exception, util from platformio.commands.device import device_monitor as cmd_device_monitor -from platformio.commands.run.helpers import ( - _clean_build_dir, _handle_legacy_libdeps, print_summary) +from platformio.commands.run.helpers import (_clean_build_dir, + _handle_legacy_libdeps, + print_summary) from platformio.commands.run.processor import EnvironmentProcessor from platformio.project.config import ProjectConfig from platformio.project.helpers import (find_project_dir_above, @@ -34,25 +35,21 @@ from platformio.project.helpers import (find_project_dir_above, @click.option("-e", "--environment", multiple=True) @click.option("-t", "--target", multiple=True) @click.option("--upload-port") -@click.option( - "-d", - "--project-dir", - default=getcwd, - type=click.Path( - exists=True, - file_okay=True, - dir_okay=True, - writable=True, - resolve_path=True)) -@click.option( - "-c", - "--project-conf", - type=click.Path( - exists=True, - file_okay=True, - dir_okay=False, - readable=True, - resolve_path=True)) +@click.option("-d", + "--project-dir", + default=getcwd, + type=click.Path(exists=True, + file_okay=True, + dir_okay=True, + writable=True, + resolve_path=True)) +@click.option("-c", + "--project-conf", + type=click.Path(exists=True, + file_okay=True, + dir_okay=False, + readable=True, + resolve_path=True)) @click.option("-s", "--silent", is_flag=True) @click.option("-v", "--verbose", is_flag=True) @click.option("--disable-auto-clean", is_flag=True) @@ -93,8 +90,8 @@ def cli(ctx, environment, target, upload_port, project_dir, project_conf, results.append((envname, None)) continue - if not silent and any( - status is not None for (_, status) in results): + if not silent and any(status is not None + for (_, status) in results): click.echo() ep = EnvironmentProcessor(ctx, envname, config, target, @@ -104,9 +101,8 @@ def cli(ctx, environment, target, upload_port, project_dir, project_conf, 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) + ctx.invoke(cmd_device_monitor, + environment=environment[0] if environment else None) found_error = any(status is False for (_, status) in results) diff --git a/platformio/commands/run/helpers.py b/platformio/commands/run/helpers.py index fd1ac7e3..d1e6b59f 100644 --- a/platformio/commands/run/helpers.py +++ b/platformio/commands/run/helpers.py @@ -22,8 +22,9 @@ from platformio import exception, util from platformio.commands.lib import (CTX_META_STORAGE_DIRS_KEY, CTX_META_STORAGE_LIBDEPS_KEY) from platformio.commands.lib import lib_install as cmd_lib_install -from platformio.project.helpers import ( - calculate_project_hash, get_project_dir, get_project_libdeps_dir) +from platformio.project.helpers import (calculate_project_hash, + get_project_dir, + get_project_libdeps_dir) def _handle_legacy_libdeps(project_dir, config): @@ -71,8 +72,8 @@ def _clean_build_dir(build_dir): proj_hash = calculate_project_hash() # if project's config is modified - if (isdir(build_dir) and getmtime( - join(get_project_dir(), "platformio.ini")) > getmtime(build_dir)): + if (isdir(build_dir) and getmtime(join( + get_project_dir(), "platformio.ini")) > getmtime(build_dir)): util.rmtree_(build_dir) # check project structure @@ -93,8 +94,9 @@ def print_header(label, is_error=False, fg=None): terminal_width, _ = click.get_terminal_size() width = len(click.unstyle(label)) half_line = "=" * int((terminal_width - width - 2) / 2) - click.secho( - "%s %s %s" % (half_line, label, half_line), fg=fg, err=is_error) + click.secho("%s %s %s" % (half_line, label, half_line), + fg=fg, + err=is_error) def print_summary(results, start_time): @@ -115,13 +117,12 @@ def print_summary(results, start_time): status_str = click.style("SUCCESS", fg="green") format_str = "Environment {0:<%d}\t[{1}]" % envname_max_len - click.echo( - format_str.format(click.style(envname, fg="cyan"), status_str), - err=status is False) + click.echo(format_str.format(click.style(envname, fg="cyan"), + status_str), + err=status is False) - print_header( - "%s%d succeeded in %.2f seconds" % - ("%d failed, " % failed_nums if failed_nums else "", succeeded_nums, - time() - start_time), - is_error=failed_nums, - fg="red" if failed_nums else "green") + print_header("%s%d succeeded in %.2f seconds" % + ("%d failed, " % failed_nums if failed_nums else "", + succeeded_nums, time() - start_time), + is_error=failed_nums, + fg="red" if failed_nums else "green") diff --git a/platformio/commands/run/processor.py b/platformio/commands/run/processor.py index 6d57f257..f507780a 100644 --- a/platformio/commands/run/processor.py +++ b/platformio/commands/run/processor.py @@ -64,10 +64,10 @@ class EnvironmentProcessor(object): if is_error or "piotest_processor" not in self.cmd_ctx.meta: print_header( - "[%s] Took %.2f seconds" % ( - (click.style("ERROR", fg="red", bold=True) if is_error else - click.style("SUCCESS", fg="green", bold=True)), - time() - start_time), + "[%s] Took %.2f seconds" % + ((click.style("ERROR", fg="red", bold=True) if + is_error else click.style("SUCCESS", fg="green", bold=True)), + time() - start_time), is_error=is_error) return not is_error @@ -106,10 +106,9 @@ class EnvironmentProcessor(object): try: p = PlatformFactory.newPlatform(self.options['platform']) except exception.UnknownPlatform: - self.cmd_ctx.invoke( - cmd_platform_install, - platforms=[self.options['platform']], - skip_default_package=True) + self.cmd_ctx.invoke(cmd_platform_install, + platforms=[self.options['platform']], + skip_default_package=True) p = PlatformFactory.newPlatform(self.options['platform']) return p.run(build_vars, build_targets, self.silent, self.verbose) diff --git a/platformio/commands/settings.py b/platformio/commands/settings.py index a29d3997..d1d5ad59 100644 --- a/platformio/commands/settings.py +++ b/platformio/commands/settings.py @@ -30,11 +30,10 @@ def settings_get(name): terminal_width, _ = click.get_terminal_size() click.echo( - list_tpl.format( - name=click.style("Name", fg="cyan"), - value=(click.style("Value", fg="green") + click.style( - " [Default]", fg="yellow")), - description="Description")) + list_tpl.format(name=click.style("Name", fg="cyan"), + value=(click.style("Value", fg="green") + + click.style(" [Default]", fg="yellow")), + description="Description")) click.echo("-" * terminal_width) for _name, _data in sorted(app.DEFAULT_SETTINGS.items()): @@ -56,10 +55,9 @@ def settings_get(name): _value_str += click.style(" ", fg="yellow") click.echo( - list_tpl.format( - name=click.style(_name, fg="cyan"), - value=_value_str, - description=_data['description'])) + list_tpl.format(name=click.style(_name, fg="cyan"), + value=_value_str, + description=_data['description'])) @cli.command("set", short_help="Set new value for the setting") diff --git a/platformio/commands/test/command.py b/platformio/commands/test/command.py index 87a84424..d330a410 100644 --- a/platformio/commands/test/command.py +++ b/platformio/commands/test/command.py @@ -31,53 +31,45 @@ from platformio.project.helpers import get_project_test_dir @click.command("test", short_help="Unit Testing") @click.option("--environment", "-e", multiple=True, metavar="") -@click.option( - "--filter", - "-f", - multiple=True, - metavar="", - help="Filter tests by a pattern") -@click.option( - "--ignore", - "-i", - multiple=True, - metavar="", - help="Ignore tests by a pattern") +@click.option("--filter", + "-f", + multiple=True, + metavar="", + help="Filter tests by a pattern") +@click.option("--ignore", + "-i", + multiple=True, + metavar="", + help="Ignore tests by a pattern") @click.option("--upload-port") @click.option("--test-port") -@click.option( - "-d", - "--project-dir", - default=getcwd, - type=click.Path( - exists=True, - file_okay=False, - dir_okay=True, - writable=True, - resolve_path=True)) -@click.option( - "-c", - "--project-conf", - type=click.Path( - exists=True, - file_okay=True, - dir_okay=False, - readable=True, - resolve_path=True)) +@click.option("-d", + "--project-dir", + default=getcwd, + type=click.Path(exists=True, + file_okay=False, + dir_okay=True, + writable=True, + resolve_path=True)) +@click.option("-c", + "--project-conf", + type=click.Path(exists=True, + file_okay=True, + dir_okay=False, + readable=True, + resolve_path=True)) @click.option("--without-building", is_flag=True) @click.option("--without-uploading", is_flag=True) @click.option("--without-testing", is_flag=True) @click.option("--no-reset", is_flag=True) -@click.option( - "--monitor-rts", - default=None, - type=click.IntRange(0, 1), - help="Set initial RTS line state for Serial Monitor") -@click.option( - "--monitor-dtr", - default=None, - type=click.IntRange(0, 1), - help="Set initial DTR line state for Serial Monitor") +@click.option("--monitor-rts", + default=None, + type=click.IntRange(0, 1), + help="Set initial RTS line state for Serial Monitor") +@click.option("--monitor-dtr", + default=None, + type=click.IntRange(0, 1), + help="Set initial DTR line state for Serial Monitor") @click.option("--verbose", "-v", is_flag=True) @click.pass_context def cli( # pylint: disable=redefined-builtin @@ -130,18 +122,17 @@ def cli( # pylint: disable=redefined-builtin EmbeddedTestProcessor) tp = cls( ctx, testname, envname, - dict( - project_config=config, - project_dir=project_dir, - upload_port=upload_port, - test_port=test_port, - without_building=without_building, - without_uploading=without_uploading, - without_testing=without_testing, - no_reset=no_reset, - monitor_rts=monitor_rts, - monitor_dtr=monitor_dtr, - verbose=verbose)) + dict(project_config=config, + project_dir=project_dir, + upload_port=upload_port, + test_port=test_port, + without_building=without_building, + without_uploading=without_uploading, + without_testing=without_testing, + no_reset=no_reset, + monitor_rts=monitor_rts, + monitor_dtr=monitor_dtr, + verbose=verbose)) results.append((tp.process(), testname, envname)) if without_testing: @@ -168,17 +159,15 @@ def cli( # pylint: disable=redefined-builtin format_str = "test/{:<%d} > {:<%d}\t[{}]" % (testname_max_len, envname_max_len) - click.echo( - format_str.format(testname, click.style(envname, fg="cyan"), - status_str), - err=status is False) + click.echo(format_str.format(testname, click.style(envname, fg="cyan"), + status_str), + err=status is False) - print_header( - "%s%d passed in %.2f seconds" - % ("%d failed, " % failed_nums if failed_nums else "", passed_nums, - time() - start_time), - is_error=failed_nums, - fg="red" if failed_nums else "green") + print_header("%s%d passed in %.2f seconds" % + ("%d failed, " % failed_nums if failed_nums else "", + passed_nums, time() - start_time), + is_error=failed_nums, + fg="red" if failed_nums else "green") if failed_nums: raise exception.ReturnErrorCode(1) diff --git a/platformio/commands/test/embedded.py b/platformio/commands/test/embedded.py index 449763db..681bfb44 100644 --- a/platformio/commands/test/embedded.py +++ b/platformio/commands/test/embedded.py @@ -57,8 +57,8 @@ class EmbeddedTestProcessor(TestProcessorBase): click.echo() try: - ser = serial.Serial( - baudrate=self.get_baudrate(), timeout=self.SERIAL_TIMEOUT) + ser = serial.Serial(baudrate=self.get_baudrate(), + timeout=self.SERIAL_TIMEOUT) ser.port = self.get_test_port() ser.rts = self.options['monitor_rts'] ser.dtr = self.options['monitor_dtr'] diff --git a/platformio/commands/test/processor.py b/platformio/commands/test/processor.py index 7b22f5ee..973a3853 100644 --- a/platformio/commands/test/processor.py +++ b/platformio/commands/test/processor.py @@ -86,8 +86,8 @@ class TestProcessorBase(object): self.test_name = testname self.options = options self.env_name = envname - self.env_options = options['project_config'].items( - env=envname, as_dict=True) + self.env_options = options['project_config'].items(env=envname, + as_dict=True) self._run_failed = False self._outputcpp_generated = False @@ -108,11 +108,10 @@ class TestProcessorBase(object): def print_progress(self, text, is_error=False): click.echo() - print_header( - "[test/%s > %s] %s" % (click.style(self.test_name, fg="yellow"), - click.style(self.env_name, fg="cyan"), - text), - is_error=is_error) + print_header("[test/%s > %s] %s" % + (click.style(self.test_name, fg="yellow"), + click.style(self.env_name, fg="cyan"), text), + is_error=is_error) def build_or_upload(self, target): if not self._outputcpp_generated: @@ -126,14 +125,13 @@ class TestProcessorBase(object): click.echo("Please wait...") try: - return self.cmd_ctx.invoke( - cmd_run, - project_dir=self.options['project_dir'], - upload_port=self.options['upload_port'], - silent=not self.options['verbose'], - environment=[self.env_name], - disable_auto_clean="nobuild" in target, - target=target) + return self.cmd_ctx.invoke(cmd_run, + project_dir=self.options['project_dir'], + upload_port=self.options['upload_port'], + silent=not self.options['verbose'], + environment=[self.env_name], + disable_auto_clean="nobuild" in target, + target=target) except exception.ReturnErrorCode: return False @@ -146,8 +144,8 @@ class TestProcessorBase(object): def on_run_out(self, line): line = line.strip() if line.endswith(":PASS"): - click.echo( - "%s\t[%s]" % (line[:-5], click.style("PASSED", fg="green"))) + click.echo("%s\t[%s]" % + (line[:-5], click.style("PASSED", fg="green"))) elif ":FAIL" in line: self._run_failed = True click.echo("%s\t[%s]" % (line, click.style("FAILED", fg="red"))) diff --git a/platformio/commands/update.py b/platformio/commands/update.py index 78d2f8bd..dc6ed1c6 100644 --- a/platformio/commands/update.py +++ b/platformio/commands/update.py @@ -22,19 +22,18 @@ from platformio.managers.core import update_core_packages from platformio.managers.lib import LibraryManager -@click.command( - "update", short_help="Update installed platforms, packages and libraries") -@click.option( - "--core-packages", is_flag=True, help="Update only the core packages") -@click.option( - "-c", - "--only-check", - is_flag=True, - help="DEPRECATED. Please use `--dry-run` instead") -@click.option( - "--dry-run", - is_flag=True, - help="Do not update, only check for the new versions") +@click.command("update", + short_help="Update installed platforms, packages and libraries") +@click.option("--core-packages", + is_flag=True, + help="Update only the core packages") +@click.option("-c", + "--only-check", + is_flag=True, + help="DEPRECATED. Please use `--dry-run` instead") +@click.option("--dry-run", + is_flag=True, + help="Do not update, only check for the new versions") @click.pass_context def cli(ctx, core_packages, only_check, dry_run): # cleanup lib search results, cached board and platform lists diff --git a/platformio/commands/upgrade.py b/platformio/commands/upgrade.py index 2c6b367e..91286230 100644 --- a/platformio/commands/upgrade.py +++ b/platformio/commands/upgrade.py @@ -26,8 +26,8 @@ from platformio.proc import exec_command, get_pythonexe_path from platformio.project.helpers import get_project_cache_dir -@click.command( - "upgrade", short_help="Upgrade PlatformIO to the latest version") +@click.command("upgrade", + short_help="Upgrade PlatformIO to the latest version") @click.option("--dev", is_flag=True, help="Use development branch") def cli(dev): if not dev and __version__ == get_latest_version(): @@ -60,20 +60,19 @@ def cli(dev): assert r['returncode'] == 0 assert "version" in r['out'] actual_version = r['out'].strip().split("version", 1)[1].strip() - click.secho( - "PlatformIO has been successfully upgraded to %s" % actual_version, - fg="green") + click.secho("PlatformIO has been successfully upgraded to %s" % + actual_version, + fg="green") click.echo("Release notes: ", nl=False) - click.secho( - "https://docs.platformio.org/en/latest/history.html", fg="cyan") + click.secho("https://docs.platformio.org/en/latest/history.html", + fg="cyan") except Exception as e: # pylint: disable=broad-except if not r: raise exception.UpgradeError("\n".join([str(cmd), str(e)])) permission_errors = ("permission denied", "not permitted") if (any(m in r['err'].lower() for m in permission_errors) and not WINDOWS): - click.secho( - """ + click.secho(""" ----------------- Permission denied ----------------- @@ -83,8 +82,8 @@ You need the `sudo` permission to install Python packages. Try WARNING! Don't use `sudo` for the rest PlatformIO commands. """, - fg="yellow", - err=True) + fg="yellow", + err=True) raise exception.ReturnErrorCode(1) raise exception.UpgradeError("\n".join([str(cmd), r['out'], r['err']])) @@ -150,8 +149,7 @@ def get_develop_latest_version(): def get_pypi_latest_version(): - r = requests.get( - "https://pypi.org/pypi/platformio/json", - headers=util.get_request_defheaders()) + r = requests.get("https://pypi.org/pypi/platformio/json", + headers=util.get_request_defheaders()) r.raise_for_status() return r.json()['info']['version'] diff --git a/platformio/downloader.py b/platformio/downloader.py index ab84e518..be5e8888 100644 --- a/platformio/downloader.py +++ b/platformio/downloader.py @@ -35,11 +35,10 @@ class FileDownloader(object): def __init__(self, url, dest_dir=None): self._request = None # make connection - self._request = requests.get( - url, - stream=True, - headers=util.get_request_defheaders(), - verify=version_info >= (2, 7, 9)) + self._request = requests.get(url, + stream=True, + headers=util.get_request_defheaders(), + verify=version_info >= (2, 7, 9)) if self._request.status_code != 200: raise FDUnrecognizedStatusCode(self._request.status_code, url) diff --git a/platformio/ide/projectgenerator.py b/platformio/ide/projectgenerator.py index 3482db28..e420802a 100644 --- a/platformio/ide/projectgenerator.py +++ b/platformio/ide/projectgenerator.py @@ -26,8 +26,9 @@ from platformio.commands.run import cli as cmd_run from platformio.compat import PY2, WINDOWS, get_file_contents from platformio.proc import where_is_program from platformio.project.config import ProjectConfig -from platformio.project.helpers import ( - get_project_lib_dir, get_project_libdeps_dir, get_project_src_dir) +from platformio.project.helpers import (get_project_lib_dir, + get_project_libdeps_dir, + get_project_src_dir) class ProjectGenerator(object): @@ -120,9 +121,8 @@ class ProjectGenerator(object): file_name = basename(tpl_path)[:-4] contents = self._render_tpl(tpl_path) - self._merge_contents( - join(dst_dir, file_name), - contents.encode("utf8") if PY2 else contents) + self._merge_contents(join(dst_dir, file_name), + contents.encode("utf8") if PY2 else contents) def _render_tpl(self, tpl_path): return bottle.template(get_file_contents(tpl_path), **self._tplvars) diff --git a/platformio/maintenance.py b/platformio/maintenance.py index ea7c75f2..b1e2d7b9 100644 --- a/platformio/maintenance.py +++ b/platformio/maintenance.py @@ -92,12 +92,12 @@ class Upgrader(object): self.to_version = semantic_version.Version.coerce( util.pepver_to_semver(to_version)) - self._upgraders = [(semantic_version.Version("3.0.0-a.1"), - self._upgrade_to_3_0_0), - (semantic_version.Version("3.0.0-b.11"), - self._upgrade_to_3_0_0b11), - (semantic_version.Version("3.5.0-a.2"), - self._update_dev_platforms)] + self._upgraders = [ + (semantic_version.Version("3.0.0-a.1"), self._upgrade_to_3_0_0), + (semantic_version.Version("3.0.0-b.11"), + self._upgrade_to_3_0_0b11), + (semantic_version.Version("3.5.0-a.2"), self._update_dev_platforms) + ] def run(self, ctx): if self.from_version > self.to_version: @@ -166,12 +166,11 @@ def after_upgrade(ctx): last_version)) > semantic_version.Version.coerce( util.pepver_to_semver(__version__)): click.secho("*" * terminal_width, fg="yellow") - click.secho( - "Obsolete PIO Core v%s is used (previous was %s)" % (__version__, - last_version), - fg="yellow") - click.secho( - "Please remove multiple PIO Cores from a system:", fg="yellow") + click.secho("Obsolete PIO Core v%s is used (previous was %s)" % + (__version__, last_version), + fg="yellow") + click.secho("Please remove multiple PIO Cores from a system:", + fg="yellow") click.secho( "https://docs.platformio.org/page/faq.html" "#multiple-pio-cores-in-a-system", @@ -188,22 +187,20 @@ def after_upgrade(ctx): u = Upgrader(last_version, __version__) if u.run(ctx): app.set_state_item("last_version", __version__) - click.secho( - "PlatformIO has been successfully upgraded to %s!\n" % - __version__, - fg="green") - telemetry.on_event( - category="Auto", - action="Upgrade", - label="%s > %s" % (last_version, __version__)) + click.secho("PlatformIO has been successfully upgraded to %s!\n" % + __version__, + fg="green") + telemetry.on_event(category="Auto", + action="Upgrade", + label="%s > %s" % (last_version, __version__)) else: raise exception.UpgradeError("Auto upgrading...") click.echo("") # PlatformIO banner click.echo("*" * terminal_width) - click.echo( - "If you like %s, please:" % (click.style("PlatformIO", fg="cyan"))) + click.echo("If you like %s, please:" % + (click.style("PlatformIO", fg="cyan"))) click.echo("- %s us on Twitter to stay up-to-date " "on the latest project news > %s" % (click.style("follow", fg="cyan"), @@ -218,9 +215,9 @@ def after_upgrade(ctx): (click.style("try", fg="cyan"), click.style("https://platformio.org/platformio-ide", fg="cyan"))) if not is_ci(): - click.echo("- %s us with PlatformIO Plus > %s" % (click.style( - "support", fg="cyan"), click.style( - "https://pioplus.com", fg="cyan"))) + click.echo("- %s us with PlatformIO Plus > %s" % + (click.style("support", fg="cyan"), + click.style("https://pioplus.com", fg="cyan"))) click.echo("*" * terminal_width) click.echo("") @@ -250,14 +247,14 @@ def check_platformio_upgrade(): click.echo("") click.echo("*" * terminal_width) - click.secho( - "There is a new version %s of PlatformIO available.\n" - "Please upgrade it via `" % latest_version, - fg="yellow", - nl=False) + click.secho("There is a new version %s of PlatformIO available.\n" + "Please upgrade it via `" % latest_version, + fg="yellow", + nl=False) if getenv("PLATFORMIO_IDE"): - click.secho( - "PlatformIO IDE Menu: Upgrade PlatformIO", fg="cyan", nl=False) + click.secho("PlatformIO IDE Menu: Upgrade PlatformIO", + fg="cyan", + nl=False) click.secho("`.", fg="yellow") elif join("Cellar", "platformio") in util.get_source_dir(): click.secho("brew update && brew upgrade", fg="cyan", nl=False) @@ -268,8 +265,8 @@ def check_platformio_upgrade(): click.secho("pip install -U platformio", fg="cyan", nl=False) click.secho("` command.", fg="yellow") click.secho("Changes: ", fg="yellow", nl=False) - click.secho( - "https://docs.platformio.org/en/latest/history.html", fg="cyan") + click.secho("https://docs.platformio.org/en/latest/history.html", + fg="cyan") click.echo("*" * terminal_width) click.echo("") @@ -305,29 +302,26 @@ def check_internal_updates(ctx, what): click.echo("") click.echo("*" * terminal_width) - click.secho( - "There are the new updates for %s (%s)" % (what, - ", ".join(outdated_items)), - fg="yellow") + click.secho("There are the new updates for %s (%s)" % + (what, ", ".join(outdated_items)), + fg="yellow") if not app.get_setting("auto_update_" + what): click.secho("Please update them via ", fg="yellow", nl=False) - click.secho( - "`platformio %s update`" % - ("lib --global" if what == "libraries" else "platform"), - fg="cyan", - nl=False) + click.secho("`platformio %s update`" % + ("lib --global" if what == "libraries" else "platform"), + fg="cyan", + nl=False) click.secho(" command.\n", fg="yellow") click.secho( "If you want to manually check for the new versions " "without updating, please use ", fg="yellow", nl=False) - click.secho( - "`platformio %s update --dry-run`" % - ("lib --global" if what == "libraries" else "platform"), - fg="cyan", - nl=False) + click.secho("`platformio %s update --dry-run`" % + ("lib --global" if what == "libraries" else "platform"), + fg="cyan", + nl=False) click.secho(" command.", fg="yellow") else: click.secho("Please wait while updating %s ..." % what, fg="yellow") @@ -338,8 +332,9 @@ def check_internal_updates(ctx, what): ctx.invoke(cmd_lib_update, libraries=outdated_items) click.echo() - telemetry.on_event( - category="Auto", action="Update", label=what.title()) + telemetry.on_event(category="Auto", + action="Update", + label=what.title()) click.echo("*" * terminal_width) click.echo("") diff --git a/platformio/managers/core.py b/platformio/managers/core.py index 8e8afaaf..6efc19f9 100644 --- a/platformio/managers/core.py +++ b/platformio/managers/core.py @@ -111,8 +111,8 @@ def shutdown_piohome_servers(): port = 8010 while port < 8050: try: - requests.get( - "http://127.0.0.1:%d?__shutdown__=1" % port, timeout=0.01) + requests.get("http://127.0.0.1:%d?__shutdown__=1" % port, + timeout=0.01) except: # pylint: disable=bare-except pass port += 1 diff --git a/platformio/managers/lib.py b/platformio/managers/lib.py index 9824afcd..1c0d04dd 100644 --- a/platformio/managers/lib.py +++ b/platformio/managers/lib.py @@ -190,14 +190,12 @@ class LibraryManager(BasePkgManager): def get_latest_repo_version(self, name, requirements, silent=False): item = self.max_satisfying_repo_version( - util.get_api_result( - "/lib/info/%d" % self.search_lib_id( - { - "name": name, - "requirements": requirements - }, - silent=silent), - cache_valid="1h")['versions'], requirements) + util.get_api_result("/lib/info/%d" % self.search_lib_id( + { + "name": name, + "requirements": requirements + }, silent=silent), + cache_valid="1h")['versions'], requirements) return item['name'] if item else None def _install_from_piorepo(self, name, requirements): @@ -206,10 +204,9 @@ class LibraryManager(BasePkgManager): if not version: raise exception.UndefinedPackageVersion(requirements or "latest", util.get_systype()) - dl_data = util.get_api_result( - "/lib/download/" + str(name[3:]), - dict(version=version), - cache_valid="30d") + dl_data = util.get_api_result("/lib/download/" + str(name[3:]), + dict(version=version), + cache_valid="30d") assert dl_data return self._install_from_url( @@ -231,8 +228,8 @@ class LibraryManager(BasePkgManager): # looking in PIO Library Registry if not silent: - click.echo("Looking for %s library in registry" % click.style( - filters['name'], fg="cyan")) + click.echo("Looking for %s library in registry" % + click.style(filters['name'], fg="cyan")) query = [] for key in filters: if key not in ("name", "authors", "frameworks", "platforms"): @@ -245,19 +242,19 @@ class LibraryManager(BasePkgManager): (key[:-1] if key.endswith("s") else key, value)) lib_info = None - result = util.get_api_result( - "/v2/lib/search", dict(query=" ".join(query)), cache_valid="1h") + result = util.get_api_result("/v2/lib/search", + dict(query=" ".join(query)), + cache_valid="1h") if result['total'] == 1: lib_info = result['items'][0] elif result['total'] > 1: if silent and not interactive: lib_info = result['items'][0] else: - click.secho( - "Conflict: More than one library has been found " - "by request %s:" % json.dumps(filters), - fg="yellow", - err=True) + click.secho("Conflict: More than one library has been found " + "by request %s:" % json.dumps(filters), + fg="yellow", + err=True) for item in result['items']: commands.lib.print_lib_item(item) @@ -269,10 +266,11 @@ class LibraryManager(BasePkgManager): err=True) lib_info = result['items'][0] else: - deplib_id = click.prompt( - "Please choose library ID", - type=click.Choice( - [str(i['id']) for i in result['items']])) + deplib_id = click.prompt("Please choose library ID", + type=click.Choice([ + str(i['id']) + for i in result['items'] + ])) for item in result['items']: if item['id'] == int(deplib_id): lib_info = item @@ -306,9 +304,8 @@ class LibraryManager(BasePkgManager): continue if key not in manifest: return None - if not util.items_in_list( - util.items_to_list(filters[key]), - util.items_to_list(manifest[key])): + if not util.items_in_list(util.items_to_list(filters[key]), + util.items_to_list(manifest[key])): return None if "authors" in filters: @@ -339,20 +336,20 @@ class LibraryManager(BasePkgManager): force=False): _name, _requirements, _url = self.parse_pkg_uri(name, requirements) if not _url: - name = "id=%d" % self.search_lib_id({ - "name": _name, - "requirements": _requirements - }, - silent=silent, - interactive=interactive) + name = "id=%d" % self.search_lib_id( + { + "name": _name, + "requirements": _requirements + }, + silent=silent, + interactive=interactive) requirements = _requirements - pkg_dir = BasePkgManager.install( - self, - name, - requirements, - silent=silent, - after_update=after_update, - force=force) + pkg_dir = BasePkgManager.install(self, + name, + requirements, + silent=silent, + after_update=after_update, + force=force) if not pkg_dir: return None @@ -376,12 +373,11 @@ class LibraryManager(BasePkgManager): self.INSTALL_HISTORY.append(history_key) if any(s in filters.get("version", "") for s in ("\\", "/")): - self.install( - "{name}={version}".format(**filters), - silent=silent, - after_update=after_update, - interactive=interactive, - force=force) + self.install("{name}={version}".format(**filters), + silent=silent, + after_update=after_update, + interactive=interactive, + force=force) else: try: lib_id = self.search_lib_id(filters, silent, interactive) @@ -391,20 +387,18 @@ class LibraryManager(BasePkgManager): continue if filters.get("version"): - self.install( - lib_id, - filters.get("version"), - silent=silent, - after_update=after_update, - interactive=interactive, - force=force) + self.install(lib_id, + filters.get("version"), + silent=silent, + after_update=after_update, + interactive=interactive, + force=force) else: - self.install( - lib_id, - silent=silent, - after_update=after_update, - interactive=interactive, - force=force) + self.install(lib_id, + silent=silent, + after_update=after_update, + interactive=interactive, + force=force) return pkg_dir diff --git a/platformio/managers/package.py b/platformio/managers/package.py index cd0f0d1a..905fb32f 100644 --- a/platformio/managers/package.py +++ b/platformio/managers/package.py @@ -92,8 +92,8 @@ class PkgRepoMixin(object): reqspec = None if requirements: try: - reqspec = self.parse_semver_spec( - requirements, raise_exception=True) + reqspec = self.parse_semver_spec(requirements, + raise_exception=True) except ValueError: pass @@ -430,8 +430,8 @@ class PkgInstallerMixin(object): try: if requirements and not self.parse_semver_spec( requirements, raise_exception=True).match( - self.parse_semver_version( - manifest['version'], raise_exception=True)): + self.parse_semver_version(manifest['version'], + raise_exception=True)): continue elif not best or (self.parse_semver_version( manifest['version'], raise_exception=True) > @@ -648,8 +648,9 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin): if "__src_url" in manifest: try: - vcs = VCSClientFactory.newClient( - pkg_dir, manifest['__src_url'], silent=True) + vcs = VCSClientFactory.newClient(pkg_dir, + manifest['__src_url'], + silent=True) except (AttributeError, exception.PlatformioException): return None if not vcs.can_be_updated: @@ -658,8 +659,8 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin): else: try: latest = self.get_latest_repo_version( - "id=%d" % manifest['id'] - if "id" in manifest else manifest['name'], + "id=%d" % + manifest['id'] if "id" in manifest else manifest['name'], requirements, silent=True) except (exception.PlatformioException, ValueError): @@ -671,10 +672,10 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin): up_to_date = False try: assert "__src_url" not in manifest - up_to_date = (self.parse_semver_version( - manifest['version'], raise_exception=True) >= - self.parse_semver_version( - latest, raise_exception=True)) + up_to_date = (self.parse_semver_version(manifest['version'], + raise_exception=True) >= + self.parse_semver_version(latest, + raise_exception=True)) except (AssertionError, ValueError): up_to_date = latest == manifest['version'] @@ -720,8 +721,10 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin): return package_dir if url: - pkg_dir = self._install_from_url( - name, url, requirements, track=True) + pkg_dir = self._install_from_url(name, + url, + requirements, + track=True) else: pkg_dir = self._install_from_piorepo(name, requirements) @@ -733,10 +736,9 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin): assert manifest if not after_update: - telemetry.on_event( - category=self.__class__.__name__, - action="Install", - label=manifest['name']) + telemetry.on_event(category=self.__class__.__name__, + action="Install", + label=manifest['name']) if not silent: click.secho( @@ -759,14 +761,13 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin): pkg_dir = self.get_package_dir(name, requirements, url) if not pkg_dir: - raise exception.UnknownPackage( - "%s @ %s" % (package, requirements or "*")) + raise exception.UnknownPackage("%s @ %s" % + (package, requirements or "*")) manifest = self.load_manifest(pkg_dir) - click.echo( - "Uninstalling %s @ %s: \t" % (click.style( - manifest['name'], fg="cyan"), manifest['version']), - nl=False) + click.echo("Uninstalling %s @ %s: \t" % (click.style( + manifest['name'], fg="cyan"), manifest['version']), + nl=False) if islink(pkg_dir): os.unlink(pkg_dir) @@ -785,10 +786,9 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin): click.echo("[%s]" % click.style("OK", fg="green")) if not after_update: - telemetry.on_event( - category=self.__class__.__name__, - action="Uninstall", - label=manifest['name']) + telemetry.on_event(category=self.__class__.__name__, + action="Uninstall", + label=manifest['name']) return True @@ -799,17 +799,16 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin): pkg_dir = self.get_package_dir(*self.parse_pkg_uri(package)) if not pkg_dir: - raise exception.UnknownPackage( - "%s @ %s" % (package, requirements or "*")) + raise exception.UnknownPackage("%s @ %s" % + (package, requirements or "*")) manifest = self.load_manifest(pkg_dir) name = manifest['name'] - click.echo( - "{} {:<40} @ {:<15}".format( - "Checking" if only_check else "Updating", - click.style(manifest['name'], fg="cyan"), manifest['version']), - nl=False) + click.echo("{} {:<40} @ {:<15}".format( + "Checking" if only_check else "Updating", + click.style(manifest['name'], fg="cyan"), manifest['version']), + nl=False) if not util.internet_on(): click.echo("[%s]" % (click.style("Off-line", fg="yellow"))) return None @@ -828,16 +827,15 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin): if "__src_url" in manifest: vcs = VCSClientFactory.newClient(pkg_dir, manifest['__src_url']) assert vcs.update() - self._update_src_manifest( - dict(version=vcs.get_current_revision()), vcs.storage_dir) + self._update_src_manifest(dict(version=vcs.get_current_revision()), + vcs.storage_dir) else: self.uninstall(pkg_dir, after_update=True) self.install(name, latest, after_update=True) - telemetry.on_event( - category=self.__class__.__name__, - action="Update", - label=manifest['name']) + telemetry.on_event(category=self.__class__.__name__, + action="Update", + label=manifest['name']) return True diff --git a/platformio/managers/platform.py b/platformio/managers/platform.py index 81982219..7aa153f8 100644 --- a/platformio/managers/platform.py +++ b/platformio/managers/platform.py @@ -30,9 +30,10 @@ from platformio.managers.package import BasePkgManager, PackageManager from platformio.proc import (BuildAsyncPipe, copy_pythonpath_to_osenv, exec_command, get_pythonexe_path) from platformio.project.config import ProjectConfig -from platformio.project.helpers import ( - get_project_boards_dir, get_project_core_dir, get_project_packages_dir, - get_project_platforms_dir) +from platformio.project.helpers import (get_project_boards_dir, + get_project_core_dir, + get_project_packages_dir, + get_project_platforms_dir) try: from urllib.parse import quote @@ -75,8 +76,11 @@ class PlatformManager(BasePkgManager): silent=False, force=False, **_): # pylint: disable=too-many-arguments, arguments-differ - platform_dir = BasePkgManager.install( - self, name, requirements, silent=silent, force=force) + platform_dir = BasePkgManager.install(self, + name, + requirements, + silent=silent, + force=force) p = PlatformFactory.newPlatform(platform_dir) # don't cleanup packages or install them after update @@ -84,12 +88,11 @@ class PlatformManager(BasePkgManager): if after_update: return True - p.install_packages( - with_packages, - without_packages, - skip_default_package, - silent=silent, - force=force) + p.install_packages(with_packages, + without_packages, + skip_default_package, + silent=silent, + force=force) return self.cleanup_packages(list(p.packages)) def uninstall(self, package, requirements=None, after_update=False): @@ -141,8 +144,8 @@ class PlatformManager(BasePkgManager): self.cleanup_packages(list(p.packages)) if missed_pkgs: - p.install_packages( - with_packages=list(missed_pkgs), skip_default_package=True) + p.install_packages(with_packages=list(missed_pkgs), + skip_default_package=True) return True @@ -253,8 +256,8 @@ class PlatformFactory(object): cls.load_module(name, join(platform_dir, "platform.py")), cls.get_clsname(name)) else: - platform_cls = type( - str(cls.get_clsname(name)), (PlatformBase, ), {}) + platform_cls = type(str(cls.get_clsname(name)), (PlatformBase, ), + {}) _instance = platform_cls(join(platform_dir, "platform.json")) assert isinstance(_instance, PlatformBase) @@ -285,8 +288,9 @@ class PlatformPackagesMixin(object): elif (name in with_packages or not (skip_default_package or opts.get("optional", False))): if ":" in version: - self.pm.install( - "%s=%s" % (name, version), silent=silent, force=force) + self.pm.install("%s=%s" % (name, version), + silent=silent, + force=force) else: self.pm.install(name, version, silent=silent, force=force) @@ -402,8 +406,8 @@ class PlatformRunMixin(object): cmd.append("%s=%s" % (key.upper(), base64.b64encode(value))) else: cmd.append( - "%s=%s" % (key.upper(), base64.b64encode( - value.encode()).decode())) + "%s=%s" % + (key.upper(), base64.b64encode(value.encode()).decode())) def _write_and_flush(stream, data): stream.write(data) @@ -461,8 +465,8 @@ class PlatformRunMixin(object): """.format(filename=filename, filename_styled=click.style(filename, fg="cyan"), link=click.style( - "https://platformio.org/lib/search?query=header:%s" % quote( - filename, safe=""), + "https://platformio.org/lib/search?query=header:%s" % + quote(filename, safe=""), fg="blue"), dots="*" * (56 + len(filename))) click.echo(banner, err=True) diff --git a/platformio/project/config.py b/platformio/project/config.py index 45e9380c..48a06bf6 100644 --- a/platformio/project/config.py +++ b/platformio/project/config.py @@ -182,8 +182,8 @@ class ProjectConfig(object): except ConfigParser.Error as e: raise exception.InvalidProjectConf(self.path, str(e)) - option_meta = ProjectOptions.get( - "%s.%s" % (section.split(":", 1)[0], option)) + option_meta = ProjectOptions.get("%s.%s" % + (section.split(":", 1)[0], option)) if not option_meta: return value or default @@ -281,8 +281,8 @@ class ProjectConfig(object): warnings.append( "`%s` configuration option in section [%s] is " "deprecated and will be removed in the next release! " - "Please use `%s` instead" % (option, section, - renamed_options[option])) + "Please use `%s` instead" % + (option, section, renamed_options[option])) # rename on-the-fly self._parser.set(section, renamed_options[option], self._parser.get(section, option)) diff --git a/platformio/project/options.py b/platformio/project/options.py index b4bd705a..fd7afd01 100644 --- a/platformio/project/options.py +++ b/platformio/project/options.py @@ -46,41 +46,39 @@ ProjectOptions = OrderedDict([ # [platformio] # ConfigPlatformioOption(name="description"), - ConfigPlatformioOption( - name="env_default", - multiple=True, - sysenvvar="PLATFORMIO_ENV_DEFAULT"), + ConfigPlatformioOption(name="env_default", + multiple=True, + sysenvvar="PLATFORMIO_ENV_DEFAULT"), ConfigPlatformioOption(name="extra_configs", multiple=True), # Dirs - ConfigPlatformioOption( - name="core_dir", - oldnames=["home_dir"], - sysenvvar="PLATFORMIO_CORE_DIR"), - ConfigPlatformioOption( - name="globallib_dir", sysenvvar="PLATFORMIO_GLOBALLIB_DIR"), - ConfigPlatformioOption( - name="platforms_dir", sysenvvar="PLATFORMIO_PLATFORMS_DIR"), - ConfigPlatformioOption( - name="packages_dir", sysenvvar="PLATFORMIO_PACKAGES_DIR"), - ConfigPlatformioOption( - name="cache_dir", sysenvvar="PLATFORMIO_CACHE_DIR"), - ConfigPlatformioOption( - name="workspace_dir", sysenvvar="PLATFORMIO_WORKSPACE_DIR"), - ConfigPlatformioOption( - name="build_dir", sysenvvar="PLATFORMIO_BUILD_DIR"), - ConfigPlatformioOption( - name="libdeps_dir", sysenvvar="PLATFORMIO_LIBDEPS_DIR"), + ConfigPlatformioOption(name="core_dir", + oldnames=["home_dir"], + sysenvvar="PLATFORMIO_CORE_DIR"), + ConfigPlatformioOption(name="globallib_dir", + sysenvvar="PLATFORMIO_GLOBALLIB_DIR"), + ConfigPlatformioOption(name="platforms_dir", + sysenvvar="PLATFORMIO_PLATFORMS_DIR"), + ConfigPlatformioOption(name="packages_dir", + sysenvvar="PLATFORMIO_PACKAGES_DIR"), + ConfigPlatformioOption(name="cache_dir", + sysenvvar="PLATFORMIO_CACHE_DIR"), + ConfigPlatformioOption(name="workspace_dir", + sysenvvar="PLATFORMIO_WORKSPACE_DIR"), + ConfigPlatformioOption(name="build_dir", + sysenvvar="PLATFORMIO_BUILD_DIR"), + ConfigPlatformioOption(name="libdeps_dir", + sysenvvar="PLATFORMIO_LIBDEPS_DIR"), ConfigPlatformioOption(name="lib_dir", sysenvvar="PLATFORMIO_LIB_DIR"), - ConfigPlatformioOption( - name="include_dir", sysenvvar="PLATFORMIO_INCLUDE_DIR"), + ConfigPlatformioOption(name="include_dir", + sysenvvar="PLATFORMIO_INCLUDE_DIR"), ConfigPlatformioOption(name="src_dir", sysenvvar="PLATFORMIO_SRC_DIR"), - ConfigPlatformioOption( - name="test_dir", sysenvvar="PLATFORMIO_TEST_DIR"), - ConfigPlatformioOption( - name="boards_dir", sysenvvar="PLATFORMIO_BOARDS_DIR"), - ConfigPlatformioOption( - name="data_dir", sysenvvar="PLATFORMIO_DATA_DIR"), + ConfigPlatformioOption(name="test_dir", + sysenvvar="PLATFORMIO_TEST_DIR"), + ConfigPlatformioOption(name="boards_dir", + sysenvvar="PLATFORMIO_BOARDS_DIR"), + ConfigPlatformioOption(name="data_dir", + sysenvvar="PLATFORMIO_DATA_DIR"), # # [env] @@ -94,59 +92,49 @@ ProjectOptions = OrderedDict([ # Board ConfigEnvOption(name="board", buildenvvar="BOARD"), - ConfigEnvOption( - name="board_build.mcu", - oldnames=["board_mcu"], - buildenvvar="BOARD_MCU"), - ConfigEnvOption( - name="board_build.f_cpu", - oldnames=["board_f_cpu"], - buildenvvar="BOARD_F_CPU"), - ConfigEnvOption( - name="board_build.f_flash", - oldnames=["board_f_flash"], - buildenvvar="BOARD_F_FLASH"), - ConfigEnvOption( - name="board_build.flash_mode", - oldnames=["board_flash_mode"], - buildenvvar="BOARD_FLASH_MODE"), + ConfigEnvOption(name="board_build.mcu", + oldnames=["board_mcu"], + buildenvvar="BOARD_MCU"), + ConfigEnvOption(name="board_build.f_cpu", + oldnames=["board_f_cpu"], + buildenvvar="BOARD_F_CPU"), + ConfigEnvOption(name="board_build.f_flash", + oldnames=["board_f_flash"], + buildenvvar="BOARD_F_FLASH"), + ConfigEnvOption(name="board_build.flash_mode", + oldnames=["board_flash_mode"], + buildenvvar="BOARD_FLASH_MODE"), # Build - ConfigEnvOption( - name="build_flags", - multiple=True, - sysenvvar="PLATFORMIO_BUILD_FLAGS", - buildenvvar="BUILD_FLAGS"), - ConfigEnvOption( - name="src_build_flags", - multiple=True, - sysenvvar="PLATFORMIO_SRC_BUILD_FLAGS", - buildenvvar="SRC_BUILD_FLAGS"), - ConfigEnvOption( - name="build_unflags", - multiple=True, - sysenvvar="PLATFORMIO_BUILD_UNFLAGS", - buildenvvar="BUILD_UNFLAGS"), - ConfigEnvOption( - name="src_filter", - multiple=True, - sysenvvar="PLATFORMIO_SRC_FILTER", - buildenvvar="SRC_FILTER"), + ConfigEnvOption(name="build_flags", + multiple=True, + sysenvvar="PLATFORMIO_BUILD_FLAGS", + buildenvvar="BUILD_FLAGS"), + ConfigEnvOption(name="src_build_flags", + multiple=True, + sysenvvar="PLATFORMIO_SRC_BUILD_FLAGS", + buildenvvar="SRC_BUILD_FLAGS"), + ConfigEnvOption(name="build_unflags", + multiple=True, + sysenvvar="PLATFORMIO_BUILD_UNFLAGS", + buildenvvar="BUILD_UNFLAGS"), + ConfigEnvOption(name="src_filter", + multiple=True, + sysenvvar="PLATFORMIO_SRC_FILTER", + buildenvvar="SRC_FILTER"), # Upload - ConfigEnvOption( - name="upload_port", - sysenvvar="PLATFORMIO_UPLOAD_PORT", - buildenvvar="UPLOAD_PORT"), + ConfigEnvOption(name="upload_port", + sysenvvar="PLATFORMIO_UPLOAD_PORT", + buildenvvar="UPLOAD_PORT"), ConfigEnvOption(name="upload_protocol", buildenvvar="UPLOAD_PROTOCOL"), ConfigEnvOption(name="upload_speed", buildenvvar="UPLOAD_SPEED"), - ConfigEnvOption( - name="upload_flags", - multiple=True, - sysenvvar="PLATFORMIO_UPLOAD_FLAGS", - buildenvvar="UPLOAD_FLAGS"), - ConfigEnvOption( - name="upload_resetmethod", buildenvvar="UPLOAD_RESETMETHOD"), + ConfigEnvOption(name="upload_flags", + multiple=True, + sysenvvar="PLATFORMIO_UPLOAD_FLAGS", + buildenvvar="UPLOAD_FLAGS"), + ConfigEnvOption(name="upload_resetmethod", + buildenvvar="UPLOAD_RESETMETHOD"), # Monitor ConfigEnvOption(name="monitor_port"), @@ -156,15 +144,13 @@ ProjectOptions = OrderedDict([ ConfigEnvOption(name="monitor_flags", multiple=True), # Library - ConfigEnvOption( - name="lib_deps", - oldnames=["lib_use", "lib_force", "lib_install"], - multiple=True), + ConfigEnvOption(name="lib_deps", + oldnames=["lib_use", "lib_force", "lib_install"], + multiple=True), ConfigEnvOption(name="lib_ignore", multiple=True), - ConfigEnvOption( - name="lib_extra_dirs", - multiple=True, - sysenvvar="PLATFORMIO_LIB_EXTRA_DIRS"), + ConfigEnvOption(name="lib_extra_dirs", + multiple=True, + sysenvvar="PLATFORMIO_LIB_EXTRA_DIRS"), ConfigEnvOption(name="lib_ldf_mode"), ConfigEnvOption(name="lib_compat_mode"), ConfigEnvOption(name="lib_archive", type=bool), @@ -189,10 +175,9 @@ ProjectOptions = OrderedDict([ ConfigEnvOption(name="debug_svd_path"), # Other - ConfigEnvOption( - name="extra_scripts", - oldnames=["extra_script"], - multiple=True, - sysenvvar="PLATFORMIO_EXTRA_SCRIPTS") + ConfigEnvOption(name="extra_scripts", + oldnames=["extra_script"], + multiple=True, + sysenvvar="PLATFORMIO_EXTRA_SCRIPTS") ] ]) diff --git a/platformio/telemetry.py b/platformio/telemetry.py index 071db390..f697a241 100644 --- a/platformio/telemetry.py +++ b/platformio/telemetry.py @@ -338,11 +338,10 @@ def on_exception(e): def _cleanup_description(text): text = text.replace("Traceback (most recent call last):", "") - text = re.sub( - r'File "([^"]+)"', - lambda m: join(*m.group(1).split(sep)[-2:]), - text, - flags=re.M) + text = re.sub(r'File "([^"]+)"', + lambda m: join(*m.group(1).split(sep)[-2:]), + text, + flags=re.M) text = re.sub(r"\s+", " ", text, flags=re.M) return text.strip() diff --git a/platformio/unpacker.py b/platformio/unpacker.py index 58132716..271b4911 100644 --- a/platformio/unpacker.py +++ b/platformio/unpacker.py @@ -74,9 +74,8 @@ class ZIPArchive(ArchiveBase): @staticmethod def preserve_mtime(item, dest_dir): - util.change_filemtime( - join(dest_dir, item.filename), - mktime(tuple(item.date_time) + tuple([0, 0, 0]))) + util.change_filemtime(join(dest_dir, item.filename), + mktime(tuple(item.date_time) + tuple([0, 0, 0]))) def get_items(self): return self._afo.infolist() diff --git a/platformio/util.py b/platformio/util.py index c4dbe537..a7657526 100644 --- a/platformio/util.py +++ b/platformio/util.py @@ -176,8 +176,8 @@ def get_logical_devices(): if WINDOWS: try: result = exec_command( - ["wmic", "logicaldisk", "get", "name,VolumeName"]).get( - "out", "") + ["wmic", "logicaldisk", "get", + "name,VolumeName"]).get("out", "") devicenamere = re.compile(r"^([A-Z]{1}\:)\s*(\S+)?") for line in result.split("\n"): match = devicenamere.match(line.strip()) @@ -321,20 +321,18 @@ def _get_api_result( try: if data: - r = _api_request_session().post( - url, - params=params, - data=data, - headers=headers, - auth=auth, - verify=verify_ssl) + r = _api_request_session().post(url, + params=params, + data=data, + headers=headers, + auth=auth, + verify=verify_ssl) else: - r = _api_request_session().get( - url, - params=params, - headers=headers, - auth=auth, - verify=verify_ssl) + r = _api_request_session().get(url, + params=params, + headers=headers, + auth=auth, + verify=verify_ssl) result = r.json() r.raise_for_status() return r.text @@ -345,8 +343,8 @@ def _get_api_result( raise exception.APIRequestError(result['errors'][0]['title']) raise exception.APIRequestError(e) except ValueError: - raise exception.APIRequestError( - "Invalid response: %s" % r.text.encode("utf-8")) + raise exception.APIRequestError("Invalid response: %s" % + r.text.encode("utf-8")) finally: if r: r.close() @@ -403,11 +401,12 @@ def _internet_on(): for ip in PING_INTERNET_IPS: try: if os.getenv("HTTP_PROXY", os.getenv("HTTPS_PROXY")): - requests.get( - "http://%s" % ip, allow_redirects=False, timeout=timeout) + requests.get("http://%s" % ip, + allow_redirects=False, + timeout=timeout) else: - socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((ip, - 80)) + socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect( + (ip, 80)) return True except: # pylint: disable=bare-except pass @@ -524,9 +523,9 @@ def rmtree_(path): os.chmod(name, stat.S_IWRITE) os.remove(name) except Exception as e: # pylint: disable=broad-except - click.secho( - "%s \nPlease manually remove the file `%s`" % (str(e), name), - fg="red", - err=True) + click.secho("%s \nPlease manually remove the file `%s`" % + (str(e), name), + fg="red", + err=True) return rmtree(path, onerror=_onerror) diff --git a/platformio/vcsclient.py b/platformio/vcsclient.py index 222ba0e5..51f454d0 100644 --- a/platformio/vcsclient.py +++ b/platformio/vcsclient.py @@ -42,10 +42,11 @@ class VCSClientFactory(object): if "#" in remote_url: remote_url, tag = remote_url.rsplit("#", 1) if not type_: - raise PlatformioException( - "VCS: Unknown repository type %s" % remote_url) - obj = getattr(modules[__name__], "%sClient" % type_.title())( - src_dir, remote_url, tag, silent) + raise PlatformioException("VCS: Unknown repository type %s" % + remote_url) + obj = getattr(modules[__name__], + "%sClient" % type_.title())(src_dir, remote_url, tag, + silent) assert isinstance(obj, VCSClientBase) return obj @@ -102,8 +103,8 @@ class VCSClientBase(object): check_call(args, **kwargs) return True except CalledProcessError as e: - raise PlatformioException( - "VCS: Could not process command %s" % e.cmd) + raise PlatformioException("VCS: Could not process command %s" % + e.cmd) def get_cmd_output(self, args, **kwargs): args = [self.command] + args