Python style formatting

This commit is contained in:
Ivan Kravets
2016-10-31 20:05:34 +02:00
parent 653f8b87ec
commit a251470ebd
20 changed files with 141 additions and 108 deletions

View File

@ -264,8 +264,10 @@ def set_session_var(name, value):
def is_disabled_progressbar(): def is_disabled_progressbar():
return any([get_session_var("force_option"), util.is_ci(), return any([
getenv("PLATFORMIO_DISABLE_PROGRESSBAR") == "true"]) get_session_var("force_option"), util.is_ci(),
getenv("PLATFORMIO_DISABLE_PROGRESSBAR") == "true"
])
def get_cid(): def get_cid():
@ -282,7 +284,7 @@ def get_cid():
except: # pylint: disable=bare-except except: # pylint: disable=bare-except
pass pass
cid = str( cid = str(
uuid.UUID(bytes=hashlib.md5(str(_uid if _uid else uuid.getnode())) uuid.UUID(bytes=hashlib.md5(
.digest())) str(_uid if _uid else uuid.getnode())).digest()))
set_state_item("cid", cid) set_state_item("cid", cid)
return cid return cid

View File

@ -67,9 +67,8 @@ commonvars.AddVariables(
DEFAULT_ENV_OPTIONS = dict( DEFAULT_ENV_OPTIONS = dict(
tools=[ tools=[
"ar", "as", "gcc", "g++", "gnulink", "ar", "as", "gcc", "g++", "gnulink", "platformio", "pioplatform",
"platformio", "pioplatform", "piowinhooks", "piowinhooks", "piolib", "piotest", "pioupload", "piomisc"
"piolib", "piotest", "pioupload", "piomisc"
], # yapf: disable ], # yapf: disable
toolpath=[join(util.get_source_dir(), "builder", "tools")], toolpath=[join(util.get_source_dir(), "builder", "tools")],
variables=commonvars, variables=commonvars,

View File

@ -51,8 +51,10 @@ class LibBuilderFactory(object):
@staticmethod @staticmethod
def get_used_frameworks(env, path): def get_used_frameworks(env, path):
if any([isfile(join(path, fname)) if any([
for fname in ("library.properties", "keywords.txt")]): isfile(join(path, fname))
for fname in ("library.properties", "keywords.txt")
]):
return ["arduino"] return ["arduino"]
if isfile(join(path, "module.json")): if isfile(join(path, "module.json")):
@ -71,6 +73,7 @@ class LibBuilderFactory(object):
return ["mbed"] return ["mbed"]
return [] return []
# pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=too-many-instance-attributes, too-many-public-methods
@ -200,10 +203,8 @@ class LibBuilderBase(object):
if self.extra_script: if self.extra_script:
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
})
def _process_dependencies(self, lib_builders): def _process_dependencies(self, lib_builders):
if not self.dependencies: if not self.dependencies:

View File

@ -19,12 +19,8 @@ from os.path import join, sep
def ProcessTest(env): def ProcessTest(env):
env.Append( env.Append(
CPPDEFINES=[ CPPDEFINES=["UNIT_TEST", "UNITY_INCLUDE_CONFIG_H"],
"UNIT_TEST", "UNITY_INCLUDE_CONFIG_H" CPPPATH=[join("$BUILD_DIR", "UnityTestLib")])
],
CPPPATH=[
join("$BUILD_DIR", "UnityTestLib")
])
unitylib = env.BuildLibrary( unitylib = env.BuildLibrary(
join("$BUILD_DIR", "UnityTestLib"), join("$BUILD_DIR", "UnityTestLib"),
env.PioPlatform().get_package_dir("tool-unity")) env.PioPlatform().get_package_dir("tool-unity"))

View File

@ -146,8 +146,8 @@ def UploadToDisk(_, target, source, env): # pylint: disable=W0613,W0621
fpath = join(env.subst("$BUILD_DIR"), "%s.%s" % (progname, ext)) fpath = join(env.subst("$BUILD_DIR"), "%s.%s" % (progname, ext))
if not isfile(fpath): if not isfile(fpath):
continue continue
copyfile(fpath, join( copyfile(fpath,
env.subst("$UPLOAD_PORT"), "%s.%s" % (progname, ext))) join(env.subst("$UPLOAD_PORT"), "%s.%s" % (progname, ext)))
print "Firmware has been successfully uploaded.\n"\ print "Firmware has been successfully uploaded.\n"\
"(Some boards may require manual hard reset)" "(Some boards may require manual hard reset)"
@ -161,8 +161,10 @@ def CheckUploadSize(_, target, source, env): # pylint: disable=W0613,W0621
sysenv = environ.copy() sysenv = environ.copy()
sysenv['PATH'] = str(env['ENV']['PATH']) sysenv['PATH'] = str(env['ENV']['PATH'])
cmd = [env.subst("$SIZETOOL"), "-B", cmd = [
str(source[0] if isinstance(target[0], Alias) else target[0])] env.subst("$SIZETOOL"), "-B",
str(source[0] if isinstance(target[0], Alias) else target[0])
]
result = util.exec_command(cmd, env=sysenv) result = util.exec_command(cmd, env=sysenv)
if result['returncode'] != 0: if result['returncode'] != 0:
return return

View File

@ -35,8 +35,9 @@ SRC_FILTER_DEFAULT = ["+<*>", "-<.git%s>" % sep, "-<svn%s>" % sep]
def BuildProgram(env): def BuildProgram(env):
def _append_pio_macros(): def _append_pio_macros():
env.AppendUnique(CPPDEFINES=["PLATFORMIO={0:02d}{1:02d}{2:02d}".format( env.AppendUnique(CPPDEFINES=[
*pioversion_to_intstr())]) "PLATFORMIO={0:02d}{1:02d}{2:02d}".format(*pioversion_to_intstr())
])
_append_pio_macros() _append_pio_macros()
@ -130,8 +131,10 @@ def ProcessFlags(env, flags):
# Cancel any previous definition of name, either built in or # Cancel any previous definition of name, either built in or
# provided with a -D option // Issue #191 # provided with a -D option // Issue #191
undefines = [u for u in env.get("CCFLAGS", []) undefines = [
if isinstance(u, basestring) and u.startswith("-U")] u for u in env.get("CCFLAGS", [])
if isinstance(u, basestring) and u.startswith("-U")
]
if undefines: if undefines:
for undef in undefines: for undef in undefines:
env['CCFLAGS'].remove(undef) env['CCFLAGS'].remove(undef)

View File

@ -73,16 +73,9 @@ def validate_path(ctx, param, value): # pylint: disable=unused-argument
@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
def cli(ctx, # pylint: disable=R0913 def cli( # pylint: disable=too-many-arguments
src, ctx, src, lib, exclude, board, build_dir, keep_build_dir, project_conf,
lib, project_option, verbose):
exclude,
board,
build_dir,
keep_build_dir,
project_conf,
project_option,
verbose):
if not src and getenv("PLATFORMIO_CI_SRC"): if not src and getenv("PLATFORMIO_CI_SRC"):
src = validate_path(ctx, None, getenv("PLATFORMIO_CI_SRC").split(":")) src = validate_path(ctx, None, getenv("PLATFORMIO_CI_SRC").split(":"))

View File

@ -58,7 +58,8 @@ def validate_boards(ctx, param, value): # pylint: disable=W0613
@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.pass_context @click.pass_context
def cli(ctx, # pylint: disable=R0913 def cli(
ctx, # pylint: disable=R0913
project_dir, project_dir,
board, board,
ide, ide,
@ -292,10 +293,11 @@ def fill_project_envs(ctx, project_dir, board_ids, project_option, env_prefix,
config = util.load_project_config(project_dir) config = util.load_project_config(project_dir)
for section in config.sections(): for section in config.sections():
if not all([section.startswith("env:"), cond = [
config.has_option(section, "board")]): section.startswith("env:"), config.has_option(section, "board")
continue ]
used_boards.append(config.get(section, "board")) if all(cond):
used_boards.append(config.get(section, "board"))
pm = PlatformManager() pm = PlatformManager()
for id_ in board_ids: for id_ in board_ids:

View File

@ -113,6 +113,7 @@ def lib_update(lm, libraries, only_check):
for library in libraries: for library in libraries:
lm.update(library, only_check=only_check) lm.update(library, only_check=only_check)
####### #######
LIBLIST_TPL = ("[{id:^14}] {name:<25} {compatibility:<30} " LIBLIST_TPL = ("[{id:^14}] {name:<25} {compatibility:<30} "

View File

@ -87,9 +87,10 @@ def cli(ctx, environment, target, upload_port, project_dir, silent, verbose,
continue continue
envname = section[4:] envname = section[4:]
skipenv = any([environment and envname not in environment, skipenv = any([
not environment and env_default and environment and envname not in environment, not environment and
envname not in env_default]) env_default and envname not in env_default
])
if skipenv: if skipenv:
results[envname] = None results[envname] = None
continue continue
@ -133,14 +134,15 @@ class EnvironmentProcessor(object):
RENAMED_PLATFORMS = {"espressif": "espressif8266"} RENAMED_PLATFORMS = {"espressif": "espressif8266"}
def __init__(self, # pylint: disable=R0913 def __init__(
cmd_ctx, self, # pylint: disable=R0913
name, cmd_ctx,
options, name,
targets, options,
upload_port, targets,
silent, upload_port,
verbose): silent,
verbose):
self.cmd_ctx = cmd_ctx self.cmd_ctx = cmd_ctx
self.name = name self.name = name
self.options = options self.options = options

View File

@ -33,9 +33,11 @@ def cli():
click.secho("Please wait while upgrading PlatformIO ...", fg="yellow") click.secho("Please wait while upgrading PlatformIO ...", fg="yellow")
to_develop = not all([c.isdigit() for c in latest if c != "."]) to_develop = not all([c.isdigit() for c in latest if c != "."])
cmds = (["pip", "install", "--upgrade", cmds = ([
"https://github.com/platformio/platformio/archive/develop.zip" "pip", "install", "--upgrade",
if to_develop else "platformio"], ["platformio", "--version"]) "https://github.com/platformio/platformio/archive/develop.zip"
if to_develop else "platformio"
], ["platformio", "--version"])
cmd = None cmd = None
r = None r = None
@ -81,8 +83,8 @@ WARNING! Don't use `sudo` for the rest PlatformIO commands.
err=True) err=True)
raise exception.ReturnErrorCode() raise exception.ReturnErrorCode()
else: else:
raise exception.UpgradeError("\n".join([str(cmd), r['out'], r[ raise exception.UpgradeError("\n".join(
'err']])) [str(cmd), r['out'], r['err']]))
def get_latest_version(): def get_latest_version():

View File

@ -38,8 +38,8 @@ class ProjectGenerator(object):
@staticmethod @staticmethod
def get_supported_ides(): def get_supported_ides():
tpls_dir = join(util.get_source_dir(), "ide", "tpls") tpls_dir = join(util.get_source_dir(), "ide", "tpls")
return sorted([d for d in os.listdir(tpls_dir) return sorted(
if isdir(join(tpls_dir, d))]) [d for d in os.listdir(tpls_dir) if isdir(join(tpls_dir, d))])
@util.memoized @util.memoized
def get_project_env(self): def get_project_env(self):
@ -69,8 +69,8 @@ class ProjectGenerator(object):
result = util.exec_command(cmd) result = util.exec_command(cmd)
if result['returncode'] != 0 or '"includes":' not in result['out']: if result['returncode'] != 0 or '"includes":' not in result['out']:
raise exception.PlatformioException("\n".join([result['out'], raise exception.PlatformioException("\n".join(
result['err']])) [result['out'], result['err']]))
output = result['out'] output = result['out']
start_index = output.index('{"') start_index = output.index('{"')

View File

@ -142,8 +142,9 @@ class Upgrader(object):
@staticmethod @staticmethod
def _upgrade_to_3_0_0b11(ctx): def _upgrade_to_3_0_0b11(ctx):
current_platforms = [m['name'] current_platforms = [
for m in PlatformManager().get_installed()] m['name'] for m in PlatformManager().get_installed()
]
if "espressif" not in current_platforms: if "espressif" not in current_platforms:
return return
ctx.invoke(cmd_platform_install, platforms=["espressif8266"]) ctx.invoke(cmd_platform_install, platforms=["espressif8266"])

View File

@ -120,8 +120,9 @@ class LibraryManager(BasePkgManager):
if item[k] == "*": if item[k] == "*":
del item[k] del item[k]
elif isinstance(item[k], basestring): elif isinstance(item[k], basestring):
item[k] = [i.strip() for i in item[k].split(",") item[k] = [
if i.strip()] i.strip() for i in item[k].split(",") if i.strip()
]
return items return items
@staticmethod @staticmethod

View File

@ -164,8 +164,9 @@ class PkgInstallerMixin(object):
if not pkgdata: if not pkgdata:
continue continue
try: try:
pkg_dir = self._install_from_url( pkg_dir = self._install_from_url(name, pkgdata['url'],
name, pkgdata['url'], requirements, pkgdata.get("sha1")) requirements,
pkgdata.get("sha1"))
break break
except Exception as e: # pylint: disable=broad-except except Exception as e: # pylint: disable=broad-except
click.secho("Warning! Package Mirror: %s" % e, fg="yellow") click.secho("Warning! Package Mirror: %s" % e, fg="yellow")
@ -240,8 +241,9 @@ class PkgInstallerMixin(object):
curmanifest['version'], partial=True) curmanifest['version'], partial=True)
# if current package version < new package, backup it # if current package version < new package, backup it
if tmpmanver > curmanver: if tmpmanver > curmanver:
os.rename(pkg_dir, join(self.package_dir, "%s@%s" % ( os.rename(pkg_dir,
name, curmanifest['version']))) join(self.package_dir, "%s@%s" %
(name, curmanifest['version'])))
elif tmpmanver < curmanver: elif tmpmanver < curmanver:
pkg_dir = join(self.package_dir, "%s@%s" % pkg_dir = join(self.package_dir, "%s@%s" %
(name, tmpmanifest['version'])) (name, tmpmanifest['version']))
@ -492,10 +494,11 @@ class BasePkgManager(PkgRepoMixin, PkgInstallerMixin):
label=manifest['name']) label=manifest['name'])
return True return True
def update(self, # pylint: disable=too-many-return-statements def update( # pylint: disable=too-many-return-statements
name, self,
requirements=None, name,
only_check=False): requirements=None,
only_check=False):
name, requirements, url = self.parse_pkg_name(name, requirements) name, requirements, url = self.parse_pkg_name(name, requirements)
package_dir = self.get_package_dir(name, None, url) package_dir = self.get_package_dir(name, None, url)
if not package_dir: if not package_dir:

View File

@ -42,13 +42,13 @@ class PlatformManager(BasePkgManager):
def manifest_name(self): def manifest_name(self):
return "platform.json" return "platform.json"
def install(self, # pylint: disable=too-many-arguments def install(self,
name, name,
requirements=None, requirements=None,
with_packages=None, with_packages=None,
without_packages=None, without_packages=None,
skip_default_package=False, skip_default_package=False,
**_): **_): # pylint: disable=too-many-arguments
platform_dir = BasePkgManager.install(self, name, requirements) platform_dir = BasePkgManager.install(self, name, requirements)
p = PlatformFactory.newPlatform(self.get_manifest_path(platform_dir)) p = PlatformFactory.newPlatform(self.get_manifest_path(platform_dir))
p.install_packages(with_packages, without_packages, p.install_packages(with_packages, without_packages,
@ -66,8 +66,12 @@ class PlatformManager(BasePkgManager):
self.cleanup_packages(p.packages.keys()) self.cleanup_packages(p.packages.keys())
return True return True
def update(self, # pylint: disable=arguments-differ def update( # pylint: disable=arguments-differ
name, requirements=None, only_packages=False, only_check=False): self,
name,
requirements=None,
only_packages=False,
only_check=False):
name, requirements, _ = self.parse_pkg_name(name, requirements) name, requirements, _ = self.parse_pkg_name(name, requirements)
if not only_packages: if not only_packages:
BasePkgManager.update(self, name, requirements, only_check) BasePkgManager.update(self, name, requirements, only_check)

View File

@ -20,21 +20,29 @@ from platform import system
from platformio import app, exception, util from platformio import app, exception, util
from platformio.managers.package import PackageManager from platformio.managers.package import PackageManager
PACKAGE_DEPS = {"pysite": {"name": "pysite-pioplus", PACKAGE_DEPS = {
"requirements": ">=0.1.0"}, "pysite": {
"tool": {"name": "tool-pioplus", "name": "pysite-pioplus",
"requirements": ">=0.3.0"}} "requirements": ">=0.1.0"
},
"tool": {
"name": "tool-pioplus",
"requirements": ">=0.3.0"
}
}
class PioPlusPackageManager(PackageManager): class PioPlusPackageManager(PackageManager):
def __init__(self): def __init__(self):
PackageManager.__init__(self, join(util.get_home_dir(), "packages"), [ PackageManager.__init__(
"https://dl.bintray.com/platformio/dl-packages/manifest.json", self,
"https://sourceforge.net/projects/platformio-storage/files/" join(util.get_home_dir(), "packages"), [
"packages/manifest.json/download", "https://dl.bintray.com/platformio/dl-packages/manifest.json",
"https://dl.platformio.org/packages/manifest.json" "https://sourceforge.net/projects/platformio-storage/files/"
]) "packages/manifest.json/download",
"https://dl.platformio.org/packages/manifest.json"
])
def pioplus_install(): def pioplus_install():

View File

@ -227,12 +227,22 @@ def measure_ci():
event = {"category": "CI", "action": "NoName", "label": None} event = {"category": "CI", "action": "NoName", "label": None}
envmap = { envmap = {
"APPVEYOR": {"label": getenv("APPVEYOR_REPO_NAME")}, "APPVEYOR": {
"CIRCLECI": {"label": "%s/%s" % (getenv("CIRCLE_PROJECT_USERNAME"), "label": getenv("APPVEYOR_REPO_NAME")
getenv("CIRCLE_PROJECT_REPONAME"))}, },
"TRAVIS": {"label": getenv("TRAVIS_REPO_SLUG")}, "CIRCLECI": {
"SHIPPABLE": {"label": getenv("REPO_NAME")}, "label": "%s/%s" % (getenv("CIRCLE_PROJECT_USERNAME"),
"DRONE": {"label": getenv("DRONE_REPO_SLUG")} getenv("CIRCLE_PROJECT_REPONAME"))
},
"TRAVIS": {
"label": getenv("TRAVIS_REPO_SLUG")
},
"SHIPPABLE": {
"label": getenv("REPO_NAME")
},
"DRONE": {
"label": getenv("DRONE_REPO_SLUG")
}
} }
for key, value in envmap.iteritems(): for key, value in envmap.iteritems():
@ -263,10 +273,11 @@ def on_event(category, action, label=None, value=None, screen_name=None):
def on_exception(e): def on_exception(e):
skip = any( skip = any([
[isinstance(e, cls) isinstance(e, cls)
for cls in (IOError, exception.AbortedByUser, for cls in (IOError, exception.AbortedByUser,
exception.NotGlobalLibDir, exception.InternetIsOffline)]) exception.NotGlobalLibDir, exception.InternetIsOffline)
])
if skip: if skip:
return return
is_crash = any([ is_crash = any([

View File

@ -254,13 +254,13 @@ def get_projectsrc_dir():
def get_projecttest_dir(): def get_projecttest_dir():
return _get_projconf_option_dir("test_dir", join(get_project_dir(), return _get_projconf_option_dir("test_dir",
"test")) join(get_project_dir(), "test"))
def get_projectboards_dir(): def get_projectboards_dir():
return _get_projconf_option_dir("boards_dir", join(get_project_dir(), return _get_projconf_option_dir("boards_dir",
"boards")) join(get_project_dir(), "boards"))
def get_projectpioenvs_dir(force=False): def get_projectpioenvs_dir(force=False):
@ -417,10 +417,11 @@ def _api_request_session():
return requests.Session() return requests.Session()
def _get_api_result(url, # pylint: disable=too-many-branches def _get_api_result(
params=None, url, # pylint: disable=too-many-branches
data=None, params=None,
auth=None): data=None,
auth=None):
from platformio.app import get_setting from platformio.app import get_setting
result = None result = None

View File

@ -177,8 +177,9 @@ class SvnClient(VCSClientBase):
return self.run_cmd(args) return self.run_cmd(args)
def get_current_revision(self): def get_current_revision(self):
output = self.get_cmd_output(["info", "--non-interactive", output = self.get_cmd_output([
"--trust-server-cert", "-r", "HEAD"]) "info", "--non-interactive", "--trust-server-cert", "-r", "HEAD"
])
for line in output.split("\n"): for line in output.split("\n"):
line = line.strip() line = line.strip()
if line.startswith("Revision:"): if line.startswith("Revision:"):