YAPF 0.27.0

This commit is contained in:
Ivan Kravets
2019-05-30 23:42:15 +03:00
parent 1598c8197e
commit 61db0f1d6a
44 changed files with 920 additions and 1000 deletions

View File

@ -23,15 +23,13 @@ from platformio.commands import PlatformioCLI
from platformio.compat import CYGWIN from platformio.compat import CYGWIN
@click.command( @click.command(cls=PlatformioCLI,
cls=PlatformioCLI, context_settings=dict(help_option_names=["-h", "--help"]))
context_settings=dict(help_option_names=["-h", "--help"]))
@click.version_option(__version__, prog_name="PlatformIO") @click.version_option(__version__, prog_name="PlatformIO")
@click.option( @click.option("--force",
"--force", "-f",
"-f", is_flag=True,
is_flag=True, help="Force to accept any confirmation prompts.")
help="Force to accept any confirmation prompts.")
@click.option("--caller", "-c", help="Caller ID (service).") @click.option("--caller", "-c", help="Caller ID (service).")
@click.pass_context @click.pass_context
def cli(ctx, force, caller): def cli(ctx, force, caller):

View File

@ -72,8 +72,9 @@ def _get_gcc_defines(env):
try: try:
sysenv = environ.copy() sysenv = environ.copy()
sysenv['PATH'] = str(env['ENV']['PATH']) sysenv['PATH'] = str(env['ENV']['PATH'])
result = exec_command( result = exec_command("echo | %s -dM -E -" % env.subst("$CC"),
"echo | %s -dM -E -" % env.subst("$CC"), env=sysenv, shell=True) env=sysenv,
shell=True)
except OSError: except OSError:
return items return items
if result['returncode'] != 0: if result['returncode'] != 0:

View File

@ -54,8 +54,9 @@ class LibBuilderFactory(object):
elif used_frameworks: elif used_frameworks:
clsname = "%sLibBuilder" % used_frameworks[0].title() clsname = "%sLibBuilder" % used_frameworks[0].title()
obj = getattr(sys.modules[__name__], clsname)( obj = getattr(sys.modules[__name__], clsname)(env,
env, path, verbose=verbose) path,
verbose=verbose)
assert isinstance(obj, LibBuilderBase) assert isinstance(obj, LibBuilderBase)
return obj return obj
@ -69,8 +70,8 @@ class LibBuilderFactory(object):
if isfile(join(path, "module.json")): if isfile(join(path, "module.json")):
return ["mbed"] return ["mbed"]
include_re = re.compile( include_re = re.compile(r'^#include\s+(<|")(Arduino|mbed)\.h(<|")',
r'^#include\s+(<|")(Arduino|mbed)\.h(<|")', flags=re.MULTILINE) flags=re.MULTILINE)
# check source files # check source files
for root, _, files in os.walk(path, followlinks=True): for root, _, files in os.walk(path, followlinks=True):
@ -270,12 +271,11 @@ class LibBuilderBase(object):
self.env.ProcessFlags(self.build_flags) self.env.ProcessFlags(self.build_flags)
if self.extra_script: if self.extra_script:
self.env.SConscriptChdir(1) self.env.SConscriptChdir(1)
self.env.SConscript( self.env.SConscript(realpath(self.extra_script),
realpath(self.extra_script), exports={
exports={ "env": self.env,
"env": self.env, "pio_lib_builder": self
"pio_lib_builder": self })
})
self.env.ProcessUnFlags(self.build_unflags) self.env.ProcessUnFlags(self.build_unflags)
def process_dependencies(self): def process_dependencies(self):
@ -290,8 +290,9 @@ class LibBuilderBase(object):
if (key in item and if (key in item and
not util.items_in_list(self.env[env_key], item[key])): not util.items_in_list(self.env[env_key], item[key])):
if self.verbose: if self.verbose:
sys.stderr.write("Skip %s incompatible dependency %s\n" sys.stderr.write(
% (key[:-1], item)) "Skip %s incompatible dependency %s\n" %
(key[:-1], item))
skip = True skip = True
if skip: if skip:
continue continue
@ -404,9 +405,9 @@ class LibBuilderBase(object):
if self != lb: if self != lb:
if _already_depends(lb): if _already_depends(lb):
if self.verbose: if self.verbose:
sys.stderr.write( sys.stderr.write("Warning! Circular dependencies detected "
"Warning! Circular dependencies detected " "between `%s` and `%s`\n" %
"between `%s` and `%s`\n" % (self.path, lb.path)) (self.path, lb.path))
self._circular_deps.append(lb) self._circular_deps.append(lb)
elif lb not in self._depbuilders: elif lb not in self._depbuilders:
self._depbuilders.append(lb) self._depbuilders.append(lb)
@ -648,8 +649,8 @@ class MbedLibBuilder(LibBuilderBase):
for key, options in manifest.get("config", {}).items(): for key, options in manifest.get("config", {}).items():
if "value" not in options: if "value" not in options:
continue continue
macros[key] = dict( macros[key] = dict(name=options.get("macro_name"),
name=options.get("macro_name"), value=options.get("value")) value=options.get("value"))
# overrode items per target # overrode items per target
for target, options in manifest.get("target_overrides", {}).items(): for target, options in manifest.get("target_overrides", {}).items():
@ -669,8 +670,10 @@ class MbedLibBuilder(LibBuilderBase):
if "." not in macro['name']: if "." not in macro['name']:
macro['name'] = "%s.%s" % (manifest.get("name"), macro['name'] = "%s.%s" % (manifest.get("name"),
macro['name']) macro['name'])
macro['name'] = re.sub( macro['name'] = re.sub(r"[^a-z\d]+",
r"[^a-z\d]+", "_", macro['name'], flags=re.I).upper() "_",
macro['name'],
flags=re.I).upper()
macro['name'] = "MBED_CONF_" + macro['name'] macro['name'] = "MBED_CONF_" + macro['name']
if isinstance(macro['value'], bool): if isinstance(macro['value'], bool):
macro['value'] = 1 if macro['value'] else 0 macro['value'] = 1 if macro['value'] else 0
@ -686,8 +689,8 @@ class MbedLibBuilder(LibBuilderBase):
lines.append( lines.append(
"// PlatformIO Library Dependency Finder (LDF)") "// PlatformIO Library Dependency Finder (LDF)")
lines.extend([ lines.extend([
"#define %s %s" % (name, "#define %s %s" %
value if value is not None else "") (name, value if value is not None else "")
for name, value in macros.items() for name, value in macros.items()
]) ])
lines.append("") lines.append("")
@ -919,9 +922,8 @@ def GetLibSourceDirs(env):
def GetLibBuilders(env): # pylint: disable=too-many-branches def GetLibBuilders(env): # pylint: disable=too-many-branches
if "__PIO_LIB_BUILDERS" in DefaultEnvironment(): if "__PIO_LIB_BUILDERS" in DefaultEnvironment():
return sorted( return sorted(DefaultEnvironment()['__PIO_LIB_BUILDERS'],
DefaultEnvironment()['__PIO_LIB_BUILDERS'], key=lambda lb: 0 if lb.dependent else 1)
key=lambda lb: 0 if lb.dependent else 1)
items = [] items = []
verbose = int(ARGUMENTS.get("PIOVERBOSE", 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( if compat_mode == "strict" and not lb.is_platforms_compatible(
env['PIOPLATFORM']): env['PIOPLATFORM']):
if verbose: if verbose:
sys.stderr.write( sys.stderr.write("Platform incompatible library %s\n" %
"Platform incompatible library %s\n" % lb.path) lb.path)
return False return False
if compat_mode == "soft" and "PIOFRAMEWORK" in env and \ if compat_mode == "soft" and "PIOFRAMEWORK" in env and \
not lb.is_frameworks_compatible(env.get("PIOFRAMEWORK", [])): not lb.is_frameworks_compatible(env.get("PIOFRAMEWORK", [])):
if verbose: if verbose:
sys.stderr.write( sys.stderr.write("Framework incompatible library %s\n" %
"Framework incompatible library %s\n" % lb.path) lb.path)
return False return False
return True return True
@ -956,12 +958,14 @@ def GetLibBuilders(env): # pylint: disable=too-many-branches
if item == "__cores__" or not isdir(join(libs_dir, item)): if item == "__cores__" or not isdir(join(libs_dir, item)):
continue continue
try: try:
lb = LibBuilderFactory.new( lb = LibBuilderFactory.new(env,
env, join(libs_dir, item), verbose=verbose) join(libs_dir, item),
verbose=verbose)
except exception.InvalidJSONFile: except exception.InvalidJSONFile:
if verbose: if verbose:
sys.stderr.write("Skip library with broken manifest: %s\n" sys.stderr.write(
% join(libs_dir, item)) "Skip library with broken manifest: %s\n" %
join(libs_dir, item))
continue continue
if _check_lib_builder(lb): if _check_lib_builder(lb):
items.append(lb) items.append(lb)

View File

@ -190,8 +190,8 @@ class InoToCPPConverter(object):
def ConvertInoToCpp(env): def ConvertInoToCpp(env):
src_dir = glob_escape(env.subst("$PROJECTSRC_DIR")) src_dir = glob_escape(env.subst("$PROJECTSRC_DIR"))
ino_nodes = ( ino_nodes = (env.Glob(join(src_dir, "*.ino")) +
env.Glob(join(src_dir, "*.ino")) + env.Glob(join(src_dir, "*.pde"))) env.Glob(join(src_dir, "*.pde")))
if not ino_nodes: if not ino_nodes:
return return
c = InoToCPPConverter(env) c = InoToCPPConverter(env)
@ -297,8 +297,8 @@ def PioClean(env, clean_dir):
def ProcessDebug(env): def ProcessDebug(env):
if not env.subst("$PIODEBUGFLAGS"): if not env.subst("$PIODEBUGFLAGS"):
env.Replace(PIODEBUGFLAGS=["-Og", "-g3", "-ggdb3"]) env.Replace(PIODEBUGFLAGS=["-Og", "-g3", "-ggdb3"])
env.Append( env.Append(BUILD_FLAGS=list(env['PIODEBUGFLAGS']) +
BUILD_FLAGS=list(env['PIODEBUGFLAGS']) + ["-D__PLATFORMIO_DEBUG__"]) ["-D__PLATFORMIO_DEBUG__"])
unflags = ["-Os"] unflags = ["-Os"]
for level in [0, 1, 2]: for level in [0, 1, 2]:
for flag in ("O", "g", "ggdb"): for flag in ("O", "g", "ggdb"):
@ -307,11 +307,10 @@ def ProcessDebug(env):
def ProcessTest(env): def ProcessTest(env):
env.Append( env.Append(CPPDEFINES=["UNIT_TEST", "UNITY_INCLUDE_CONFIG_H"],
CPPDEFINES=["UNIT_TEST", "UNITY_INCLUDE_CONFIG_H"], CPPPATH=[join("$BUILD_DIR", "UnityTestLib")])
CPPPATH=[join("$BUILD_DIR", "UnityTestLib")]) unitylib = env.BuildLibrary(join("$BUILD_DIR", "UnityTestLib"),
unitylib = env.BuildLibrary( get_core_package_dir("tool-unity"))
join("$BUILD_DIR", "UnityTestLib"), get_core_package_dir("tool-unity"))
env.Prepend(LIBS=[unitylib]) env.Prepend(LIBS=[unitylib])
src_filter = ["+<*.cpp>", "+<*.c>"] src_filter = ["+<*.cpp>", "+<*.c>"]

View File

@ -138,8 +138,8 @@ def PrintConfiguration(env):
ram = board_config.get("upload", {}).get("maximum_ram_size") ram = board_config.get("upload", {}).get("maximum_ram_size")
flash = board_config.get("upload", {}).get("maximum_size") flash = board_config.get("upload", {}).get("maximum_size")
hardware_data.append( hardware_data.append(
"%s RAM (%s Flash)" % (util.format_filesize(ram), "%s RAM (%s Flash)" %
util.format_filesize(flash))) (util.format_filesize(ram), util.format_filesize(flash)))
configuration_data.append( configuration_data.append(
"https://docs.platformio.org/page/boards/%s/%s.html" % "https://docs.platformio.org/page/boards/%s/%s.html" %
(platform.name, board_config.id)) (platform.name, board_config.id))
@ -153,8 +153,8 @@ def PrintConfiguration(env):
return return
data = [ data = [
"CURRENT(%s)" % board_config.get_debug_tool_name( "CURRENT(%s)" %
env.GetProjectOption("debug_tool")) board_config.get_debug_tool_name(env.GetProjectOption("debug_tool"))
] ]
onboard = [] onboard = []
external = [] external = []

View File

@ -198,10 +198,9 @@ def CheckUploadSize(_, target, source, env):
return return
def _configure_defaults(): def _configure_defaults():
env.Replace( env.Replace(SIZECHECKCMD="$SIZETOOL -B -d $SOURCES",
SIZECHECKCMD="$SIZETOOL -B -d $SOURCES", SIZEPROGREGEXP=r"^(\d+)\s+(\d+)\s+\d+\s",
SIZEPROGREGEXP=r"^(\d+)\s+(\d+)\s+\d+\s", SIZEDATAREGEXP=r"^\d+\s+(\d+)\s+(\d+)\s+\d+")
SIZEDATAREGEXP=r"^\d+\s+(\d+)\s+(\d+)\s+\d+")
def _get_size_output(): def _get_size_output():
cmd = env.get("SIZECHECKCMD") cmd = env.get("SIZECHECKCMD")
@ -251,8 +250,8 @@ def CheckUploadSize(_, target, source, env):
if data_max_size and data_size > -1: if data_max_size and data_size > -1:
print("DATA: %s" % _format_availale_bytes(data_size, data_max_size)) print("DATA: %s" % _format_availale_bytes(data_size, data_max_size))
if program_size > -1: if program_size > -1:
print("PROGRAM: %s" % _format_availale_bytes(program_size, print("PROGRAM: %s" %
program_max_size)) _format_availale_bytes(program_size, program_max_size))
if int(ARGUMENTS.get("PIOVERBOSE", 0)): if int(ARGUMENTS.get("PIOVERBOSE", 0)):
print(output) print(output)
@ -273,8 +272,8 @@ def PrintUploadInfo(env):
configured = env.subst("$UPLOAD_PROTOCOL") configured = env.subst("$UPLOAD_PROTOCOL")
available = [configured] if configured else [] available = [configured] if configured else []
if "BOARD" in env: if "BOARD" in env:
available.extend(env.BoardConfig().get("upload", {}).get( available.extend(env.BoardConfig().get("upload",
"protocols", [])) {}).get("protocols", []))
if available: if available:
print("AVAILABLE: %s" % ", ".join(sorted(set(available)))) print("AVAILABLE: %s" % ", ".join(sorted(set(available))))
if configured: if configured:

View File

@ -132,8 +132,8 @@ def BuildProgram(env):
env.Prepend(_LIBFLAGS="-Wl,--start-group ") env.Prepend(_LIBFLAGS="-Wl,--start-group ")
env.Append(_LIBFLAGS=" -Wl,--end-group") env.Append(_LIBFLAGS=" -Wl,--end-group")
program = env.Program( program = env.Program(join("$BUILD_DIR", env.subst("$PROGNAME")),
join("$BUILD_DIR", env.subst("$PROGNAME")), env['PIOBUILDFILES']) env['PIOBUILDFILES'])
env.Replace(PIOMAINPROG=program) env.Replace(PIOMAINPROG=program)
AlwaysBuild( AlwaysBuild(

View File

@ -51,24 +51,22 @@ def print_boards(boards):
BOARDLIST_TPL = ("{type:<30} {mcu:<14} {frequency:<8} " BOARDLIST_TPL = ("{type:<30} {mcu:<14} {frequency:<8} "
" {flash:<7} {ram:<6} {name}") " {flash:<7} {ram:<6} {name}")
click.echo( click.echo(
BOARDLIST_TPL.format( BOARDLIST_TPL.format(type=click.style("ID", fg="cyan"),
type=click.style("ID", fg="cyan"), mcu="MCU",
mcu="MCU", frequency="Frequency",
frequency="Frequency", flash="Flash",
flash="Flash", ram="RAM",
ram="RAM", name="Name"))
name="Name"))
click.echo("-" * terminal_width) click.echo("-" * terminal_width)
for board in boards: for board in boards:
click.echo( click.echo(
BOARDLIST_TPL.format( BOARDLIST_TPL.format(type=click.style(board['id'], fg="cyan"),
type=click.style(board['id'], fg="cyan"), mcu=board['mcu'],
mcu=board['mcu'], frequency="%dMHz" % (board['fcpu'] / 1000000),
frequency="%dMHz" % (board['fcpu'] / 1000000), flash=util.format_filesize(board['rom']),
flash=util.format_filesize(board['rom']), ram=util.format_filesize(board['ram']),
ram=util.format_filesize(board['ram']), name=board['name']))
name=board['name']))
def _get_boards(installed=False): def _get_boards(installed=False):

View File

@ -48,26 +48,31 @@ def validate_path(ctx, param, value): # pylint: disable=unused-argument
@click.command("ci", short_help="Continuous Integration") @click.command("ci", short_help="Continuous Integration")
@click.argument("src", nargs=-1, callback=validate_path) @click.argument("src", nargs=-1, callback=validate_path)
@click.option( @click.option("-l",
"-l", "--lib", multiple=True, callback=validate_path, metavar="DIRECTORY") "--lib",
multiple=True,
callback=validate_path,
metavar="DIRECTORY")
@click.option("--exclude", multiple=True) @click.option("--exclude", multiple=True)
@click.option( @click.option("-b",
"-b", "--board", multiple=True, metavar="ID", callback=validate_boards) "--board",
@click.option( multiple=True,
"--build-dir", metavar="ID",
default=mkdtemp, callback=validate_boards)
type=click.Path( @click.option("--build-dir",
file_okay=False, dir_okay=True, writable=True, resolve_path=True)) 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("--keep-build-dir", is_flag=True)
@click.option( @click.option("-c",
"-c", "--project-conf",
"--project-conf", type=click.Path(exists=True,
type=click.Path( file_okay=True,
exists=True, dir_okay=False,
file_okay=True, readable=True,
dir_okay=False, resolve_path=True))
readable=True,
resolve_path=True))
@click.option("-O", "--project-option", multiple=True) @click.option("-O", "--project-option", multiple=True)
@click.option("-v", "--verbose", is_flag=True) @click.option("-v", "--verbose", is_flag=True)
@click.pass_context @click.pass_context
@ -105,11 +110,10 @@ def cli( # pylint: disable=too-many-arguments, too-many-branches
_exclude_contents(build_dir, exclude) _exclude_contents(build_dir, exclude)
# initialise project # initialise project
ctx.invoke( ctx.invoke(cmd_init,
cmd_init, project_dir=build_dir,
project_dir=build_dir, board=board,
board=board, project_option=project_option)
project_option=project_option)
# process project # process project
ctx.invoke(cmd_run, project_dir=build_dir, verbose=verbose) ctx.invoke(cmd_run, project_dir=build_dir, verbose=verbose)

View File

@ -52,8 +52,8 @@ class GDBClient(BaseProcess): # pylint: disable=too-many-instance-attributes
if not isdir(get_project_cache_dir()): if not isdir(get_project_cache_dir()):
os.makedirs(get_project_cache_dir()) os.makedirs(get_project_cache_dir())
self._gdbsrc_dir = mkdtemp( self._gdbsrc_dir = mkdtemp(dir=get_project_cache_dir(),
dir=get_project_cache_dir(), prefix=".piodebug-") prefix=".piodebug-")
self._target_is_run = False self._target_is_run = False
self._last_server_activity = 0 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.extend(["--data-directory", gdb_data_dir])
args.append(patterns['PROG_PATH']) args.append(patterns['PROG_PATH'])
return reactor.spawnProcess( return reactor.spawnProcess(self,
self, gdb_path, args, path=self.project_dir, env=os.environ) gdb_path,
args,
path=self.project_dir,
env=os.environ)
@staticmethod @staticmethod
def _get_data_dir(gdb_path): 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 return gdb_data_dir if isdir(gdb_data_dir) else None
def generate_pioinit(self, dst_dir, patterns): def generate_pioinit(self, dst_dir, patterns):
server_exe = (self.debug_options.get("server") or {}).get( server_exe = (self.debug_options.get("server")
"executable", "").lower() or {}).get("executable", "").lower()
if "jlink" in server_exe: if "jlink" in server_exe:
cfg = initcfgs.GDB_JLINK_INIT_CONFIG cfg = initcfgs.GDB_JLINK_INIT_CONFIG
elif "st-util" in server_exe: elif "st-util" in server_exe:

View File

@ -27,29 +27,24 @@ from platformio.project.config import ProjectConfig
from platformio.project.helpers import is_platformio_project from platformio.project.helpers import is_platformio_project
@click.command( @click.command("debug",
"debug", context_settings=dict(ignore_unknown_options=True),
context_settings=dict(ignore_unknown_options=True), short_help="PIO Unified Debugger")
short_help="PIO Unified Debugger") @click.option("-d",
@click.option( "--project-dir",
"-d", default=os.getcwd,
"--project-dir", type=click.Path(exists=True,
default=os.getcwd, file_okay=False,
type=click.Path( dir_okay=True,
exists=True, writable=True,
file_okay=False, resolve_path=True))
dir_okay=True, @click.option("-c",
writable=True, "--project-conf",
resolve_path=True)) type=click.Path(exists=True,
@click.option( file_okay=True,
"-c", dir_okay=False,
"--project-conf", readable=True,
type=click.Path( resolve_path=True))
exists=True,
file_okay=True,
dir_okay=False,
readable=True,
resolve_path=True))
@click.option("--environment", "-e", metavar="<environment>") @click.option("--environment", "-e", metavar="<environment>")
@click.option("--verbose", "-v", is_flag=True) @click.option("--verbose", "-v", is_flag=True)
@click.option("--interface", type=click.Choice(["gdb"])) @click.option("--interface", type=click.Choice(["gdb"]))

View File

@ -63,16 +63,15 @@ def validate_debug_options(cmd_ctx, env_options):
try: try:
platform = PlatformFactory.newPlatform(env_options['platform']) platform = PlatformFactory.newPlatform(env_options['platform'])
except exception.UnknownPlatform: except exception.UnknownPlatform:
cmd_ctx.invoke( cmd_ctx.invoke(cmd_platform_install,
cmd_platform_install, platforms=[env_options['platform']],
platforms=[env_options['platform']], skip_default_package=True)
skip_default_package=True)
platform = PlatformFactory.newPlatform(env_options['platform']) platform = PlatformFactory.newPlatform(env_options['platform'])
board_config = platform.board_config(env_options['board']) board_config = platform.board_config(env_options['board'])
tool_name = board_config.get_debug_tool_name(env_options.get("debug_tool")) tool_name = board_config.get_debug_tool_name(env_options.get("debug_tool"))
tool_settings = board_config.get("debug", {}).get("tools", {}).get( tool_settings = board_config.get("debug", {}).get("tools",
tool_name, {}) {}).get(tool_name, {})
server_options = None server_options = None
# specific server per a system # 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_dir = platform.get_package_dir(
server_package) if server_package else None server_package) if server_package else None
if server_package and not server_package_dir: if server_package and not server_package_dir:
platform.install_packages( platform.install_packages(with_packages=[server_package],
with_packages=[server_package], skip_default_package=True,
skip_default_package=True, silent=True)
silent=True)
server_package_dir = platform.get_package_dir(server_package) server_package_dir = platform.get_package_dir(server_package)
server_options = dict( server_options = dict(
cwd=server_package_dir if server_package else None, 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): def predebug_project(ctx, project_dir, env_name, preload, verbose):
ctx.invoke( ctx.invoke(cmd_run,
cmd_run, project_dir=project_dir,
project_dir=project_dir, environment=[env_name],
environment=[env_name], target=["__debug"] + (["upload"] if preload else []),
target=["__debug"] + (["upload"] if preload else []), verbose=verbose)
verbose=verbose)
if preload: if preload:
time.sleep(5) time.sleep(5)
@ -167,11 +164,10 @@ def capture_std_streams(stdout, stderr=None):
def load_configuration(ctx, project_dir, env_name): def load_configuration(ctx, project_dir, env_name):
output = BytesIO() output = BytesIO()
with capture_std_streams(output): with capture_std_streams(output):
ctx.invoke( ctx.invoke(cmd_run,
cmd_run, project_dir=project_dir,
project_dir=project_dir, environment=[env_name],
environment=[env_name], target=["idedata"])
target=["idedata"])
result = output.getvalue().decode() result = output.getvalue().decode()
output.close() output.close()
if '"includes":' not in result: if '"includes":' not in result:

View File

@ -101,63 +101,57 @@ def device_list( # pylint: disable=too-many-branches
@cli.command("monitor", short_help="Monitor device (Serial)") @cli.command("monitor", short_help="Monitor device (Serial)")
@click.option("--port", "-p", help="Port, a number or a device name") @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("--baud", "-b", type=int, help="Set baud rate, default=9600")
@click.option( @click.option("--parity",
"--parity", default="N",
default="N", type=click.Choice(["N", "E", "O", "S", "M"]),
type=click.Choice(["N", "E", "O", "S", "M"]), help="Set parity, default=N")
help="Set parity, default=N") @click.option("--rtscts",
@click.option( is_flag=True,
"--rtscts", is_flag=True, help="Enable RTS/CTS flow control, default=Off") help="Enable RTS/CTS flow control, default=Off")
@click.option( @click.option("--xonxoff",
"--xonxoff", is_flag=True,
is_flag=True, help="Enable software flow control, default=Off")
help="Enable software flow control, default=Off") @click.option("--rts",
@click.option( default=None,
"--rts", type=click.IntRange(0, 1),
default=None, help="Set initial RTS line state")
type=click.IntRange(0, 1), @click.option("--dtr",
help="Set initial RTS line state") default=None,
@click.option( type=click.IntRange(0, 1),
"--dtr", help="Set initial DTR line state")
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("--echo", is_flag=True, help="Enable local echo, default=Off")
@click.option( @click.option("--encoding",
"--encoding", default="UTF-8",
default="UTF-8", help="Set the encoding for the serial port (e.g. hexlify, "
help="Set the encoding for the serial port (e.g. hexlify, " "Latin1, UTF-8), default: UTF-8")
"Latin1, UTF-8), default: UTF-8")
@click.option("--filter", "-f", multiple=True, help="Add text transformation") @click.option("--filter", "-f", multiple=True, help="Add text transformation")
@click.option( @click.option("--eol",
"--eol", default="CRLF",
default="CRLF", type=click.Choice(["CR", "LF", "CRLF"]),
type=click.Choice(["CR", "LF", "CRLF"]), help="End of line mode, default=CRLF")
help="End of line mode, default=CRLF") @click.option("--raw",
@click.option( is_flag=True,
"--raw", is_flag=True, help="Do not apply any encodings/transformations") help="Do not apply any encodings/transformations")
@click.option( @click.option("--exit-char",
"--exit-char", type=int,
type=int, default=3,
default=3, help="ASCII code of special character that is used to exit "
help="ASCII code of special character that is used to exit " "the application, default=3 (Ctrl+C)")
"the application, default=3 (Ctrl+C)") @click.option("--menu-char",
@click.option( type=int,
"--menu-char", default=20,
type=int, help="ASCII code of special character that is used to "
default=20, "control miniterm (menu), default=20 (DEC)")
help="ASCII code of special character that is used to " @click.option("--quiet",
"control miniterm (menu), default=20 (DEC)") is_flag=True,
@click.option( help="Diagnostics: suppress non-error messages, default=Off")
"--quiet", @click.option("-d",
is_flag=True, "--project-dir",
help="Diagnostics: suppress non-error messages, default=Off") default=getcwd,
@click.option( type=click.Path(exists=True,
"-d", file_okay=False,
"--project-dir", dir_okay=True,
default=getcwd, resolve_path=True))
type=click.Path(
exists=True, file_okay=False, dir_okay=True, resolve_path=True))
@click.option( @click.option(
"-e", "-e",
"--environment", "--environment",
@ -206,11 +200,10 @@ def device_monitor(**kwargs): # pylint: disable=too-many-branches
break break
try: try:
miniterm.main( miniterm.main(default_port=kwargs['port'],
default_port=kwargs['port'], default_baudrate=kwargs['baud'] or 9600,
default_baudrate=kwargs['baud'] or 9600, default_rts=kwargs['rts'],
default_rts=kwargs['rts'], default_dtr=kwargs['dtr'])
default_dtr=kwargs['dtr'])
except Exception as e: except Exception as e:
raise exception.MinitermException(e) raise exception.MinitermException(e)

View File

@ -60,8 +60,9 @@ def is_twitter_blocked():
timeout = 2 timeout = 2
try: try:
if os.getenv("HTTP_PROXY", os.getenv("HTTPS_PROXY")): if os.getenv("HTTP_PROXY", os.getenv("HTTPS_PROXY")):
requests.get( requests.get("http://%s" % ip,
"http://%s" % ip, allow_redirects=False, timeout=timeout) allow_redirects=False,
timeout=timeout)
else: else:
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((ip, 80)) socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((ip, 80))
return False return False

View File

@ -67,11 +67,11 @@ class MiscRPC(object):
html_or_json = json.loads(html_or_json) html_or_json = json.loads(html_or_json)
assert "items_html" in html_or_json assert "items_html" in html_or_json
soup = BeautifulSoup(html_or_json['items_html'], "html.parser") soup = BeautifulSoup(html_or_json['items_html'], "html.parser")
tweet_nodes = soup.find_all( tweet_nodes = soup.find_all("div",
"div", attrs={ attrs={
"class": "tweet", "class": "tweet",
"data-tweet-id": True "data-tweet-id": True
}) })
result = yield defer.DeferredList( result = yield defer.DeferredList(
[self._parse_tweet_node(node, username) for node in tweet_nodes], [self._parse_tweet_node(node, username) for node in tweet_nodes],
consumeErrors=True) consumeErrors=True)
@ -97,13 +97,14 @@ class MiscRPC(object):
node.get("data-expanded-url") node.get("data-expanded-url")
for node in (quote_text_node or text_node).find_all( for node in (quote_text_node or text_node).find_all(
class_="twitter-timeline-link", class_="twitter-timeline-link",
attrs={"data-expanded-url": True}) attrs={"data-expanded-url": True}
] )
] # yapf: disable
# fetch data from iframe card # fetch data from iframe card
if (not photos or not urls) and tweet.get("data-card2-type"): if (not photos or not urls) and tweet.get("data-card2-type"):
iframe_node = tweet.find( iframe_node = tweet.find("div",
"div", attrs={"data-full-card-iframe-url": True}) attrs={"data-full-card-iframe-url": True})
if iframe_node: if iframe_node:
iframe_card = yield self._fetch_iframe_card( iframe_card = yield self._fetch_iframe_card(
twitter_url + iframe_node.get("data-full-card-iframe-url"), 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") url_node = soup.find("a", class_="TwitterCard-container")
text_node = soup.find("div", class_="SummaryCard-content") text_node = soup.find("div", class_="SummaryCard-content")
if text_node: if text_node:
text_node.find( text_node.find("span",
"span", class_="SummaryCard-destination").decompose() class_="SummaryCard-destination").decompose()
defer.returnValue({ defer.returnValue({
"photo": "photo":
photo_node.get("data-src") if photo_node else None, photo_node.get("data-src") if photo_node else None,

View File

@ -54,8 +54,10 @@ class OSRPC(object):
session = helpers.requests_session() session = helpers.requests_session()
if data: if data:
r = yield session.post( r = yield session.post(uri,
uri, data=data, headers=headers, timeout=timeout) data=data,
headers=headers,
timeout=timeout)
else: else:
r = yield session.get(uri, headers=headers, timeout=timeout) r = yield session.get(uri, headers=headers, timeout=timeout)

View File

@ -29,8 +29,9 @@ from platformio.compat import get_filesystem_encoding
from platformio.ide.projectgenerator import ProjectGenerator from platformio.ide.projectgenerator import ProjectGenerator
from platformio.managers.platform import PlatformManager from platformio.managers.platform import PlatformManager
from platformio.project.config import ProjectConfig from platformio.project.config import ProjectConfig
from platformio.project.helpers import ( from platformio.project.helpers import (get_project_libdeps_dir,
get_project_libdeps_dir, get_project_src_dir, is_platformio_project) get_project_src_dir,
is_platformio_project)
class ProjectRPC(object): class ProjectRPC(object):

View File

@ -48,8 +48,8 @@ class JSONRPCServerProtocol(WebSocketServerProtocol):
if isinstance(failure.value, JSONRPCDispatchException): if isinstance(failure.value, JSONRPCDispatchException):
e = failure.value e = failure.value
else: else:
e = JSONRPCDispatchException( e = JSONRPCDispatchException(code=4999,
code=4999, message=failure.getErrorMessage()) message=failure.getErrorMessage())
del response["result"] del response["result"]
response['error'] = e.error._data # pylint: disable=protected-access response['error'] = e.error._data # pylint: disable=protected-access
print(response['error']) print(response['error'])

View File

@ -25,9 +25,11 @@ from platformio.commands.platform import \
from platformio.ide.projectgenerator import ProjectGenerator from platformio.ide.projectgenerator import ProjectGenerator
from platformio.managers.platform import PlatformManager from platformio.managers.platform import PlatformManager
from platformio.project.config import ProjectConfig from platformio.project.config import ProjectConfig
from platformio.project.helpers import ( from platformio.project.helpers import (get_project_include_dir,
get_project_include_dir, get_project_lib_dir, get_project_src_dir, get_project_lib_dir,
get_project_test_dir, is_platformio_project) get_project_src_dir,
get_project_test_dir,
is_platformio_project)
def validate_boards(ctx, param, value): # pylint: disable=W0613 def validate_boards(ctx, param, value): # pylint: disable=W0613
@ -42,22 +44,23 @@ def validate_boards(ctx, param, value): # pylint: disable=W0613
return value return value
@click.command( @click.command("init",
"init", short_help="Initialize PlatformIO project or update existing") short_help="Initialize PlatformIO project or update existing")
@click.option( @click.option("--project-dir",
"--project-dir", "-d",
"-d", default=getcwd,
default=getcwd, type=click.Path(exists=True,
type=click.Path( file_okay=False,
exists=True, dir_okay=True,
file_okay=False, writable=True,
dir_okay=True, resolve_path=True))
writable=True, @click.option("-b",
resolve_path=True)) "--board",
@click.option( multiple=True,
"-b", "--board", multiple=True, metavar="ID", callback=validate_boards) metavar="ID",
@click.option( callback=validate_boards)
"--ide", type=click.Choice(ProjectGenerator.get_supported_ides())) @click.option("--ide",
type=click.Choice(ProjectGenerator.get_supported_ides()))
@click.option("-O", "--project-option", multiple=True) @click.option("-O", "--project-option", multiple=True)
@click.option("--env-prefix", default="") @click.option("--env-prefix", default="")
@click.option("-s", "--silent", is_flag=True) @click.option("-s", "--silent", is_flag=True)
@ -72,22 +75,23 @@ def cli(
silent): silent):
if not silent: if not silent:
if project_dir == getcwd(): if project_dir == getcwd():
click.secho( click.secho("\nThe current working directory",
"\nThe current working directory", fg="yellow", nl=False) fg="yellow",
nl=False)
click.secho(" %s " % project_dir, fg="cyan", nl=False) click.secho(" %s " % project_dir, fg="cyan", nl=False)
click.secho("will be used for the project.", fg="yellow") click.secho("will be used for the project.", fg="yellow")
click.echo("") click.echo("")
click.echo("The next files/directories have been created in %s" % click.echo("The next files/directories have been created in %s" %
click.style(project_dir, fg="cyan")) click.style(project_dir, fg="cyan"))
click.echo("%s - Put project header files here" % click.style( click.echo("%s - Put project header files here" %
"include", fg="cyan")) click.style("include", fg="cyan"))
click.echo("%s - Put here project specific (private) libraries" % click.echo("%s - Put here project specific (private) libraries" %
click.style("lib", fg="cyan")) click.style("lib", fg="cyan"))
click.echo("%s - Put project source files here" % click.style( click.echo("%s - Put project source files here" %
"src", fg="cyan")) click.style("src", fg="cyan"))
click.echo("%s - Project Configuration File" % click.style( click.echo("%s - Project Configuration File" %
"platformio.ini", fg="cyan")) click.style("platformio.ini", fg="cyan"))
is_new_project = not is_platformio_project(project_dir) is_new_project = not is_platformio_project(project_dir)
if is_new_project: if is_new_project:
@ -112,8 +116,8 @@ def cli(
if ide: if ide:
click.secho( click.secho(
"\nProject has been successfully %s including configuration files " "\nProject has been successfully %s including configuration files "
"for `%s` IDE." % ("initialized" if is_new_project else "updated", "for `%s` IDE." %
ide), ("initialized" if is_new_project else "updated", ide),
fg="green") fg="green")
else: else:
click.secho( 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, def fill_project_envs(ctx, project_dir, board_ids, project_option, env_prefix,
force_download): force_download):
config = ProjectConfig( config = ProjectConfig(join(project_dir, "platformio.ini"),
join(project_dir, "platformio.ini"), parse_extra=False) parse_extra=False)
used_boards = [] used_boards = []
for section in config.sections(): for section in config.sections():
cond = [ cond = [
@ -417,6 +421,5 @@ def _install_dependent_platforms(ctx, platforms):
] ]
if set(platforms) <= set(installed_platforms): if set(platforms) <= set(installed_platforms):
return return
ctx.invoke( ctx.invoke(cli_platform_install,
cli_platform_install, platforms=list(set(platforms) - set(installed_platforms)))
platforms=list(set(platforms) - set(installed_platforms)))

View File

@ -26,9 +26,10 @@ from platformio.managers.lib import (LibraryManager, get_builtin_libs,
is_builtin_lib) is_builtin_lib)
from platformio.proc import is_ci from platformio.proc import is_ci
from platformio.project.config import ProjectConfig from platformio.project.config import ProjectConfig
from platformio.project.helpers import ( from platformio.project.helpers import (get_project_dir,
get_project_dir, get_project_global_lib_dir, get_project_libdeps_dir, get_project_global_lib_dir,
is_platformio_project) get_project_libdeps_dir,
is_platformio_project)
try: try:
from urllib.parse import quote 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.group(short_help="Library Manager")
@click.option( @click.option("-d",
"-d", "--storage-dir",
"--storage-dir", multiple=True,
multiple=True, default=None,
default=None, type=click.Path(exists=True,
type=click.Path( file_okay=False,
exists=True, dir_okay=True,
file_okay=False, writable=True,
dir_okay=True, resolve_path=True),
writable=True, help="Manage custom library storage")
resolve_path=True), @click.option("-g",
help="Manage custom library storage") "--global",
@click.option( is_flag=True,
"-g", help="Manage global PlatformIO library storage")
"--global",
is_flag=True,
help="Manage global PlatformIO library storage")
@click.option( @click.option(
"-e", "-e",
"--environment", "--environment",
@ -101,8 +99,8 @@ def cli(ctx, **options):
continue continue
with util.cd(storage_dir): with util.cd(storage_dir):
libdeps_dir = get_project_libdeps_dir() libdeps_dir = get_project_libdeps_dir()
config = ProjectConfig.get_instance( config = ProjectConfig.get_instance(join(storage_dir,
join(storage_dir, "platformio.ini")) "platformio.ini"))
config.validate(options['environment']) config.validate(options['environment'])
for env in config.envs(): for env in config.envs():
if options['environment'] and env not in options['environment']: if options['environment'] and env not in options['environment']:
@ -119,17 +117,17 @@ def cli(ctx, **options):
"--save", "--save",
is_flag=True, is_flag=True,
help="Save installed libraries into the `platformio.ini` dependency list") help="Save installed libraries into the `platformio.ini` dependency list")
@click.option( @click.option("-s",
"-s", "--silent", is_flag=True, help="Suppress progress reporting") "--silent",
@click.option( is_flag=True,
"--interactive", help="Suppress progress reporting")
is_flag=True, @click.option("--interactive",
help="Allow to make a choice for all prompts") is_flag=True,
@click.option( help="Allow to make a choice for all prompts")
"-f", @click.option("-f",
"--force", "--force",
is_flag=True, is_flag=True,
help="Reinstall/redownload library if exists") help="Reinstall/redownload library if exists")
@click.pass_context @click.pass_context
def lib_install( # pylint: disable=too-many-arguments def lib_install( # pylint: disable=too-many-arguments
ctx, libraries, save, silent, interactive, force): ctx, libraries, save, silent, interactive, force):
@ -143,20 +141,18 @@ def lib_install( # pylint: disable=too-many-arguments
lm = LibraryManager(storage_dir) lm = LibraryManager(storage_dir)
if libraries: if libraries:
for library in libraries: for library in libraries:
pkg_dir = lm.install( pkg_dir = lm.install(library,
library, silent=silent,
silent=silent, interactive=interactive,
interactive=interactive, force=force)
force=force)
installed_manifests[library] = lm.load_manifest(pkg_dir) installed_manifests[library] = lm.load_manifest(pkg_dir)
elif storage_dir in storage_libdeps: elif storage_dir in storage_libdeps:
for library in storage_libdeps[storage_dir]: for library in storage_libdeps[storage_dir]:
try: try:
pkg_dir = lm.install( pkg_dir = lm.install(library,
library, silent=silent,
silent=silent, interactive=interactive,
interactive=interactive, force=force)
force=force)
installed_manifests[library] = lm.load_manifest(pkg_dir) installed_manifests[library] = lm.load_manifest(pkg_dir)
except exception.LibNotFound as e: except exception.LibNotFound as e:
if not silent or not is_builtin_lib(library): 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") @cli.command("update", short_help="Update installed libraries")
@click.argument("libraries", required=False, nargs=-1, metavar="[LIBRARY...]") @click.argument("libraries", required=False, nargs=-1, metavar="[LIBRARY...]")
@click.option( @click.option("-c",
"-c", "--only-check",
"--only-check", is_flag=True,
is_flag=True, help="DEPRECATED. Please use `--dry-run` instead")
help="DEPRECATED. Please use `--dry-run` instead") @click.option("--dry-run",
@click.option( is_flag=True,
"--dry-run", help="Do not update, only check for the new versions")
is_flag=True,
help="Do not update, only check for the new versions")
@click.option("--json-output", is_flag=True) @click.option("--json-output", is_flag=True)
@click.pass_context @click.pass_context
def lib_update(ctx, libraries, only_check, dry_run, json_output): 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("-f", "--framework", multiple=True)
@click.option("-p", "--platform", multiple=True) @click.option("-p", "--platform", multiple=True)
@click.option("-i", "--header", multiple=True) @click.option("-i", "--header", multiple=True)
@click.option( @click.option("--noninteractive",
"--noninteractive", is_flag=True,
is_flag=True, help="Do not prompt, automatically paginate with delay")
help="Do not prompt, automatically paginate with delay")
def lib_search(query, json_output, page, noninteractive, **filters): def lib_search(query, json_output, page, noninteractive, **filters):
if not query: if not query:
query = [] query = []
@ -311,10 +304,9 @@ def lib_search(query, json_output, page, noninteractive, **filters):
for value in values: for value in values:
query.append('%s:"%s"' % (key, value)) query.append('%s:"%s"' % (key, value))
result = util.get_api_result( result = util.get_api_result("/v2/lib/search",
"/v2/lib/search", dict(query=" ".join(query), page=page),
dict(query=" ".join(query), page=page), cache_valid="1d")
cache_valid="1d")
if json_output: if json_output:
click.echo(json.dumps(result)) click.echo(json.dumps(result))
@ -336,9 +328,8 @@ def lib_search(query, json_output, page, noninteractive, **filters):
fg="cyan") fg="cyan")
return return
click.secho( click.secho("Found %d libraries:\n" % result['total'],
"Found %d libraries:\n" % result['total'], fg="green" if result['total'] else "yellow")
fg="green" if result['total'] else "yellow")
while True: while True:
for item in result['items']: for item in result['items']:
@ -350,20 +341,18 @@ def lib_search(query, json_output, page, noninteractive, **filters):
if noninteractive: if noninteractive:
click.echo() click.echo()
click.secho( click.secho("Loading next %d libraries... Press Ctrl+C to stop!" %
"Loading next %d libraries... Press Ctrl+C to stop!" % result['perpage'],
result['perpage'], fg="yellow")
fg="yellow")
click.echo() click.echo()
time.sleep(5) time.sleep(5)
elif not click.confirm("Show next libraries?"): elif not click.confirm("Show next libraries?"):
break break
result = util.get_api_result( result = util.get_api_result("/v2/lib/search", {
"/v2/lib/search", { "query": " ".join(query),
"query": " ".join(query), "page": int(result['page']) + 1
"page": int(result['page']) + 1 },
}, cache_valid="1d")
cache_valid="1d")
@cli.command("builtin", short_help="List built-in libraries") @cli.command("builtin", short_help="List built-in libraries")
@ -475,13 +464,12 @@ def lib_register(config_url):
and not config_url.startswith("https://")): and not config_url.startswith("https://")):
raise exception.InvalidLibConfURL(config_url) raise exception.InvalidLibConfURL(config_url)
result = util.get_api_result( result = util.get_api_result("/lib/register",
"/lib/register", data=dict(config_url=config_url)) data=dict(config_url=config_url))
if "message" in result and result['message']: if "message" in result and result['message']:
click.secho( click.secho(result['message'],
result['message'], fg="green" if "successed" in result and result['successed']
fg="green" else "red")
if "successed" in result and result['successed'] else "red")
@cli.command("stats", short_help="Library Registry Statistics") @cli.command("stats", short_help="Library Registry Statistics")
@ -512,10 +500,9 @@ def lib_stats(json_output):
date = str( date = str(
time.strftime("%c", util.parse_date(item['date'])) if "date" in time.strftime("%c", util.parse_date(item['date'])) if "date" in
item else "") item else "")
url = click.style( url = click.style("https://platformio.org/lib/show/%s/%s" %
"https://platformio.org/lib/show/%s/%s" % (item['id'], (item['id'], quote(item['name'])),
quote(item['name'])), fg="blue")
fg="blue")
click.echo( click.echo(
(printitemdate_tpl if "date" in item else printitem_tpl).format( (printitemdate_tpl if "date" in item else printitem_tpl).format(
name=click.style(item['name'], fg="cyan"), date=date, url=url)) name=click.style(item['name'], fg="cyan"), date=date, url=url))
@ -524,10 +511,9 @@ def lib_stats(json_output):
click.echo( click.echo(
printitem_tpl.format( printitem_tpl.format(
name=click.style(name, fg="cyan"), name=click.style(name, fg="cyan"),
url=click.style( url=click.style("https://platformio.org/lib/search?query=" +
"https://platformio.org/lib/search?query=" + quote( quote("keyword:%s" % name),
"keyword:%s" % name), fg="blue")))
fg="blue")))
for key in ("updated", "added"): for key in ("updated", "added"):
_print_title("Recently " + key) _print_title("Recently " + key)

View File

@ -29,9 +29,9 @@ def cli():
def _print_platforms(platforms): def _print_platforms(platforms):
for platform in platforms: for platform in platforms:
click.echo("{name} ~ {title}".format( click.echo("{name} ~ {title}".format(name=click.style(platform['name'],
name=click.style(platform['name'], fg="cyan"), fg="cyan"),
title=platform['title'])) title=platform['title']))
click.echo("=" * (3 + len(platform['name'] + platform['title']))) click.echo("=" * (3 + len(platform['name'] + platform['title'])))
click.echo(platform['description']) click.echo(platform['description'])
click.echo() click.echo()
@ -65,19 +65,18 @@ def _get_installed_platform_data(platform,
with_boards=True, with_boards=True,
expose_packages=True): expose_packages=True):
p = PlatformFactory.newPlatform(platform) p = PlatformFactory.newPlatform(platform)
data = dict( data = dict(name=p.name,
name=p.name, title=p.title,
title=p.title, description=p.description,
description=p.description, version=p.version,
version=p.version, homepage=p.homepage,
homepage=p.homepage, repository=p.repository_url,
repository=p.repository_url, url=p.vendor_url,
url=p.vendor_url, docs=p.docs_url,
docs=p.docs_url, license=p.license,
license=p.license, forDesktop=not p.is_embedded(),
forDesktop=not p.is_embedded(), frameworks=sorted(list(p.frameworks) if p.frameworks else []),
frameworks=sorted(list(p.frameworks) if p.frameworks else []), packages=list(p.packages) if p.packages else [])
packages=list(p.packages) if p.packages else [])
# if dump to API # if dump to API
# del data['version'] # del data['version']
@ -99,11 +98,10 @@ def _get_installed_platform_data(platform,
data['packages'] = [] data['packages'] = []
installed_pkgs = p.get_installed_packages() installed_pkgs = p.get_installed_packages()
for name, opts in p.packages.items(): for name, opts in p.packages.items():
item = dict( item = dict(name=name,
name=name, type=p.get_package_type(name),
type=p.get_package_type(name), requirements=opts.get("version"),
requirements=opts.get("version"), optional=opts.get("optional") is True)
optional=opts.get("optional") is True)
if name in installed_pkgs: if name in installed_pkgs:
for key, value in installed_pkgs[name].items(): for key, value in installed_pkgs[name].items():
if key not in ("url", "version", "description"): if key not in ("url", "version", "description"):
@ -129,18 +127,17 @@ def _get_registry_platform_data( # pylint: disable=unused-argument
if not _data: if not _data:
return None return None
data = dict( data = dict(name=_data['name'],
name=_data['name'], title=_data['title'],
title=_data['title'], description=_data['description'],
description=_data['description'], homepage=_data['homepage'],
homepage=_data['homepage'], repository=_data['repository'],
repository=_data['repository'], url=_data['url'],
url=_data['url'], license=_data['license'],
license=_data['license'], forDesktop=_data['forDesktop'],
forDesktop=_data['forDesktop'], frameworks=_data['frameworks'],
frameworks=_data['frameworks'], packages=_data['packages'],
packages=_data['packages'], versions=_data['versions'])
versions=_data['versions'])
if with_boards: if with_boards:
data['boards'] = [ data['boards'] = [
@ -163,8 +160,9 @@ def platform_search(query, json_output):
if query and query.lower() not in search_data.lower(): if query and query.lower() not in search_data.lower():
continue continue
platforms.append( platforms.append(
_get_registry_platform_data( _get_registry_platform_data(platform['name'],
platform['name'], with_boards=False, expose_packages=False)) with_boards=False,
expose_packages=False))
if json_output: if json_output:
click.echo(json.dumps(platforms)) click.echo(json.dumps(platforms))
@ -183,8 +181,8 @@ def platform_frameworks(query, json_output):
search_data = json.dumps(framework) search_data = json.dumps(framework)
if query and query.lower() not in search_data.lower(): if query and query.lower() not in search_data.lower():
continue continue
framework['homepage'] = ( framework['homepage'] = ("https://platformio.org/frameworks/" +
"https://platformio.org/frameworks/" + framework['name']) framework['name'])
framework['platforms'] = [ framework['platforms'] = [
platform['name'] for platform in _get_registry_platforms() platform['name'] for platform in _get_registry_platforms()
if framework['name'] in platform['frameworks'] if framework['name'] in platform['frameworks']
@ -205,10 +203,9 @@ def platform_list(json_output):
pm = PlatformManager() pm = PlatformManager()
for manifest in pm.get_installed(): for manifest in pm.get_installed():
platforms.append( platforms.append(
_get_installed_platform_data( _get_installed_platform_data(manifest['__pkg_dir'],
manifest['__pkg_dir'], with_boards=False,
with_boards=False, expose_packages=False))
expose_packages=False))
platforms = sorted(platforms, key=lambda manifest: manifest['name']) platforms = sorted(platforms, key=lambda manifest: manifest['name'])
if json_output: if json_output:
@ -227,8 +224,9 @@ def platform_show(platform, json_output): # pylint: disable=too-many-branches
if json_output: if json_output:
return click.echo(json.dumps(data)) return click.echo(json.dumps(data))
click.echo("{name} ~ {title}".format( click.echo("{name} ~ {title}".format(name=click.style(data['name'],
name=click.style(data['name'], fg="cyan"), title=data['title'])) fg="cyan"),
title=data['title']))
click.echo("=" * (3 + len(data['name'] + data['title']))) click.echo("=" * (3 + len(data['name'] + data['title'])))
click.echo(data['description']) click.echo(data['description'])
click.echo() click.echo()
@ -293,17 +291,15 @@ def platform_install(platforms, with_package, without_package,
skip_default_package, force): skip_default_package, force):
pm = PlatformManager() pm = PlatformManager()
for platform in platforms: for platform in platforms:
if pm.install( if pm.install(name=platform,
name=platform, with_packages=with_package,
with_packages=with_package, without_packages=without_package,
without_packages=without_package, skip_default_package=skip_default_package,
skip_default_package=skip_default_package, force=force):
force=force): click.secho("The platform '%s' has been successfully installed!\n"
click.secho( "The rest of packages will be installed automatically "
"The platform '%s' has been successfully installed!\n" "depending on your build environment." % platform,
"The rest of packages will be installed automatically " fg="green")
"depending on your build environment." % platform,
fg="green")
@cli.command("uninstall", short_help="Uninstall development platform") @cli.command("uninstall", short_help="Uninstall development platform")
@ -312,28 +308,24 @@ def platform_uninstall(platforms):
pm = PlatformManager() pm = PlatformManager()
for platform in platforms: for platform in platforms:
if pm.uninstall(platform): if pm.uninstall(platform):
click.secho( click.secho("The platform '%s' has been successfully "
"The platform '%s' has been successfully " "uninstalled!" % platform,
"uninstalled!" % platform, fg="green")
fg="green")
@cli.command("update", short_help="Update installed development platforms") @cli.command("update", short_help="Update installed development platforms")
@click.argument("platforms", nargs=-1, required=False, metavar="[PLATFORM...]") @click.argument("platforms", nargs=-1, required=False, metavar="[PLATFORM...]")
@click.option( @click.option("-p",
"-p", "--only-packages",
"--only-packages", is_flag=True,
is_flag=True, help="Update only the platform packages")
help="Update only the platform packages") @click.option("-c",
@click.option( "--only-check",
"-c", is_flag=True,
"--only-check", help="DEPRECATED. Please use `--dry-run` instead")
is_flag=True, @click.option("--dry-run",
help="DEPRECATED. Please use `--dry-run` instead") is_flag=True,
@click.option( help="Do not update, only check for the new versions")
"--dry-run",
is_flag=True,
help="Do not update, only check for the new versions")
@click.option("--json-output", is_flag=True) @click.option("--json-output", is_flag=True)
def platform_update( # pylint: disable=too-many-locals def platform_update( # pylint: disable=too-many-locals
platforms, only_packages, only_check, dry_run, json_output): 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( if (not latest and not PlatformFactory.newPlatform(
pkg_dir).are_outdated_packages()): pkg_dir).are_outdated_packages()):
continue continue
data = _get_installed_platform_data( data = _get_installed_platform_data(pkg_dir,
pkg_dir, with_boards=False, expose_packages=False) with_boards=False,
expose_packages=False)
if latest: if latest:
data['versionLatest'] = latest data['versionLatest'] = latest
result.append(data) result.append(data)
@ -373,8 +366,9 @@ def platform_update( # pylint: disable=too-many-locals
# cleanup cached board and platform lists # cleanup cached board and platform lists
app.clean_cache() app.clean_cache()
for platform in platforms: for platform in platforms:
click.echo("Platform %s" % click.style( click.echo(
pkg_dir_to_name.get(platform, platform), fg="cyan")) "Platform %s" %
click.style(pkg_dir_to_name.get(platform, platform), fg="cyan"))
click.echo("--------") click.echo("--------")
pm.update(platform, only_packages=only_packages, only_check=only_check) pm.update(platform, only_packages=only_packages, only_check=only_check)
click.echo() click.echo()

View File

@ -43,12 +43,13 @@ def remote_agent():
@remote_agent.command("start", short_help="Start agent") @remote_agent.command("start", short_help="Start agent")
@click.option("-n", "--name") @click.option("-n", "--name")
@click.option("-s", "--share", multiple=True, metavar="E-MAIL") @click.option("-s", "--share", multiple=True, metavar="E-MAIL")
@click.option( @click.option("-d",
"-d", "--working-dir",
"--working-dir", envvar="PLATFORMIO_REMOTE_AGENT_DIR",
envvar="PLATFORMIO_REMOTE_AGENT_DIR", type=click.Path(file_okay=False,
type=click.Path( dir_okay=True,
file_okay=False, dir_okay=True, writable=True, resolve_path=True)) writable=True,
resolve_path=True))
def remote_agent_start(**kwargs): def remote_agent_start(**kwargs):
pioplus_call(sys.argv[1:]) pioplus_call(sys.argv[1:])
@ -63,17 +64,15 @@ def remote_agent_list():
pioplus_call(sys.argv[1:]) pioplus_call(sys.argv[1:])
@cli.command( @cli.command("update",
"update", short_help="Update installed Platforms, Packages and Libraries") short_help="Update installed Platforms, Packages and Libraries")
@click.option( @click.option("-c",
"-c", "--only-check",
"--only-check", is_flag=True,
is_flag=True, help="DEPRECATED. Please use `--dry-run` instead")
help="DEPRECATED. Please use `--dry-run` instead") @click.option("--dry-run",
@click.option( is_flag=True,
"--dry-run", help="Do not update, only check for the new versions")
is_flag=True,
help="Do not update, only check for the new versions")
def remote_update(only_check, dry_run): def remote_update(only_check, dry_run):
pioplus_call(sys.argv[1:]) pioplus_call(sys.argv[1:])
@ -82,16 +81,14 @@ def remote_update(only_check, dry_run):
@click.option("-e", "--environment", multiple=True) @click.option("-e", "--environment", multiple=True)
@click.option("-t", "--target", multiple=True) @click.option("-t", "--target", multiple=True)
@click.option("--upload-port") @click.option("--upload-port")
@click.option( @click.option("-d",
"-d", "--project-dir",
"--project-dir", default=getcwd,
default=getcwd, type=click.Path(exists=True,
type=click.Path( file_okay=True,
exists=True, dir_okay=True,
file_okay=True, writable=True,
dir_okay=True, resolve_path=True))
writable=True,
resolve_path=True))
@click.option("--disable-auto-clean", is_flag=True) @click.option("--disable-auto-clean", is_flag=True)
@click.option("-r", "--force-remote", is_flag=True) @click.option("-r", "--force-remote", is_flag=True)
@click.option("-s", "--silent", 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="<pattern>") @click.option("--ignore", "-i", multiple=True, metavar="<pattern>")
@click.option("--upload-port") @click.option("--upload-port")
@click.option("--test-port") @click.option("--test-port")
@click.option( @click.option("-d",
"-d", "--project-dir",
"--project-dir", default=getcwd,
default=getcwd, type=click.Path(exists=True,
type=click.Path( file_okay=False,
exists=True, dir_okay=True,
file_okay=False, writable=True,
dir_okay=True, resolve_path=True))
writable=True,
resolve_path=True))
@click.option("-r", "--force-remote", is_flag=True) @click.option("-r", "--force-remote", is_flag=True)
@click.option("--without-building", is_flag=True) @click.option("--without-building", is_flag=True)
@click.option("--without-uploading", 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") @remote_device.command("monitor", short_help="Monitor remote device")
@click.option("--port", "-p", help="Port, a number or a device name") @click.option("--port", "-p", help="Port, a number or a device name")
@click.option( @click.option("--baud",
"--baud", "-b", type=int, default=9600, help="Set baud rate, default=9600") "-b",
@click.option( type=int,
"--parity", default=9600,
default="N", help="Set baud rate, default=9600")
type=click.Choice(["N", "E", "O", "S", "M"]), @click.option("--parity",
help="Set parity, default=N") default="N",
@click.option( type=click.Choice(["N", "E", "O", "S", "M"]),
"--rtscts", is_flag=True, help="Enable RTS/CTS flow control, default=Off") help="Set parity, default=N")
@click.option( @click.option("--rtscts",
"--xonxoff", is_flag=True,
is_flag=True, help="Enable RTS/CTS flow control, default=Off")
help="Enable software flow control, default=Off") @click.option("--xonxoff",
@click.option( is_flag=True,
"--rts", help="Enable software flow control, default=Off")
default=None, @click.option("--rts",
type=click.IntRange(0, 1), default=None,
help="Set initial RTS line state") type=click.IntRange(0, 1),
@click.option( help="Set initial RTS line state")
"--dtr", @click.option("--dtr",
default=None, default=None,
type=click.IntRange(0, 1), type=click.IntRange(0, 1),
help="Set initial DTR line state") help="Set initial DTR line state")
@click.option("--echo", is_flag=True, help="Enable local echo, default=Off") @click.option("--echo", is_flag=True, help="Enable local echo, default=Off")
@click.option( @click.option("--encoding",
"--encoding", default="UTF-8",
default="UTF-8", help="Set the encoding for the serial port (e.g. hexlify, "
help="Set the encoding for the serial port (e.g. hexlify, " "Latin1, UTF-8), default: UTF-8")
"Latin1, UTF-8), default: UTF-8")
@click.option("--filter", "-f", multiple=True, help="Add text transformation") @click.option("--filter", "-f", multiple=True, help="Add text transformation")
@click.option( @click.option("--eol",
"--eol", default="CRLF",
default="CRLF", type=click.Choice(["CR", "LF", "CRLF"]),
type=click.Choice(["CR", "LF", "CRLF"]), help="End of line mode, default=CRLF")
help="End of line mode, default=CRLF") @click.option("--raw",
@click.option( is_flag=True,
"--raw", is_flag=True, help="Do not apply any encodings/transformations") help="Do not apply any encodings/transformations")
@click.option( @click.option("--exit-char",
"--exit-char", type=int,
type=int, default=3,
default=3, help="ASCII code of special character that is used to exit "
help="ASCII code of special character that is used to exit " "the application, default=3 (Ctrl+C)")
"the application, default=3 (Ctrl+C)") @click.option("--menu-char",
@click.option( type=int,
"--menu-char", default=20,
type=int, help="ASCII code of special character that is used to "
default=20, "control miniterm (menu), default=20 (DEC)")
help="ASCII code of special character that is used to " @click.option("--quiet",
"control miniterm (menu), default=20 (DEC)") is_flag=True,
@click.option( help="Diagnostics: suppress non-error messages, default=Off")
"--quiet",
is_flag=True,
help="Diagnostics: suppress non-error messages, default=Off")
@click.pass_context @click.pass_context
def device_monitor(ctx, **kwargs): def device_monitor(ctx, **kwargs):

View File

@ -20,8 +20,9 @@ import click
from platformio import exception, util from platformio import exception, util
from platformio.commands.device import device_monitor as cmd_device_monitor from platformio.commands.device import device_monitor as cmd_device_monitor
from platformio.commands.run.helpers import ( from platformio.commands.run.helpers import (_clean_build_dir,
_clean_build_dir, _handle_legacy_libdeps, print_summary) _handle_legacy_libdeps,
print_summary)
from platformio.commands.run.processor import EnvironmentProcessor from platformio.commands.run.processor import EnvironmentProcessor
from platformio.project.config import ProjectConfig from platformio.project.config import ProjectConfig
from platformio.project.helpers import (find_project_dir_above, 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("-e", "--environment", multiple=True)
@click.option("-t", "--target", multiple=True) @click.option("-t", "--target", multiple=True)
@click.option("--upload-port") @click.option("--upload-port")
@click.option( @click.option("-d",
"-d", "--project-dir",
"--project-dir", default=getcwd,
default=getcwd, type=click.Path(exists=True,
type=click.Path( file_okay=True,
exists=True, dir_okay=True,
file_okay=True, writable=True,
dir_okay=True, resolve_path=True))
writable=True, @click.option("-c",
resolve_path=True)) "--project-conf",
@click.option( type=click.Path(exists=True,
"-c", file_okay=True,
"--project-conf", dir_okay=False,
type=click.Path( readable=True,
exists=True, resolve_path=True))
file_okay=True,
dir_okay=False,
readable=True,
resolve_path=True))
@click.option("-s", "--silent", is_flag=True) @click.option("-s", "--silent", is_flag=True)
@click.option("-v", "--verbose", is_flag=True) @click.option("-v", "--verbose", is_flag=True)
@click.option("--disable-auto-clean", 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)) results.append((envname, None))
continue continue
if not silent and any( if not silent and any(status is not None
status is not None for (_, status) in results): for (_, status) in results):
click.echo() click.echo()
ep = EnvironmentProcessor(ctx, envname, config, target, 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 \ if result[1] and "monitor" in ep.get_build_targets() and \
"nobuild" not in ep.get_build_targets(): "nobuild" not in ep.get_build_targets():
ctx.invoke( ctx.invoke(cmd_device_monitor,
cmd_device_monitor, environment=environment[0] if environment else None)
environment=environment[0] if environment else None)
found_error = any(status is False for (_, status) in results) found_error = any(status is False for (_, status) in results)

View File

@ -22,8 +22,9 @@ from platformio import exception, util
from platformio.commands.lib import (CTX_META_STORAGE_DIRS_KEY, from platformio.commands.lib import (CTX_META_STORAGE_DIRS_KEY,
CTX_META_STORAGE_LIBDEPS_KEY) CTX_META_STORAGE_LIBDEPS_KEY)
from platformio.commands.lib import lib_install as cmd_lib_install from platformio.commands.lib import lib_install as cmd_lib_install
from platformio.project.helpers import ( from platformio.project.helpers import (calculate_project_hash,
calculate_project_hash, get_project_dir, get_project_libdeps_dir) get_project_dir,
get_project_libdeps_dir)
def _handle_legacy_libdeps(project_dir, config): def _handle_legacy_libdeps(project_dir, config):
@ -71,8 +72,8 @@ def _clean_build_dir(build_dir):
proj_hash = calculate_project_hash() proj_hash = calculate_project_hash()
# if project's config is modified # if project's config is modified
if (isdir(build_dir) and getmtime( if (isdir(build_dir) and getmtime(join(
join(get_project_dir(), "platformio.ini")) > getmtime(build_dir)): get_project_dir(), "platformio.ini")) > getmtime(build_dir)):
util.rmtree_(build_dir) util.rmtree_(build_dir)
# check project structure # check project structure
@ -93,8 +94,9 @@ def print_header(label, is_error=False, fg=None):
terminal_width, _ = click.get_terminal_size() terminal_width, _ = click.get_terminal_size()
width = len(click.unstyle(label)) width = len(click.unstyle(label))
half_line = "=" * int((terminal_width - width - 2) / 2) half_line = "=" * int((terminal_width - width - 2) / 2)
click.secho( click.secho("%s %s %s" % (half_line, label, half_line),
"%s %s %s" % (half_line, label, half_line), fg=fg, err=is_error) fg=fg,
err=is_error)
def print_summary(results, start_time): def print_summary(results, start_time):
@ -115,13 +117,12 @@ def print_summary(results, start_time):
status_str = click.style("SUCCESS", fg="green") status_str = click.style("SUCCESS", fg="green")
format_str = "Environment {0:<%d}\t[{1}]" % envname_max_len format_str = "Environment {0:<%d}\t[{1}]" % envname_max_len
click.echo( click.echo(format_str.format(click.style(envname, fg="cyan"),
format_str.format(click.style(envname, fg="cyan"), status_str), status_str),
err=status is False) err=status is False)
print_header( print_header("%s%d succeeded in %.2f seconds" %
"%s%d succeeded in %.2f seconds" % ("%d failed, " % failed_nums if failed_nums else "",
("%d failed, " % failed_nums if failed_nums else "", succeeded_nums, succeeded_nums, time() - start_time),
time() - start_time), is_error=failed_nums,
is_error=failed_nums, fg="red" if failed_nums else "green")
fg="red" if failed_nums else "green")

View File

@ -64,10 +64,10 @@ class EnvironmentProcessor(object):
if is_error or "piotest_processor" not in self.cmd_ctx.meta: if is_error or "piotest_processor" not in self.cmd_ctx.meta:
print_header( print_header(
"[%s] Took %.2f seconds" % ( "[%s] Took %.2f seconds" %
(click.style("ERROR", fg="red", bold=True) if is_error else ((click.style("ERROR", fg="red", bold=True) if
click.style("SUCCESS", fg="green", bold=True)), is_error else click.style("SUCCESS", fg="green", bold=True)),
time() - start_time), time() - start_time),
is_error=is_error) is_error=is_error)
return not is_error return not is_error
@ -106,10 +106,9 @@ class EnvironmentProcessor(object):
try: try:
p = PlatformFactory.newPlatform(self.options['platform']) p = PlatformFactory.newPlatform(self.options['platform'])
except exception.UnknownPlatform: except exception.UnknownPlatform:
self.cmd_ctx.invoke( self.cmd_ctx.invoke(cmd_platform_install,
cmd_platform_install, platforms=[self.options['platform']],
platforms=[self.options['platform']], skip_default_package=True)
skip_default_package=True)
p = PlatformFactory.newPlatform(self.options['platform']) p = PlatformFactory.newPlatform(self.options['platform'])
return p.run(build_vars, build_targets, self.silent, self.verbose) return p.run(build_vars, build_targets, self.silent, self.verbose)

View File

@ -30,11 +30,10 @@ def settings_get(name):
terminal_width, _ = click.get_terminal_size() terminal_width, _ = click.get_terminal_size()
click.echo( click.echo(
list_tpl.format( list_tpl.format(name=click.style("Name", fg="cyan"),
name=click.style("Name", fg="cyan"), value=(click.style("Value", fg="green") +
value=(click.style("Value", fg="green") + click.style( click.style(" [Default]", fg="yellow")),
" [Default]", fg="yellow")), description="Description"))
description="Description"))
click.echo("-" * terminal_width) click.echo("-" * terminal_width)
for _name, _data in sorted(app.DEFAULT_SETTINGS.items()): for _name, _data in sorted(app.DEFAULT_SETTINGS.items()):
@ -56,10 +55,9 @@ def settings_get(name):
_value_str += click.style(" ", fg="yellow") _value_str += click.style(" ", fg="yellow")
click.echo( click.echo(
list_tpl.format( list_tpl.format(name=click.style(_name, fg="cyan"),
name=click.style(_name, fg="cyan"), value=_value_str,
value=_value_str, description=_data['description']))
description=_data['description']))
@cli.command("set", short_help="Set new value for the setting") @cli.command("set", short_help="Set new value for the setting")

View File

@ -31,53 +31,45 @@ from platformio.project.helpers import get_project_test_dir
@click.command("test", short_help="Unit Testing") @click.command("test", short_help="Unit Testing")
@click.option("--environment", "-e", multiple=True, metavar="<environment>") @click.option("--environment", "-e", multiple=True, metavar="<environment>")
@click.option( @click.option("--filter",
"--filter", "-f",
"-f", multiple=True,
multiple=True, metavar="<pattern>",
metavar="<pattern>", help="Filter tests by a pattern")
help="Filter tests by a pattern") @click.option("--ignore",
@click.option( "-i",
"--ignore", multiple=True,
"-i", metavar="<pattern>",
multiple=True, help="Ignore tests by a pattern")
metavar="<pattern>",
help="Ignore tests by a pattern")
@click.option("--upload-port") @click.option("--upload-port")
@click.option("--test-port") @click.option("--test-port")
@click.option( @click.option("-d",
"-d", "--project-dir",
"--project-dir", default=getcwd,
default=getcwd, type=click.Path(exists=True,
type=click.Path( file_okay=False,
exists=True, dir_okay=True,
file_okay=False, writable=True,
dir_okay=True, resolve_path=True))
writable=True, @click.option("-c",
resolve_path=True)) "--project-conf",
@click.option( type=click.Path(exists=True,
"-c", file_okay=True,
"--project-conf", dir_okay=False,
type=click.Path( readable=True,
exists=True, resolve_path=True))
file_okay=True,
dir_okay=False,
readable=True,
resolve_path=True))
@click.option("--without-building", is_flag=True) @click.option("--without-building", is_flag=True)
@click.option("--without-uploading", is_flag=True) @click.option("--without-uploading", is_flag=True)
@click.option("--without-testing", is_flag=True) @click.option("--without-testing", is_flag=True)
@click.option("--no-reset", is_flag=True) @click.option("--no-reset", is_flag=True)
@click.option( @click.option("--monitor-rts",
"--monitor-rts", default=None,
default=None, type=click.IntRange(0, 1),
type=click.IntRange(0, 1), help="Set initial RTS line state for Serial Monitor")
help="Set initial RTS line state for Serial Monitor") @click.option("--monitor-dtr",
@click.option( default=None,
"--monitor-dtr", type=click.IntRange(0, 1),
default=None, help="Set initial DTR line state for Serial Monitor")
type=click.IntRange(0, 1),
help="Set initial DTR line state for Serial Monitor")
@click.option("--verbose", "-v", is_flag=True) @click.option("--verbose", "-v", is_flag=True)
@click.pass_context @click.pass_context
def cli( # pylint: disable=redefined-builtin def cli( # pylint: disable=redefined-builtin
@ -130,18 +122,17 @@ def cli( # pylint: disable=redefined-builtin
EmbeddedTestProcessor) EmbeddedTestProcessor)
tp = cls( tp = cls(
ctx, testname, envname, ctx, testname, envname,
dict( dict(project_config=config,
project_config=config, project_dir=project_dir,
project_dir=project_dir, upload_port=upload_port,
upload_port=upload_port, test_port=test_port,
test_port=test_port, without_building=without_building,
without_building=without_building, without_uploading=without_uploading,
without_uploading=without_uploading, without_testing=without_testing,
without_testing=without_testing, no_reset=no_reset,
no_reset=no_reset, monitor_rts=monitor_rts,
monitor_rts=monitor_rts, monitor_dtr=monitor_dtr,
monitor_dtr=monitor_dtr, verbose=verbose))
verbose=verbose))
results.append((tp.process(), testname, envname)) results.append((tp.process(), testname, envname))
if without_testing: if without_testing:
@ -168,17 +159,15 @@ def cli( # pylint: disable=redefined-builtin
format_str = "test/{:<%d} > {:<%d}\t[{}]" % (testname_max_len, format_str = "test/{:<%d} > {:<%d}\t[{}]" % (testname_max_len,
envname_max_len) envname_max_len)
click.echo( click.echo(format_str.format(testname, click.style(envname, fg="cyan"),
format_str.format(testname, click.style(envname, fg="cyan"), status_str),
status_str), err=status is False)
err=status is False)
print_header( print_header("%s%d passed in %.2f seconds" %
"%s%d passed in %.2f seconds" ("%d failed, " % failed_nums if failed_nums else "",
% ("%d failed, " % failed_nums if failed_nums else "", passed_nums, passed_nums, time() - start_time),
time() - start_time), is_error=failed_nums,
is_error=failed_nums, fg="red" if failed_nums else "green")
fg="red" if failed_nums else "green")
if failed_nums: if failed_nums:
raise exception.ReturnErrorCode(1) raise exception.ReturnErrorCode(1)

View File

@ -57,8 +57,8 @@ class EmbeddedTestProcessor(TestProcessorBase):
click.echo() click.echo()
try: try:
ser = serial.Serial( ser = serial.Serial(baudrate=self.get_baudrate(),
baudrate=self.get_baudrate(), timeout=self.SERIAL_TIMEOUT) timeout=self.SERIAL_TIMEOUT)
ser.port = self.get_test_port() ser.port = self.get_test_port()
ser.rts = self.options['monitor_rts'] ser.rts = self.options['monitor_rts']
ser.dtr = self.options['monitor_dtr'] ser.dtr = self.options['monitor_dtr']

View File

@ -86,8 +86,8 @@ class TestProcessorBase(object):
self.test_name = testname self.test_name = testname
self.options = options self.options = options
self.env_name = envname self.env_name = envname
self.env_options = options['project_config'].items( self.env_options = options['project_config'].items(env=envname,
env=envname, as_dict=True) as_dict=True)
self._run_failed = False self._run_failed = False
self._outputcpp_generated = False self._outputcpp_generated = False
@ -108,11 +108,10 @@ class TestProcessorBase(object):
def print_progress(self, text, is_error=False): def print_progress(self, text, is_error=False):
click.echo() click.echo()
print_header( print_header("[test/%s > %s] %s" %
"[test/%s > %s] %s" % (click.style(self.test_name, fg="yellow"), (click.style(self.test_name, fg="yellow"),
click.style(self.env_name, fg="cyan"), click.style(self.env_name, fg="cyan"), text),
text), is_error=is_error)
is_error=is_error)
def build_or_upload(self, target): def build_or_upload(self, target):
if not self._outputcpp_generated: if not self._outputcpp_generated:
@ -126,14 +125,13 @@ class TestProcessorBase(object):
click.echo("Please wait...") click.echo("Please wait...")
try: try:
return self.cmd_ctx.invoke( return self.cmd_ctx.invoke(cmd_run,
cmd_run, project_dir=self.options['project_dir'],
project_dir=self.options['project_dir'], upload_port=self.options['upload_port'],
upload_port=self.options['upload_port'], silent=not self.options['verbose'],
silent=not self.options['verbose'], environment=[self.env_name],
environment=[self.env_name], disable_auto_clean="nobuild" in target,
disable_auto_clean="nobuild" in target, target=target)
target=target)
except exception.ReturnErrorCode: except exception.ReturnErrorCode:
return False return False
@ -146,8 +144,8 @@ class TestProcessorBase(object):
def on_run_out(self, line): def on_run_out(self, line):
line = line.strip() line = line.strip()
if line.endswith(":PASS"): if line.endswith(":PASS"):
click.echo( click.echo("%s\t[%s]" %
"%s\t[%s]" % (line[:-5], click.style("PASSED", fg="green"))) (line[:-5], click.style("PASSED", fg="green")))
elif ":FAIL" in line: elif ":FAIL" in line:
self._run_failed = True self._run_failed = True
click.echo("%s\t[%s]" % (line, click.style("FAILED", fg="red"))) click.echo("%s\t[%s]" % (line, click.style("FAILED", fg="red")))

View File

@ -22,19 +22,18 @@ from platformio.managers.core import update_core_packages
from platformio.managers.lib import LibraryManager from platformio.managers.lib import LibraryManager
@click.command( @click.command("update",
"update", short_help="Update installed platforms, packages and libraries") short_help="Update installed platforms, packages and libraries")
@click.option( @click.option("--core-packages",
"--core-packages", is_flag=True, help="Update only the core packages") is_flag=True,
@click.option( help="Update only the core packages")
"-c", @click.option("-c",
"--only-check", "--only-check",
is_flag=True, is_flag=True,
help="DEPRECATED. Please use `--dry-run` instead") help="DEPRECATED. Please use `--dry-run` instead")
@click.option( @click.option("--dry-run",
"--dry-run", is_flag=True,
is_flag=True, help="Do not update, only check for the new versions")
help="Do not update, only check for the new versions")
@click.pass_context @click.pass_context
def cli(ctx, core_packages, only_check, dry_run): def cli(ctx, core_packages, only_check, dry_run):
# cleanup lib search results, cached board and platform lists # cleanup lib search results, cached board and platform lists

View File

@ -26,8 +26,8 @@ from platformio.proc import exec_command, get_pythonexe_path
from platformio.project.helpers import get_project_cache_dir from platformio.project.helpers import get_project_cache_dir
@click.command( @click.command("upgrade",
"upgrade", short_help="Upgrade PlatformIO to the latest version") short_help="Upgrade PlatformIO to the latest version")
@click.option("--dev", is_flag=True, help="Use development branch") @click.option("--dev", is_flag=True, help="Use development branch")
def cli(dev): def cli(dev):
if not dev and __version__ == get_latest_version(): if not dev and __version__ == get_latest_version():
@ -60,20 +60,19 @@ def cli(dev):
assert r['returncode'] == 0 assert r['returncode'] == 0
assert "version" in r['out'] assert "version" in r['out']
actual_version = r['out'].strip().split("version", 1)[1].strip() actual_version = r['out'].strip().split("version", 1)[1].strip()
click.secho( click.secho("PlatformIO has been successfully upgraded to %s" %
"PlatformIO has been successfully upgraded to %s" % actual_version, actual_version,
fg="green") fg="green")
click.echo("Release notes: ", nl=False) click.echo("Release notes: ", nl=False)
click.secho( click.secho("https://docs.platformio.org/en/latest/history.html",
"https://docs.platformio.org/en/latest/history.html", fg="cyan") fg="cyan")
except Exception as e: # pylint: disable=broad-except except Exception as e: # pylint: disable=broad-except
if not r: if not r:
raise exception.UpgradeError("\n".join([str(cmd), str(e)])) raise exception.UpgradeError("\n".join([str(cmd), str(e)]))
permission_errors = ("permission denied", "not permitted") permission_errors = ("permission denied", "not permitted")
if (any(m in r['err'].lower() for m in permission_errors) if (any(m in r['err'].lower() for m in permission_errors)
and not WINDOWS): and not WINDOWS):
click.secho( click.secho("""
"""
----------------- -----------------
Permission denied 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. WARNING! Don't use `sudo` for the rest PlatformIO commands.
""", """,
fg="yellow", fg="yellow",
err=True) err=True)
raise exception.ReturnErrorCode(1) raise exception.ReturnErrorCode(1)
raise exception.UpgradeError("\n".join([str(cmd), r['out'], r['err']])) 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(): def get_pypi_latest_version():
r = requests.get( r = requests.get("https://pypi.org/pypi/platformio/json",
"https://pypi.org/pypi/platformio/json", headers=util.get_request_defheaders())
headers=util.get_request_defheaders())
r.raise_for_status() r.raise_for_status()
return r.json()['info']['version'] return r.json()['info']['version']

View File

@ -35,11 +35,10 @@ class FileDownloader(object):
def __init__(self, url, dest_dir=None): def __init__(self, url, dest_dir=None):
self._request = None self._request = None
# make connection # make connection
self._request = requests.get( self._request = requests.get(url,
url, stream=True,
stream=True, headers=util.get_request_defheaders(),
headers=util.get_request_defheaders(), verify=version_info >= (2, 7, 9))
verify=version_info >= (2, 7, 9))
if self._request.status_code != 200: if self._request.status_code != 200:
raise FDUnrecognizedStatusCode(self._request.status_code, url) raise FDUnrecognizedStatusCode(self._request.status_code, url)

View File

@ -26,8 +26,9 @@ from platformio.commands.run import cli as cmd_run
from platformio.compat import PY2, WINDOWS, get_file_contents from platformio.compat import PY2, WINDOWS, get_file_contents
from platformio.proc import where_is_program from platformio.proc import where_is_program
from platformio.project.config import ProjectConfig from platformio.project.config import ProjectConfig
from platformio.project.helpers import ( from platformio.project.helpers import (get_project_lib_dir,
get_project_lib_dir, get_project_libdeps_dir, get_project_src_dir) get_project_libdeps_dir,
get_project_src_dir)
class ProjectGenerator(object): class ProjectGenerator(object):
@ -120,9 +121,8 @@ class ProjectGenerator(object):
file_name = basename(tpl_path)[:-4] file_name = basename(tpl_path)[:-4]
contents = self._render_tpl(tpl_path) contents = self._render_tpl(tpl_path)
self._merge_contents( self._merge_contents(join(dst_dir, file_name),
join(dst_dir, file_name), contents.encode("utf8") if PY2 else contents)
contents.encode("utf8") if PY2 else contents)
def _render_tpl(self, tpl_path): def _render_tpl(self, tpl_path):
return bottle.template(get_file_contents(tpl_path), **self._tplvars) return bottle.template(get_file_contents(tpl_path), **self._tplvars)

View File

@ -92,12 +92,12 @@ class Upgrader(object):
self.to_version = semantic_version.Version.coerce( self.to_version = semantic_version.Version.coerce(
util.pepver_to_semver(to_version)) util.pepver_to_semver(to_version))
self._upgraders = [(semantic_version.Version("3.0.0-a.1"), self._upgraders = [
self._upgrade_to_3_0_0), (semantic_version.Version("3.0.0-a.1"), self._upgrade_to_3_0_0),
(semantic_version.Version("3.0.0-b.11"), (semantic_version.Version("3.0.0-b.11"),
self._upgrade_to_3_0_0b11), self._upgrade_to_3_0_0b11),
(semantic_version.Version("3.5.0-a.2"), (semantic_version.Version("3.5.0-a.2"), self._update_dev_platforms)
self._update_dev_platforms)] ]
def run(self, ctx): def run(self, ctx):
if self.from_version > self.to_version: if self.from_version > self.to_version:
@ -166,12 +166,11 @@ def after_upgrade(ctx):
last_version)) > semantic_version.Version.coerce( last_version)) > semantic_version.Version.coerce(
util.pepver_to_semver(__version__)): util.pepver_to_semver(__version__)):
click.secho("*" * terminal_width, fg="yellow") click.secho("*" * terminal_width, fg="yellow")
click.secho( click.secho("Obsolete PIO Core v%s is used (previous was %s)" %
"Obsolete PIO Core v%s is used (previous was %s)" % (__version__, (__version__, last_version),
last_version), fg="yellow")
fg="yellow") click.secho("Please remove multiple PIO Cores from a system:",
click.secho( fg="yellow")
"Please remove multiple PIO Cores from a system:", fg="yellow")
click.secho( click.secho(
"https://docs.platformio.org/page/faq.html" "https://docs.platformio.org/page/faq.html"
"#multiple-pio-cores-in-a-system", "#multiple-pio-cores-in-a-system",
@ -188,22 +187,20 @@ def after_upgrade(ctx):
u = Upgrader(last_version, __version__) u = Upgrader(last_version, __version__)
if u.run(ctx): if u.run(ctx):
app.set_state_item("last_version", __version__) app.set_state_item("last_version", __version__)
click.secho( click.secho("PlatformIO has been successfully upgraded to %s!\n" %
"PlatformIO has been successfully upgraded to %s!\n" % __version__,
__version__, fg="green")
fg="green") telemetry.on_event(category="Auto",
telemetry.on_event( action="Upgrade",
category="Auto", label="%s > %s" % (last_version, __version__))
action="Upgrade",
label="%s > %s" % (last_version, __version__))
else: else:
raise exception.UpgradeError("Auto upgrading...") raise exception.UpgradeError("Auto upgrading...")
click.echo("") click.echo("")
# PlatformIO banner # PlatformIO banner
click.echo("*" * terminal_width) click.echo("*" * terminal_width)
click.echo( click.echo("If you like %s, please:" %
"If you like %s, please:" % (click.style("PlatformIO", fg="cyan"))) (click.style("PlatformIO", fg="cyan")))
click.echo("- %s us on Twitter to stay up-to-date " click.echo("- %s us on Twitter to stay up-to-date "
"on the latest project news > %s" % "on the latest project news > %s" %
(click.style("follow", fg="cyan"), (click.style("follow", fg="cyan"),
@ -218,9 +215,9 @@ def after_upgrade(ctx):
(click.style("try", fg="cyan"), (click.style("try", fg="cyan"),
click.style("https://platformio.org/platformio-ide", fg="cyan"))) click.style("https://platformio.org/platformio-ide", fg="cyan")))
if not is_ci(): if not is_ci():
click.echo("- %s us with PlatformIO Plus > %s" % (click.style( click.echo("- %s us with PlatformIO Plus > %s" %
"support", fg="cyan"), click.style( (click.style("support", fg="cyan"),
"https://pioplus.com", fg="cyan"))) click.style("https://pioplus.com", fg="cyan")))
click.echo("*" * terminal_width) click.echo("*" * terminal_width)
click.echo("") click.echo("")
@ -250,14 +247,14 @@ def check_platformio_upgrade():
click.echo("") click.echo("")
click.echo("*" * terminal_width) click.echo("*" * terminal_width)
click.secho( click.secho("There is a new version %s of PlatformIO available.\n"
"There is a new version %s of PlatformIO available.\n" "Please upgrade it via `" % latest_version,
"Please upgrade it via `" % latest_version, fg="yellow",
fg="yellow", nl=False)
nl=False)
if getenv("PLATFORMIO_IDE"): if getenv("PLATFORMIO_IDE"):
click.secho( click.secho("PlatformIO IDE Menu: Upgrade PlatformIO",
"PlatformIO IDE Menu: Upgrade PlatformIO", fg="cyan", nl=False) fg="cyan",
nl=False)
click.secho("`.", fg="yellow") click.secho("`.", fg="yellow")
elif join("Cellar", "platformio") in util.get_source_dir(): elif join("Cellar", "platformio") in util.get_source_dir():
click.secho("brew update && brew upgrade", fg="cyan", nl=False) 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("pip install -U platformio", fg="cyan", nl=False)
click.secho("` command.", fg="yellow") click.secho("` command.", fg="yellow")
click.secho("Changes: ", fg="yellow", nl=False) click.secho("Changes: ", fg="yellow", nl=False)
click.secho( click.secho("https://docs.platformio.org/en/latest/history.html",
"https://docs.platformio.org/en/latest/history.html", fg="cyan") fg="cyan")
click.echo("*" * terminal_width) click.echo("*" * terminal_width)
click.echo("") click.echo("")
@ -305,29 +302,26 @@ def check_internal_updates(ctx, what):
click.echo("") click.echo("")
click.echo("*" * terminal_width) click.echo("*" * terminal_width)
click.secho( click.secho("There are the new updates for %s (%s)" %
"There are the new updates for %s (%s)" % (what, (what, ", ".join(outdated_items)),
", ".join(outdated_items)), fg="yellow")
fg="yellow")
if not app.get_setting("auto_update_" + what): if not app.get_setting("auto_update_" + what):
click.secho("Please update them via ", fg="yellow", nl=False) click.secho("Please update them via ", fg="yellow", nl=False)
click.secho( click.secho("`platformio %s update`" %
"`platformio %s update`" % ("lib --global" if what == "libraries" else "platform"),
("lib --global" if what == "libraries" else "platform"), fg="cyan",
fg="cyan", nl=False)
nl=False)
click.secho(" command.\n", fg="yellow") click.secho(" command.\n", fg="yellow")
click.secho( click.secho(
"If you want to manually check for the new versions " "If you want to manually check for the new versions "
"without updating, please use ", "without updating, please use ",
fg="yellow", fg="yellow",
nl=False) nl=False)
click.secho( click.secho("`platformio %s update --dry-run`" %
"`platformio %s update --dry-run`" % ("lib --global" if what == "libraries" else "platform"),
("lib --global" if what == "libraries" else "platform"), fg="cyan",
fg="cyan", nl=False)
nl=False)
click.secho(" command.", fg="yellow") click.secho(" command.", fg="yellow")
else: else:
click.secho("Please wait while updating %s ..." % what, fg="yellow") 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) ctx.invoke(cmd_lib_update, libraries=outdated_items)
click.echo() click.echo()
telemetry.on_event( telemetry.on_event(category="Auto",
category="Auto", action="Update", label=what.title()) action="Update",
label=what.title())
click.echo("*" * terminal_width) click.echo("*" * terminal_width)
click.echo("") click.echo("")

View File

@ -111,8 +111,8 @@ def shutdown_piohome_servers():
port = 8010 port = 8010
while port < 8050: while port < 8050:
try: try:
requests.get( requests.get("http://127.0.0.1:%d?__shutdown__=1" % port,
"http://127.0.0.1:%d?__shutdown__=1" % port, timeout=0.01) timeout=0.01)
except: # pylint: disable=bare-except except: # pylint: disable=bare-except
pass pass
port += 1 port += 1

View File

@ -190,14 +190,12 @@ class LibraryManager(BasePkgManager):
def get_latest_repo_version(self, name, requirements, silent=False): def get_latest_repo_version(self, name, requirements, silent=False):
item = self.max_satisfying_repo_version( item = self.max_satisfying_repo_version(
util.get_api_result( util.get_api_result("/lib/info/%d" % self.search_lib_id(
"/lib/info/%d" % self.search_lib_id( {
{ "name": name,
"name": name, "requirements": requirements
"requirements": requirements }, silent=silent),
}, cache_valid="1h")['versions'], requirements)
silent=silent),
cache_valid="1h")['versions'], requirements)
return item['name'] if item else None return item['name'] if item else None
def _install_from_piorepo(self, name, requirements): def _install_from_piorepo(self, name, requirements):
@ -206,10 +204,9 @@ class LibraryManager(BasePkgManager):
if not version: if not version:
raise exception.UndefinedPackageVersion(requirements or "latest", raise exception.UndefinedPackageVersion(requirements or "latest",
util.get_systype()) util.get_systype())
dl_data = util.get_api_result( dl_data = util.get_api_result("/lib/download/" + str(name[3:]),
"/lib/download/" + str(name[3:]), dict(version=version),
dict(version=version), cache_valid="30d")
cache_valid="30d")
assert dl_data assert dl_data
return self._install_from_url( return self._install_from_url(
@ -231,8 +228,8 @@ class LibraryManager(BasePkgManager):
# looking in PIO Library Registry # looking in PIO Library Registry
if not silent: if not silent:
click.echo("Looking for %s library in registry" % click.style( click.echo("Looking for %s library in registry" %
filters['name'], fg="cyan")) click.style(filters['name'], fg="cyan"))
query = [] query = []
for key in filters: for key in filters:
if key not in ("name", "authors", "frameworks", "platforms"): if key not in ("name", "authors", "frameworks", "platforms"):
@ -245,19 +242,19 @@ class LibraryManager(BasePkgManager):
(key[:-1] if key.endswith("s") else key, value)) (key[:-1] if key.endswith("s") else key, value))
lib_info = None lib_info = None
result = util.get_api_result( result = util.get_api_result("/v2/lib/search",
"/v2/lib/search", dict(query=" ".join(query)), cache_valid="1h") dict(query=" ".join(query)),
cache_valid="1h")
if result['total'] == 1: if result['total'] == 1:
lib_info = result['items'][0] lib_info = result['items'][0]
elif result['total'] > 1: elif result['total'] > 1:
if silent and not interactive: if silent and not interactive:
lib_info = result['items'][0] lib_info = result['items'][0]
else: else:
click.secho( click.secho("Conflict: More than one library has been found "
"Conflict: More than one library has been found " "by request %s:" % json.dumps(filters),
"by request %s:" % json.dumps(filters), fg="yellow",
fg="yellow", err=True)
err=True)
for item in result['items']: for item in result['items']:
commands.lib.print_lib_item(item) commands.lib.print_lib_item(item)
@ -269,10 +266,11 @@ class LibraryManager(BasePkgManager):
err=True) err=True)
lib_info = result['items'][0] lib_info = result['items'][0]
else: else:
deplib_id = click.prompt( deplib_id = click.prompt("Please choose library ID",
"Please choose library ID", type=click.Choice([
type=click.Choice( str(i['id'])
[str(i['id']) for i in result['items']])) for i in result['items']
]))
for item in result['items']: for item in result['items']:
if item['id'] == int(deplib_id): if item['id'] == int(deplib_id):
lib_info = item lib_info = item
@ -306,9 +304,8 @@ class LibraryManager(BasePkgManager):
continue continue
if key not in manifest: if key not in manifest:
return None return None
if not util.items_in_list( if not util.items_in_list(util.items_to_list(filters[key]),
util.items_to_list(filters[key]), util.items_to_list(manifest[key])):
util.items_to_list(manifest[key])):
return None return None
if "authors" in filters: if "authors" in filters:
@ -339,20 +336,20 @@ class LibraryManager(BasePkgManager):
force=False): force=False):
_name, _requirements, _url = self.parse_pkg_uri(name, requirements) _name, _requirements, _url = self.parse_pkg_uri(name, requirements)
if not _url: if not _url:
name = "id=%d" % self.search_lib_id({ name = "id=%d" % self.search_lib_id(
"name": _name, {
"requirements": _requirements "name": _name,
}, "requirements": _requirements
silent=silent, },
interactive=interactive) silent=silent,
interactive=interactive)
requirements = _requirements requirements = _requirements
pkg_dir = BasePkgManager.install( pkg_dir = BasePkgManager.install(self,
self, name,
name, requirements,
requirements, silent=silent,
silent=silent, after_update=after_update,
after_update=after_update, force=force)
force=force)
if not pkg_dir: if not pkg_dir:
return None return None
@ -376,12 +373,11 @@ class LibraryManager(BasePkgManager):
self.INSTALL_HISTORY.append(history_key) self.INSTALL_HISTORY.append(history_key)
if any(s in filters.get("version", "") for s in ("\\", "/")): if any(s in filters.get("version", "") for s in ("\\", "/")):
self.install( self.install("{name}={version}".format(**filters),
"{name}={version}".format(**filters), silent=silent,
silent=silent, after_update=after_update,
after_update=after_update, interactive=interactive,
interactive=interactive, force=force)
force=force)
else: else:
try: try:
lib_id = self.search_lib_id(filters, silent, interactive) lib_id = self.search_lib_id(filters, silent, interactive)
@ -391,20 +387,18 @@ class LibraryManager(BasePkgManager):
continue continue
if filters.get("version"): if filters.get("version"):
self.install( self.install(lib_id,
lib_id, filters.get("version"),
filters.get("version"), silent=silent,
silent=silent, after_update=after_update,
after_update=after_update, interactive=interactive,
interactive=interactive, force=force)
force=force)
else: else:
self.install( self.install(lib_id,
lib_id, silent=silent,
silent=silent, after_update=after_update,
after_update=after_update, interactive=interactive,
interactive=interactive, force=force)
force=force)
return pkg_dir return pkg_dir

View File

@ -92,8 +92,8 @@ class PkgRepoMixin(object):
reqspec = None reqspec = None
if requirements: if requirements:
try: try:
reqspec = self.parse_semver_spec( reqspec = self.parse_semver_spec(requirements,
requirements, raise_exception=True) raise_exception=True)
except ValueError: except ValueError:
pass pass
@ -430,8 +430,8 @@ class PkgInstallerMixin(object):
try: try:
if requirements and not self.parse_semver_spec( if requirements and not self.parse_semver_spec(
requirements, raise_exception=True).match( requirements, raise_exception=True).match(
self.parse_semver_version( self.parse_semver_version(manifest['version'],
manifest['version'], raise_exception=True)): raise_exception=True)):
continue continue
elif not best or (self.parse_semver_version( elif not best or (self.parse_semver_version(
manifest['version'], raise_exception=True) > manifest['version'], raise_exception=True) >
@ -648,8 +648,9 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin):
if "__src_url" in manifest: if "__src_url" in manifest:
try: try:
vcs = VCSClientFactory.newClient( vcs = VCSClientFactory.newClient(pkg_dir,
pkg_dir, manifest['__src_url'], silent=True) manifest['__src_url'],
silent=True)
except (AttributeError, exception.PlatformioException): except (AttributeError, exception.PlatformioException):
return None return None
if not vcs.can_be_updated: if not vcs.can_be_updated:
@ -658,8 +659,8 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin):
else: else:
try: try:
latest = self.get_latest_repo_version( latest = self.get_latest_repo_version(
"id=%d" % manifest['id'] "id=%d" %
if "id" in manifest else manifest['name'], manifest['id'] if "id" in manifest else manifest['name'],
requirements, requirements,
silent=True) silent=True)
except (exception.PlatformioException, ValueError): except (exception.PlatformioException, ValueError):
@ -671,10 +672,10 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin):
up_to_date = False up_to_date = False
try: try:
assert "__src_url" not in manifest assert "__src_url" not in manifest
up_to_date = (self.parse_semver_version( up_to_date = (self.parse_semver_version(manifest['version'],
manifest['version'], raise_exception=True) >= raise_exception=True) >=
self.parse_semver_version( self.parse_semver_version(latest,
latest, raise_exception=True)) raise_exception=True))
except (AssertionError, ValueError): except (AssertionError, ValueError):
up_to_date = latest == manifest['version'] up_to_date = latest == manifest['version']
@ -720,8 +721,10 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin):
return package_dir return package_dir
if url: if url:
pkg_dir = self._install_from_url( pkg_dir = self._install_from_url(name,
name, url, requirements, track=True) url,
requirements,
track=True)
else: else:
pkg_dir = self._install_from_piorepo(name, requirements) pkg_dir = self._install_from_piorepo(name, requirements)
@ -733,10 +736,9 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin):
assert manifest assert manifest
if not after_update: if not after_update:
telemetry.on_event( telemetry.on_event(category=self.__class__.__name__,
category=self.__class__.__name__, action="Install",
action="Install", label=manifest['name'])
label=manifest['name'])
if not silent: if not silent:
click.secho( click.secho(
@ -759,14 +761,13 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin):
pkg_dir = self.get_package_dir(name, requirements, url) pkg_dir = self.get_package_dir(name, requirements, url)
if not pkg_dir: if not pkg_dir:
raise exception.UnknownPackage( raise exception.UnknownPackage("%s @ %s" %
"%s @ %s" % (package, requirements or "*")) (package, requirements or "*"))
manifest = self.load_manifest(pkg_dir) manifest = self.load_manifest(pkg_dir)
click.echo( click.echo("Uninstalling %s @ %s: \t" % (click.style(
"Uninstalling %s @ %s: \t" % (click.style( manifest['name'], fg="cyan"), manifest['version']),
manifest['name'], fg="cyan"), manifest['version']), nl=False)
nl=False)
if islink(pkg_dir): if islink(pkg_dir):
os.unlink(pkg_dir) os.unlink(pkg_dir)
@ -785,10 +786,9 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin):
click.echo("[%s]" % click.style("OK", fg="green")) click.echo("[%s]" % click.style("OK", fg="green"))
if not after_update: if not after_update:
telemetry.on_event( telemetry.on_event(category=self.__class__.__name__,
category=self.__class__.__name__, action="Uninstall",
action="Uninstall", label=manifest['name'])
label=manifest['name'])
return True return True
@ -799,17 +799,16 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin):
pkg_dir = self.get_package_dir(*self.parse_pkg_uri(package)) pkg_dir = self.get_package_dir(*self.parse_pkg_uri(package))
if not pkg_dir: if not pkg_dir:
raise exception.UnknownPackage( raise exception.UnknownPackage("%s @ %s" %
"%s @ %s" % (package, requirements or "*")) (package, requirements or "*"))
manifest = self.load_manifest(pkg_dir) manifest = self.load_manifest(pkg_dir)
name = manifest['name'] name = manifest['name']
click.echo( click.echo("{} {:<40} @ {:<15}".format(
"{} {:<40} @ {:<15}".format( "Checking" if only_check else "Updating",
"Checking" if only_check else "Updating", click.style(manifest['name'], fg="cyan"), manifest['version']),
click.style(manifest['name'], fg="cyan"), manifest['version']), nl=False)
nl=False)
if not util.internet_on(): if not util.internet_on():
click.echo("[%s]" % (click.style("Off-line", fg="yellow"))) click.echo("[%s]" % (click.style("Off-line", fg="yellow")))
return None return None
@ -828,16 +827,15 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin):
if "__src_url" in manifest: if "__src_url" in manifest:
vcs = VCSClientFactory.newClient(pkg_dir, manifest['__src_url']) vcs = VCSClientFactory.newClient(pkg_dir, manifest['__src_url'])
assert vcs.update() assert vcs.update()
self._update_src_manifest( self._update_src_manifest(dict(version=vcs.get_current_revision()),
dict(version=vcs.get_current_revision()), vcs.storage_dir) vcs.storage_dir)
else: else:
self.uninstall(pkg_dir, after_update=True) self.uninstall(pkg_dir, after_update=True)
self.install(name, latest, after_update=True) self.install(name, latest, after_update=True)
telemetry.on_event( telemetry.on_event(category=self.__class__.__name__,
category=self.__class__.__name__, action="Update",
action="Update", label=manifest['name'])
label=manifest['name'])
return True return True

View File

@ -30,9 +30,10 @@ from platformio.managers.package import BasePkgManager, PackageManager
from platformio.proc import (BuildAsyncPipe, copy_pythonpath_to_osenv, from platformio.proc import (BuildAsyncPipe, copy_pythonpath_to_osenv,
exec_command, get_pythonexe_path) exec_command, get_pythonexe_path)
from platformio.project.config import ProjectConfig from platformio.project.config import ProjectConfig
from platformio.project.helpers import ( from platformio.project.helpers import (get_project_boards_dir,
get_project_boards_dir, get_project_core_dir, get_project_packages_dir, get_project_core_dir,
get_project_platforms_dir) get_project_packages_dir,
get_project_platforms_dir)
try: try:
from urllib.parse import quote from urllib.parse import quote
@ -75,8 +76,11 @@ class PlatformManager(BasePkgManager):
silent=False, silent=False,
force=False, force=False,
**_): # pylint: disable=too-many-arguments, arguments-differ **_): # pylint: disable=too-many-arguments, arguments-differ
platform_dir = BasePkgManager.install( platform_dir = BasePkgManager.install(self,
self, name, requirements, silent=silent, force=force) name,
requirements,
silent=silent,
force=force)
p = PlatformFactory.newPlatform(platform_dir) p = PlatformFactory.newPlatform(platform_dir)
# don't cleanup packages or install them after update # don't cleanup packages or install them after update
@ -84,12 +88,11 @@ class PlatformManager(BasePkgManager):
if after_update: if after_update:
return True return True
p.install_packages( p.install_packages(with_packages,
with_packages, without_packages,
without_packages, skip_default_package,
skip_default_package, silent=silent,
silent=silent, force=force)
force=force)
return self.cleanup_packages(list(p.packages)) return self.cleanup_packages(list(p.packages))
def uninstall(self, package, requirements=None, after_update=False): def uninstall(self, package, requirements=None, after_update=False):
@ -141,8 +144,8 @@ class PlatformManager(BasePkgManager):
self.cleanup_packages(list(p.packages)) self.cleanup_packages(list(p.packages))
if missed_pkgs: if missed_pkgs:
p.install_packages( p.install_packages(with_packages=list(missed_pkgs),
with_packages=list(missed_pkgs), skip_default_package=True) skip_default_package=True)
return True return True
@ -253,8 +256,8 @@ class PlatformFactory(object):
cls.load_module(name, join(platform_dir, "platform.py")), cls.load_module(name, join(platform_dir, "platform.py")),
cls.get_clsname(name)) cls.get_clsname(name))
else: else:
platform_cls = type( platform_cls = type(str(cls.get_clsname(name)), (PlatformBase, ),
str(cls.get_clsname(name)), (PlatformBase, ), {}) {})
_instance = platform_cls(join(platform_dir, "platform.json")) _instance = platform_cls(join(platform_dir, "platform.json"))
assert isinstance(_instance, PlatformBase) assert isinstance(_instance, PlatformBase)
@ -285,8 +288,9 @@ class PlatformPackagesMixin(object):
elif (name in with_packages or elif (name in with_packages or
not (skip_default_package or opts.get("optional", False))): not (skip_default_package or opts.get("optional", False))):
if ":" in version: if ":" in version:
self.pm.install( self.pm.install("%s=%s" % (name, version),
"%s=%s" % (name, version), silent=silent, force=force) silent=silent,
force=force)
else: else:
self.pm.install(name, version, silent=silent, force=force) 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))) cmd.append("%s=%s" % (key.upper(), base64.b64encode(value)))
else: else:
cmd.append( cmd.append(
"%s=%s" % (key.upper(), base64.b64encode( "%s=%s" %
value.encode()).decode())) (key.upper(), base64.b64encode(value.encode()).decode()))
def _write_and_flush(stream, data): def _write_and_flush(stream, data):
stream.write(data) stream.write(data)
@ -461,8 +465,8 @@ class PlatformRunMixin(object):
""".format(filename=filename, """.format(filename=filename,
filename_styled=click.style(filename, fg="cyan"), filename_styled=click.style(filename, fg="cyan"),
link=click.style( link=click.style(
"https://platformio.org/lib/search?query=header:%s" % quote( "https://platformio.org/lib/search?query=header:%s" %
filename, safe=""), quote(filename, safe=""),
fg="blue"), fg="blue"),
dots="*" * (56 + len(filename))) dots="*" * (56 + len(filename)))
click.echo(banner, err=True) click.echo(banner, err=True)

View File

@ -182,8 +182,8 @@ class ProjectConfig(object):
except ConfigParser.Error as e: except ConfigParser.Error as e:
raise exception.InvalidProjectConf(self.path, str(e)) raise exception.InvalidProjectConf(self.path, str(e))
option_meta = ProjectOptions.get( option_meta = ProjectOptions.get("%s.%s" %
"%s.%s" % (section.split(":", 1)[0], option)) (section.split(":", 1)[0], option))
if not option_meta: if not option_meta:
return value or default return value or default
@ -281,8 +281,8 @@ class ProjectConfig(object):
warnings.append( warnings.append(
"`%s` configuration option in section [%s] is " "`%s` configuration option in section [%s] is "
"deprecated and will be removed in the next release! " "deprecated and will be removed in the next release! "
"Please use `%s` instead" % (option, section, "Please use `%s` instead" %
renamed_options[option])) (option, section, renamed_options[option]))
# rename on-the-fly # rename on-the-fly
self._parser.set(section, renamed_options[option], self._parser.set(section, renamed_options[option],
self._parser.get(section, option)) self._parser.get(section, option))

View File

@ -46,41 +46,39 @@ ProjectOptions = OrderedDict([
# [platformio] # [platformio]
# #
ConfigPlatformioOption(name="description"), ConfigPlatformioOption(name="description"),
ConfigPlatformioOption( ConfigPlatformioOption(name="env_default",
name="env_default", multiple=True,
multiple=True, sysenvvar="PLATFORMIO_ENV_DEFAULT"),
sysenvvar="PLATFORMIO_ENV_DEFAULT"),
ConfigPlatformioOption(name="extra_configs", multiple=True), ConfigPlatformioOption(name="extra_configs", multiple=True),
# Dirs # Dirs
ConfigPlatformioOption( ConfigPlatformioOption(name="core_dir",
name="core_dir", oldnames=["home_dir"],
oldnames=["home_dir"], sysenvvar="PLATFORMIO_CORE_DIR"),
sysenvvar="PLATFORMIO_CORE_DIR"), ConfigPlatformioOption(name="globallib_dir",
ConfigPlatformioOption( sysenvvar="PLATFORMIO_GLOBALLIB_DIR"),
name="globallib_dir", sysenvvar="PLATFORMIO_GLOBALLIB_DIR"), ConfigPlatformioOption(name="platforms_dir",
ConfigPlatformioOption( sysenvvar="PLATFORMIO_PLATFORMS_DIR"),
name="platforms_dir", sysenvvar="PLATFORMIO_PLATFORMS_DIR"), ConfigPlatformioOption(name="packages_dir",
ConfigPlatformioOption( sysenvvar="PLATFORMIO_PACKAGES_DIR"),
name="packages_dir", sysenvvar="PLATFORMIO_PACKAGES_DIR"), ConfigPlatformioOption(name="cache_dir",
ConfigPlatformioOption( sysenvvar="PLATFORMIO_CACHE_DIR"),
name="cache_dir", sysenvvar="PLATFORMIO_CACHE_DIR"), ConfigPlatformioOption(name="workspace_dir",
ConfigPlatformioOption( sysenvvar="PLATFORMIO_WORKSPACE_DIR"),
name="workspace_dir", sysenvvar="PLATFORMIO_WORKSPACE_DIR"), ConfigPlatformioOption(name="build_dir",
ConfigPlatformioOption( sysenvvar="PLATFORMIO_BUILD_DIR"),
name="build_dir", sysenvvar="PLATFORMIO_BUILD_DIR"), ConfigPlatformioOption(name="libdeps_dir",
ConfigPlatformioOption( sysenvvar="PLATFORMIO_LIBDEPS_DIR"),
name="libdeps_dir", sysenvvar="PLATFORMIO_LIBDEPS_DIR"),
ConfigPlatformioOption(name="lib_dir", sysenvvar="PLATFORMIO_LIB_DIR"), ConfigPlatformioOption(name="lib_dir", sysenvvar="PLATFORMIO_LIB_DIR"),
ConfigPlatformioOption( ConfigPlatformioOption(name="include_dir",
name="include_dir", sysenvvar="PLATFORMIO_INCLUDE_DIR"), sysenvvar="PLATFORMIO_INCLUDE_DIR"),
ConfigPlatformioOption(name="src_dir", sysenvvar="PLATFORMIO_SRC_DIR"), ConfigPlatformioOption(name="src_dir", sysenvvar="PLATFORMIO_SRC_DIR"),
ConfigPlatformioOption( ConfigPlatformioOption(name="test_dir",
name="test_dir", sysenvvar="PLATFORMIO_TEST_DIR"), sysenvvar="PLATFORMIO_TEST_DIR"),
ConfigPlatformioOption( ConfigPlatformioOption(name="boards_dir",
name="boards_dir", sysenvvar="PLATFORMIO_BOARDS_DIR"), sysenvvar="PLATFORMIO_BOARDS_DIR"),
ConfigPlatformioOption( ConfigPlatformioOption(name="data_dir",
name="data_dir", sysenvvar="PLATFORMIO_DATA_DIR"), sysenvvar="PLATFORMIO_DATA_DIR"),
# #
# [env] # [env]
@ -94,59 +92,49 @@ ProjectOptions = OrderedDict([
# Board # Board
ConfigEnvOption(name="board", buildenvvar="BOARD"), ConfigEnvOption(name="board", buildenvvar="BOARD"),
ConfigEnvOption( ConfigEnvOption(name="board_build.mcu",
name="board_build.mcu", oldnames=["board_mcu"],
oldnames=["board_mcu"], buildenvvar="BOARD_MCU"),
buildenvvar="BOARD_MCU"), ConfigEnvOption(name="board_build.f_cpu",
ConfigEnvOption( oldnames=["board_f_cpu"],
name="board_build.f_cpu", buildenvvar="BOARD_F_CPU"),
oldnames=["board_f_cpu"], ConfigEnvOption(name="board_build.f_flash",
buildenvvar="BOARD_F_CPU"), oldnames=["board_f_flash"],
ConfigEnvOption( buildenvvar="BOARD_F_FLASH"),
name="board_build.f_flash", ConfigEnvOption(name="board_build.flash_mode",
oldnames=["board_f_flash"], oldnames=["board_flash_mode"],
buildenvvar="BOARD_F_FLASH"), buildenvvar="BOARD_FLASH_MODE"),
ConfigEnvOption(
name="board_build.flash_mode",
oldnames=["board_flash_mode"],
buildenvvar="BOARD_FLASH_MODE"),
# Build # Build
ConfigEnvOption( ConfigEnvOption(name="build_flags",
name="build_flags", multiple=True,
multiple=True, sysenvvar="PLATFORMIO_BUILD_FLAGS",
sysenvvar="PLATFORMIO_BUILD_FLAGS", buildenvvar="BUILD_FLAGS"),
buildenvvar="BUILD_FLAGS"), ConfigEnvOption(name="src_build_flags",
ConfigEnvOption( multiple=True,
name="src_build_flags", sysenvvar="PLATFORMIO_SRC_BUILD_FLAGS",
multiple=True, buildenvvar="SRC_BUILD_FLAGS"),
sysenvvar="PLATFORMIO_SRC_BUILD_FLAGS", ConfigEnvOption(name="build_unflags",
buildenvvar="SRC_BUILD_FLAGS"), multiple=True,
ConfigEnvOption( sysenvvar="PLATFORMIO_BUILD_UNFLAGS",
name="build_unflags", buildenvvar="BUILD_UNFLAGS"),
multiple=True, ConfigEnvOption(name="src_filter",
sysenvvar="PLATFORMIO_BUILD_UNFLAGS", multiple=True,
buildenvvar="BUILD_UNFLAGS"), sysenvvar="PLATFORMIO_SRC_FILTER",
ConfigEnvOption( buildenvvar="SRC_FILTER"),
name="src_filter",
multiple=True,
sysenvvar="PLATFORMIO_SRC_FILTER",
buildenvvar="SRC_FILTER"),
# Upload # Upload
ConfigEnvOption( ConfigEnvOption(name="upload_port",
name="upload_port", sysenvvar="PLATFORMIO_UPLOAD_PORT",
sysenvvar="PLATFORMIO_UPLOAD_PORT", buildenvvar="UPLOAD_PORT"),
buildenvvar="UPLOAD_PORT"),
ConfigEnvOption(name="upload_protocol", buildenvvar="UPLOAD_PROTOCOL"), ConfigEnvOption(name="upload_protocol", buildenvvar="UPLOAD_PROTOCOL"),
ConfigEnvOption(name="upload_speed", buildenvvar="UPLOAD_SPEED"), ConfigEnvOption(name="upload_speed", buildenvvar="UPLOAD_SPEED"),
ConfigEnvOption( ConfigEnvOption(name="upload_flags",
name="upload_flags", multiple=True,
multiple=True, sysenvvar="PLATFORMIO_UPLOAD_FLAGS",
sysenvvar="PLATFORMIO_UPLOAD_FLAGS", buildenvvar="UPLOAD_FLAGS"),
buildenvvar="UPLOAD_FLAGS"), ConfigEnvOption(name="upload_resetmethod",
ConfigEnvOption( buildenvvar="UPLOAD_RESETMETHOD"),
name="upload_resetmethod", buildenvvar="UPLOAD_RESETMETHOD"),
# Monitor # Monitor
ConfigEnvOption(name="monitor_port"), ConfigEnvOption(name="monitor_port"),
@ -156,15 +144,13 @@ ProjectOptions = OrderedDict([
ConfigEnvOption(name="monitor_flags", multiple=True), ConfigEnvOption(name="monitor_flags", multiple=True),
# Library # Library
ConfigEnvOption( ConfigEnvOption(name="lib_deps",
name="lib_deps", oldnames=["lib_use", "lib_force", "lib_install"],
oldnames=["lib_use", "lib_force", "lib_install"], multiple=True),
multiple=True),
ConfigEnvOption(name="lib_ignore", multiple=True), ConfigEnvOption(name="lib_ignore", multiple=True),
ConfigEnvOption( ConfigEnvOption(name="lib_extra_dirs",
name="lib_extra_dirs", multiple=True,
multiple=True, sysenvvar="PLATFORMIO_LIB_EXTRA_DIRS"),
sysenvvar="PLATFORMIO_LIB_EXTRA_DIRS"),
ConfigEnvOption(name="lib_ldf_mode"), ConfigEnvOption(name="lib_ldf_mode"),
ConfigEnvOption(name="lib_compat_mode"), ConfigEnvOption(name="lib_compat_mode"),
ConfigEnvOption(name="lib_archive", type=bool), ConfigEnvOption(name="lib_archive", type=bool),
@ -189,10 +175,9 @@ ProjectOptions = OrderedDict([
ConfigEnvOption(name="debug_svd_path"), ConfigEnvOption(name="debug_svd_path"),
# Other # Other
ConfigEnvOption( ConfigEnvOption(name="extra_scripts",
name="extra_scripts", oldnames=["extra_script"],
oldnames=["extra_script"], multiple=True,
multiple=True, sysenvvar="PLATFORMIO_EXTRA_SCRIPTS")
sysenvvar="PLATFORMIO_EXTRA_SCRIPTS")
] ]
]) ])

View File

@ -338,11 +338,10 @@ def on_exception(e):
def _cleanup_description(text): def _cleanup_description(text):
text = text.replace("Traceback (most recent call last):", "") text = text.replace("Traceback (most recent call last):", "")
text = re.sub( text = re.sub(r'File "([^"]+)"',
r'File "([^"]+)"', lambda m: join(*m.group(1).split(sep)[-2:]),
lambda m: join(*m.group(1).split(sep)[-2:]), text,
text, flags=re.M)
flags=re.M)
text = re.sub(r"\s+", " ", text, flags=re.M) text = re.sub(r"\s+", " ", text, flags=re.M)
return text.strip() return text.strip()

View File

@ -74,9 +74,8 @@ class ZIPArchive(ArchiveBase):
@staticmethod @staticmethod
def preserve_mtime(item, dest_dir): def preserve_mtime(item, dest_dir):
util.change_filemtime( util.change_filemtime(join(dest_dir, item.filename),
join(dest_dir, item.filename), mktime(tuple(item.date_time) + tuple([0, 0, 0])))
mktime(tuple(item.date_time) + tuple([0, 0, 0])))
def get_items(self): def get_items(self):
return self._afo.infolist() return self._afo.infolist()

View File

@ -176,8 +176,8 @@ def get_logical_devices():
if WINDOWS: if WINDOWS:
try: try:
result = exec_command( result = exec_command(
["wmic", "logicaldisk", "get", "name,VolumeName"]).get( ["wmic", "logicaldisk", "get",
"out", "") "name,VolumeName"]).get("out", "")
devicenamere = re.compile(r"^([A-Z]{1}\:)\s*(\S+)?") devicenamere = re.compile(r"^([A-Z]{1}\:)\s*(\S+)?")
for line in result.split("\n"): for line in result.split("\n"):
match = devicenamere.match(line.strip()) match = devicenamere.match(line.strip())
@ -321,20 +321,18 @@ def _get_api_result(
try: try:
if data: if data:
r = _api_request_session().post( r = _api_request_session().post(url,
url, params=params,
params=params, data=data,
data=data, headers=headers,
headers=headers, auth=auth,
auth=auth, verify=verify_ssl)
verify=verify_ssl)
else: else:
r = _api_request_session().get( r = _api_request_session().get(url,
url, params=params,
params=params, headers=headers,
headers=headers, auth=auth,
auth=auth, verify=verify_ssl)
verify=verify_ssl)
result = r.json() result = r.json()
r.raise_for_status() r.raise_for_status()
return r.text return r.text
@ -345,8 +343,8 @@ def _get_api_result(
raise exception.APIRequestError(result['errors'][0]['title']) raise exception.APIRequestError(result['errors'][0]['title'])
raise exception.APIRequestError(e) raise exception.APIRequestError(e)
except ValueError: except ValueError:
raise exception.APIRequestError( raise exception.APIRequestError("Invalid response: %s" %
"Invalid response: %s" % r.text.encode("utf-8")) r.text.encode("utf-8"))
finally: finally:
if r: if r:
r.close() r.close()
@ -403,11 +401,12 @@ def _internet_on():
for ip in PING_INTERNET_IPS: for ip in PING_INTERNET_IPS:
try: try:
if os.getenv("HTTP_PROXY", os.getenv("HTTPS_PROXY")): if os.getenv("HTTP_PROXY", os.getenv("HTTPS_PROXY")):
requests.get( requests.get("http://%s" % ip,
"http://%s" % ip, allow_redirects=False, timeout=timeout) allow_redirects=False,
timeout=timeout)
else: else:
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((ip, socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(
80)) (ip, 80))
return True return True
except: # pylint: disable=bare-except except: # pylint: disable=bare-except
pass pass
@ -524,9 +523,9 @@ def rmtree_(path):
os.chmod(name, stat.S_IWRITE) os.chmod(name, stat.S_IWRITE)
os.remove(name) os.remove(name)
except Exception as e: # pylint: disable=broad-except except Exception as e: # pylint: disable=broad-except
click.secho( click.secho("%s \nPlease manually remove the file `%s`" %
"%s \nPlease manually remove the file `%s`" % (str(e), name), (str(e), name),
fg="red", fg="red",
err=True) err=True)
return rmtree(path, onerror=_onerror) return rmtree(path, onerror=_onerror)

View File

@ -42,10 +42,11 @@ class VCSClientFactory(object):
if "#" in remote_url: if "#" in remote_url:
remote_url, tag = remote_url.rsplit("#", 1) remote_url, tag = remote_url.rsplit("#", 1)
if not type_: if not type_:
raise PlatformioException( raise PlatformioException("VCS: Unknown repository type %s" %
"VCS: Unknown repository type %s" % remote_url) remote_url)
obj = getattr(modules[__name__], "%sClient" % type_.title())( obj = getattr(modules[__name__],
src_dir, remote_url, tag, silent) "%sClient" % type_.title())(src_dir, remote_url, tag,
silent)
assert isinstance(obj, VCSClientBase) assert isinstance(obj, VCSClientBase)
return obj return obj
@ -102,8 +103,8 @@ class VCSClientBase(object):
check_call(args, **kwargs) check_call(args, **kwargs)
return True return True
except CalledProcessError as e: except CalledProcessError as e:
raise PlatformioException( raise PlatformioException("VCS: Could not process command %s" %
"VCS: Could not process command %s" % e.cmd) e.cmd)
def get_cmd_output(self, args, **kwargs): def get_cmd_output(self, args, **kwargs):
args = [self.command] + args args = [self.command] + args