Beispiel #1
0
def platform_frameworks(query, json_output):
    regclient = PlatformPackageManager().get_registry_client_instance()
    frameworks = []
    for framework in regclient.fetch_json_data("get",
                                               "/v2/frameworks",
                                               cache_valid="1d"):
        if query == "all":
            query = ""
        search_data = dump_json_to_unicode(framework)
        if query and query.lower() not in search_data.lower():
            continue
        framework[
            "homepage"] = "https://platformio.org/frameworks/" + framework[
                "name"]
        framework["platforms"] = [
            platform["name"] for platform in _get_registry_platforms()
            if framework["name"] in platform["frameworks"]
        ]
        frameworks.append(framework)

    frameworks = sorted(frameworks, key=lambda manifest: manifest["name"])
    if json_output:
        click.echo(dump_json_to_unicode(frameworks))
    else:
        _print_platforms(frameworks)
Beispiel #2
0
def lib_stats(json_output):
    result = util.get_api_result("/lib/stats", cache_valid="1h")

    if json_output:
        return click.echo(dump_json_to_unicode(result))

    for key in ("updated", "added"):
        tabular_data = [(
            click.style(item["name"], fg="cyan"),
            time.strftime("%c", util.parse_date(item["date"])),
            "https://platformio.org/lib/show/%s/%s" %
            (item["id"], quote(item["name"])),
        ) for item in result.get(key, [])]
        table = tabulate(
            tabular_data,
            headers=[
                click.style("RECENTLY " + key.upper(), bold=True), "Date",
                "URL"
            ],
        )
        click.echo(table)
        click.echo()

    for key in ("lastkeywords", "topkeywords"):
        tabular_data = [(
            click.style(name, fg="cyan"),
            "https://platformio.org/lib/search?query=" +
            quote("keyword:%s" % name),
        ) for name in result.get(key, [])]
        table = tabulate(
            tabular_data,
            headers=[
                click.style(
                    ("RECENT" if key == "lastkeywords" else "POPULAR") +
                    " KEYWORDS",
                    bold=True,
                ),
                "URL",
            ],
        )
        click.echo(table)
        click.echo()

    for key, title in (("dlday", "Today"), ("dlweek", "Week"), ("dlmonth",
                                                                "Month")):
        tabular_data = [(
            click.style(item["name"], fg="cyan"),
            "https://platformio.org/lib/show/%s/%s" %
            (item["id"], quote(item["name"])),
        ) for item in result.get(key, [])]
        table = tabulate(
            tabular_data,
            headers=[
                click.style("FEATURED: " + title.upper(), bold=True), "URL"
            ],
        )
        click.echo(table)
        click.echo()

    return True
Beispiel #3
0
def lib_search(query, json_output, page, noninteractive, **filters):
    if not query:
        query = []
    if not isinstance(query, list):
        query = list(query)

    for key, values in filters.items():
        for value in values:
            query.append('%s:"%s"' % (key, value))

    result = util.get_api_result("/v2/lib/search",
                                 dict(query=" ".join(query), page=page),
                                 cache_valid="1d")

    if json_output:
        click.echo(dump_json_to_unicode(result))
        return

    if result['total'] == 0:
        click.secho(
            "Nothing has been found by your request\n"
            "Try a less-specific search or use truncation (or wildcard) "
            "operator",
            fg="yellow",
            nl=False)
        click.secho(" *", fg="green")
        click.secho("For example: DS*, PCA*, DHT* and etc.\n", fg="yellow")
        click.echo("For more examples and advanced search syntax, "
                   "please use documentation:")
        click.secho(
            "https://docs.platformio.org/page/userguide/lib/cmd_search.html\n",
            fg="cyan")
        return

    click.secho("Found %d libraries:\n" % result['total'],
                fg="green" if result['total'] else "yellow")

    while True:
        for item in result['items']:
            print_lib_item(item)

        if (int(result['page']) * int(result['perpage']) >= int(
                result['total'])):
            break

        if noninteractive:
            click.echo()
            click.secho("Loading next %d libraries... Press Ctrl+C to stop!" %
                        result['perpage'],
                        fg="yellow")
            click.echo()
            time.sleep(5)
        elif not click.confirm("Show next libraries?"):
            break
        result = util.get_api_result("/v2/lib/search", {
            "query": " ".join(query),
            "page": int(result['page']) + 1
        },
                                     cache_valid="1d")
Beispiel #4
0
def platform_show(platform, json_output):  # pylint: disable=too-many-branches
    data = _get_platform_data(platform)
    if not data:
        raise UnknownPlatform(platform)
    if json_output:
        return click.echo(dump_json_to_unicode(data))

    dep = "{ownername}/{name}".format(
        **data) if "ownername" in data else data["name"]
    click.echo("{dep} ~ {title}".format(dep=click.style(dep, fg="cyan"),
                                        title=data["title"]))
    click.echo("=" * (3 + len(dep + data["title"])))
    click.echo(data["description"])
    click.echo()
    if "version" in data:
        click.echo("Version: %s" % data["version"])
    if data["homepage"]:
        click.echo("Home: %s" % data["homepage"])
    if data["repository"]:
        click.echo("Repository: %s" % data["repository"])
    if data["url"]:
        click.echo("Vendor: %s" % data["url"])
    if data["license"]:
        click.echo("License: %s" % data["license"])
    if data["frameworks"]:
        click.echo("Frameworks: %s" % ", ".join(data["frameworks"]))

    if not data["packages"]:
        return None

    if not isinstance(data["packages"][0], dict):
        click.echo("Packages: %s" % ", ".join(data["packages"]))
    else:
        click.echo()
        click.secho("Packages", bold=True)
        click.echo("--------")
        for item in data["packages"]:
            click.echo()
            click.echo("Package %s" % click.style(item["name"], fg="yellow"))
            click.echo("-" * (8 + len(item["name"])))
            if item["type"]:
                click.echo("Type: %s" % item["type"])
            click.echo("Requirements: %s" % item["requirements"])
            click.echo("Installed: %s" %
                       ("Yes" if item.get("version") else "No (optional)"))
            if "version" in item:
                click.echo("Version: %s" % item["version"])
            if "originalVersion" in item:
                click.echo("Original version: %s" % item["originalVersion"])
            if "description" in item:
                click.echo("Description: %s" % item["description"])

    if data["boards"]:
        click.echo()
        click.secho("Boards", bold=True)
        click.echo("------")
        print_boards(data["boards"])

    return True
Beispiel #5
0
 def sendJSONResponse(self, response):
     # click.echo("< %s" % response)
     if "error" in response:
         click.secho("Error: %s" % response["error"], fg="red", err=True)
     response = dump_json_to_unicode(response)
     if not PY2 and not is_bytes(response):
         response = response.encode("utf-8")
     self.sendMessage(response)
Beispiel #6
0
 def __exit__(self, type_, value, traceback):
     if self.modified:
         try:
             with open(self.path, "w") as fp:
                 fp.write(dump_json_to_unicode(self._storage))
         except IOError:
             raise exception.HomeDirPermissionsError(get_project_core_dir())
     self._unlock_state_file()
Beispiel #7
0
def platform_search(query, json_output):
    platforms = []
    for platform in _get_registry_platforms():
        if query == "all":
            query = ""
        search_data = dump_json_to_unicode(platform)
        if query and query.lower() not in search_data.lower():
            continue
        platforms.append(
            _get_registry_platform_data(platform["name"],
                                        with_boards=False,
                                        expose_packages=False))

    if json_output:
        click.echo(dump_json_to_unicode(platforms))
    else:
        _print_platforms(platforms)
Beispiel #8
0
def lib_update(  # pylint: disable=too-many-arguments
    ctx, libraries, only_check, dry_run, silent, json_output
):
    storage_dirs = ctx.meta[CTX_META_STORAGE_DIRS_KEY]
    only_check = dry_run or only_check
    json_result = {}
    for storage_dir in storage_dirs:
        if not json_output:
            print_storage_header(storage_dirs, storage_dir)
        lib_deps = ctx.meta.get(CTX_META_STORAGE_LIBDEPS_KEY, {}).get(storage_dir, [])
        lm = LibraryPackageManager(storage_dir)
        _libraries = libraries or lib_deps or lm.get_installed()

        if only_check and json_output:
            result = []
            for library in _libraries:
                spec = None
                pkg = None
                if isinstance(library, PackageItem):
                    pkg = library
                else:
                    spec = PackageSpec(library)
                    pkg = lm.get_package(spec)
                if not pkg:
                    continue
                outdated = lm.outdated(pkg, spec)
                if not outdated.is_outdated(allow_incompatible=True):
                    continue
                manifest = lm.legacy_load_manifest(pkg)
                manifest["versionWanted"] = (
                    str(outdated.wanted) if outdated.wanted else None
                )
                manifest["versionLatest"] = (
                    str(outdated.latest) if outdated.latest else None
                )
                result.append(manifest)
            json_result[storage_dir] = result
        else:
            for library in _libraries:
                to_spec = (
                    None if isinstance(library, PackageItem) else PackageSpec(library)
                )
                try:
                    lm.update(
                        library, to_spec=to_spec, only_check=only_check, silent=silent
                    )
                except UnknownPackageError as e:
                    if library not in lib_deps:
                        raise e

    if json_output:
        return click.echo(
            dump_json_to_unicode(
                json_result[storage_dirs[0]] if len(storage_dirs) == 1 else json_result
            )
        )

    return True
Beispiel #9
0
def platform_show(platform, json_output):  # pylint: disable=too-many-branches
    data = _get_platform_data(platform)
    if not data:
        raise exception.UnknownPlatform(platform)
    if json_output:
        return click.echo(dump_json_to_unicode(data))

    click.echo("{name} ~ {title}".format(name=click.style(data['name'],
                                                          fg="cyan"),
                                         title=data['title']))
    click.echo("=" * (3 + len(data['name'] + data['title'])))
    click.echo(data['description'])
    click.echo()
    if "version" in data:
        click.echo("Version: %s" % data['version'])
    if data['homepage']:
        click.echo("Home: %s" % data['homepage'])
    if data['repository']:
        click.echo("Repository: %s" % data['repository'])
    if data['url']:
        click.echo("Vendor: %s" % data['url'])
    if data['license']:
        click.echo("License: %s" % data['license'])
    if data['frameworks']:
        click.echo("Frameworks: %s" % ", ".join(data['frameworks']))

    if not data['packages']:
        return None

    if not isinstance(data['packages'][0], dict):
        click.echo("Packages: %s" % ", ".join(data['packages']))
    else:
        click.echo()
        click.secho("Packages", bold=True)
        click.echo("--------")
        for item in data['packages']:
            click.echo()
            click.echo("Package %s" % click.style(item['name'], fg="yellow"))
            click.echo("-" * (8 + len(item['name'])))
            if item['type']:
                click.echo("Type: %s" % item['type'])
            click.echo("Requirements: %s" % item['requirements'])
            click.echo("Installed: %s" %
                       ("Yes" if item.get("version") else "No (optional)"))
            if "version" in item:
                click.echo("Version: %s" % item['version'])
            if "originalVersion" in item:
                click.echo("Original version: %s" % item['originalVersion'])
            if "description" in item:
                click.echo("Description: %s" % item['description'])

    if data['boards']:
        click.echo()
        click.secho("Boards", bold=True)
        click.echo("------")
        print_boards(data['boards'])

    return True
Beispiel #10
0
def _print_boards_json(query, installed=False):
    result = []
    for board in _get_boards(installed):
        if query:
            search_data = "%s %s" % (board["id"], json.dumps(board).lower())
            if query.lower() not in search_data.lower():
                continue
        result.append(board)
    click.echo(dump_json_to_unicode(result))
Beispiel #11
0
def platform_frameworks(query, json_output):
    frameworks = []
    for framework in util.get_api_result("/frameworks", cache_valid="7d"):
        if query == "all":
            query = ""
        search_data = dump_json_to_unicode(framework)
        if query and query.lower() not in search_data.lower():
            continue
        framework['homepage'] = ("https://platformio.org/frameworks/" +
                                 framework['name'])
        framework['platforms'] = [
            platform['name'] for platform in _get_registry_platforms()
            if framework['name'] in platform['frameworks']
        ]
        frameworks.append(framework)

    frameworks = sorted(frameworks, key=lambda manifest: manifest['name'])
    if json_output:
        click.echo(dump_json_to_unicode(frameworks))
    else:
        _print_platforms(frameworks)
Beispiel #12
0
def platform_list(json_output):
    platforms = []
    pm = PlatformPackageManager()
    for pkg in pm.get_installed():
        platforms.append(
            _get_installed_platform_data(pkg,
                                         with_boards=False,
                                         expose_packages=False))

    platforms = sorted(platforms, key=lambda manifest: manifest["name"])
    if json_output:
        click.echo(dump_json_to_unicode(platforms))
    else:
        _print_platforms(platforms)
Beispiel #13
0
def platform_update(  # pylint: disable=too-many-locals, too-many-arguments
        platforms, only_packages, only_check, dry_run, silent, json_output):
    pm = PlatformPackageManager()
    platforms = platforms or pm.get_installed()
    only_check = dry_run or only_check

    if only_check and json_output:
        result = []
        for platform in platforms:
            spec = None
            pkg = None
            if isinstance(platform, PackageItem):
                pkg = platform
            else:
                spec = PackageSpec(platform)
                pkg = pm.get_package(spec)
            if not pkg:
                continue
            outdated = pm.outdated(pkg, spec)
            if (not outdated.is_outdated(allow_incompatible=True)
                    and not PlatformFactory.new(pkg).are_outdated_packages()):
                continue
            data = _get_installed_platform_data(pkg,
                                                with_boards=False,
                                                expose_packages=False)
            if outdated.is_outdated(allow_incompatible=True):
                data["versionLatest"] = (str(outdated.latest)
                                         if outdated.latest else None)
            result.append(data)
        return click.echo(dump_json_to_unicode(result))

    # cleanup cached board and platform lists
    cleanup_content_cache("http")

    for platform in platforms:
        click.echo("Platform %s" % click.style(
            platform.metadata.name
            if isinstance(platform, PackageItem) else platform,
            fg="cyan",
        ))
        click.echo("--------")
        pm.update(platform,
                  only_packages=only_packages,
                  only_check=only_check,
                  silent=silent)
        click.echo()

    return True
Beispiel #14
0
def lib_builtin(storage, json_output):
    items = get_builtin_libs(storage)
    if json_output:
        return click.echo(dump_json_to_unicode(items))

    for storage_ in items:
        if not storage_['items']:
            continue
        click.secho(storage_['name'], fg="green")
        click.echo("*" * len(storage_['name']))
        click.echo()

        for item in sorted(storage_['items'], key=lambda i: i['name']):
            print_lib_item(item)

    return True
Beispiel #15
0
def platform_update(  # pylint: disable=too-many-locals
        platforms, only_packages, only_check, dry_run, json_output):
    pm = PlatformManager()
    pkg_dir_to_name = {}
    if not platforms:
        platforms = []
        for manifest in pm.get_installed():
            platforms.append(manifest["__pkg_dir"])
            pkg_dir_to_name[manifest["__pkg_dir"]] = manifest.get(
                "title", manifest["name"])

    only_check = dry_run or only_check

    if only_check and json_output:
        result = []
        for platform in platforms:
            pkg_dir = platform if isdir(platform) else None
            requirements = None
            url = None
            if not pkg_dir:
                name, requirements, url = pm.parse_pkg_uri(platform)
                pkg_dir = pm.get_package_dir(name, requirements, url)
            if not pkg_dir:
                continue
            latest = pm.outdated(pkg_dir, requirements)
            if (not latest and not PlatformFactory.newPlatform(
                    pkg_dir).are_outdated_packages()):
                continue
            data = _get_installed_platform_data(pkg_dir,
                                                with_boards=False,
                                                expose_packages=False)
            if latest:
                data["versionLatest"] = latest
            result.append(data)
        return click.echo(dump_json_to_unicode(result))

    # cleanup cached board and platform lists
    app.clean_cache()
    for platform in platforms:
        click.echo(
            "Platform %s" %
            click.style(pkg_dir_to_name.get(platform, platform), fg="cyan"))
        click.echo("--------")
        pm.update(platform, only_packages=only_packages, only_check=only_check)
        click.echo()

    return True
Beispiel #16
0
def lib_update(ctx, libraries, only_check, dry_run, json_output):
    storage_dirs = ctx.meta[CTX_META_STORAGE_DIRS_KEY]
    only_check = dry_run or only_check
    json_result = {}
    for storage_dir in storage_dirs:
        if not json_output:
            print_storage_header(storage_dirs, storage_dir)
        lm = LibraryManager(storage_dir)

        _libraries = libraries
        if not _libraries:
            _libraries = [
                manifest['__pkg_dir'] for manifest in lm.get_installed()
            ]

        if only_check and json_output:
            result = []
            for library in _libraries:
                pkg_dir = library if isdir(library) else None
                requirements = None
                url = None
                if not pkg_dir:
                    name, requirements, url = lm.parse_pkg_uri(library)
                    pkg_dir = lm.get_package_dir(name, requirements, url)
                if not pkg_dir:
                    continue
                latest = lm.outdated(pkg_dir, requirements)
                if not latest:
                    continue
                manifest = lm.load_manifest(pkg_dir)
                manifest['versionLatest'] = latest
                result.append(manifest)
            json_result[storage_dir] = result
        else:
            for library in _libraries:
                lm.update(library, only_check=only_check)

    if json_output:
        return click.echo(
            dump_json_to_unicode(json_result[storage_dirs[0]]
                                 if len(storage_dirs) == 1 else json_result))

    return True
Beispiel #17
0
def lib_list(ctx, json_output):
    storage_dirs = ctx.meta[CTX_META_STORAGE_DIRS_KEY]
    json_result = {}
    for storage_dir in storage_dirs:
        if not json_output:
            print_storage_header(storage_dirs, storage_dir)
        lm = LibraryManager(storage_dir)
        items = lm.get_installed()
        if json_output:
            json_result[storage_dir] = items
        elif items:
            for item in sorted(items, key=lambda i: i['name']):
                print_lib_item(item)
        else:
            click.echo("No items found")

    if json_output:
        return click.echo(
            dump_json_to_unicode(json_result[storage_dirs[0]]
                                 if len(storage_dirs) == 1 else json_result))

    return True
Beispiel #18
0
def DumpSizeData(_, target, source, env):  # pylint: disable=unused-argument
    data = {"device": {}, "memory": {}, "version": 1}

    board = env.BoardConfig()
    if board:
        data["device"] = {
            "mcu": board.get("build.mcu", ""),
            "cpu": board.get("build.cpu", ""),
            "frequency": board.get("build.f_cpu"),
            "flash": int(board.get("upload.maximum_size", 0)),
            "ram": int(board.get("upload.maximum_ram_size", 0)),
        }
        if data["device"]["frequency"] and data["device"][
                "frequency"].endswith("L"):
            data["device"]["frequency"] = int(
                data["device"]["frequency"][0:-1])

    elf_path = env.subst("$PIOMAINPROG")

    with open(elf_path, "rb") as fp:
        elffile = ELFFile(fp)

        if not elffile.has_dwarf_info():
            sys.stderr.write("Elf file doesn't contain DWARF information")
            env.Exit(1)

        sections = _collect_sections_info(elffile)
        firmware_ram, firmware_flash = _calculate_firmware_size(sections)
        data["memory"]["total"] = {
            "ram_size": firmware_ram,
            "flash_size": firmware_flash,
            "sections": sections,
        }

        files = dict()
        for symbol in _collect_symbols_info(env, elffile, elf_path, sections):
            file_path = symbol.get("file") or "unknown"
            if not files.get(file_path, {}):
                files[file_path] = {
                    "symbols": [],
                    "ram_size": 0,
                    "flash_size": 0
                }

            symbol_size = symbol.get("size", 0)
            section = sections.get(symbol.get("section", ""), {})
            if _is_ram_section(section):
                files[file_path]["ram_size"] += symbol_size
            if _is_flash_section(section):
                files[file_path]["flash_size"] += symbol_size

            files[file_path]["symbols"].append(symbol)

        data["memory"]["files"] = list()
        for k, v in files.items():
            file_data = {"path": k}
            file_data.update(v)
            data["memory"]["files"].append(file_data)

    with open(join(env.subst("$BUILD_DIR"), "sizedata.json"), "w") as fp:
        fp.write(dump_json_to_unicode(data))
Beispiel #19
0
def lib_stats(json_output):
    result = util.get_api_result("/lib/stats", cache_valid="1h")

    if json_output:
        return click.echo(dump_json_to_unicode(result))

    printitem_tpl = "{name:<33} {url}"
    printitemdate_tpl = "{name:<33} {date:23} {url}"

    def _print_title(title):
        click.secho(title.upper(), bold=True)
        click.echo("*" * len(title))

    def _print_header(with_date=False):
        click.echo((printitemdate_tpl if with_date else printitem_tpl).format(
            name=click.style("Name", fg="cyan"),
            date="Date",
            url=click.style("Url", fg="blue")))

        terminal_width, _ = click.get_terminal_size()
        click.echo("-" * terminal_width)

    def _print_lib_item(item):
        date = str(
            time.strftime("%c", util.parse_date(item['date'])) if "date" in
            item else "")
        url = click.style("https://platformio.org/lib/show/%s/%s" %
                          (item['id'], quote(item['name'])),
                          fg="blue")
        click.echo(
            (printitemdate_tpl if "date" in item else printitem_tpl).format(
                name=click.style(item['name'], fg="cyan"), date=date, url=url))

    def _print_tag_item(name):
        click.echo(
            printitem_tpl.format(
                name=click.style(name, fg="cyan"),
                url=click.style("https://platformio.org/lib/search?query=" +
                                quote("keyword:%s" % name),
                                fg="blue")))

    for key in ("updated", "added"):
        _print_title("Recently " + key)
        _print_header(with_date=True)
        for item in result.get(key, []):
            _print_lib_item(item)
        click.echo()

    _print_title("Recent keywords")
    _print_header(with_date=False)
    for item in result.get("lastkeywords"):
        _print_tag_item(item)
    click.echo()

    _print_title("Popular keywords")
    _print_header(with_date=False)
    for item in result.get("topkeywords"):
        _print_tag_item(item)
    click.echo()

    for key, title in (("dlday", "Today"), ("dlweek", "Week"), ("dlmonth",
                                                                "Month")):
        _print_title("Featured: " + title)
        _print_header(with_date=False)
        for item in result.get(key, []):
            _print_lib_item(item)
        click.echo()

    return True
Beispiel #20
0
# Checking program size
if env.get("SIZETOOL") and "nobuild" not in COMMAND_LINE_TARGETS:
    env.Depends(["upload", "program"], "checkprogsize")
    # Replace platform's "size" target with our
    _new_targets = [t for t in DEFAULT_TARGETS if str(t) != "size"]
    Default(None)
    Default(_new_targets)
    Default("checkprogsize")

# Print configured protocols
env.AddPreAction(
    ["upload", "program"],
    env.VerboseAction(lambda source, target, env: env.PrintUploadInfo(),
                      "Configuring upload protocol..."))

AlwaysBuild(env.Alias("debug", DEFAULT_TARGETS))
AlwaysBuild(env.Alias("__test", DEFAULT_TARGETS))

##############################################################################

if "envdump" in COMMAND_LINE_TARGETS:
    print(env.Dump())
    env.Exit(0)

if "idedata" in COMMAND_LINE_TARGETS:
    Import("projenv")
    print("\n%s\n" % dump_json_to_unicode(
        env.DumpIDEData(projenv)  # pylint: disable=undefined-variable
    ))
    env.Exit(0)
Beispiel #21
0
def lib_search(query, json_output, page, noninteractive, **filters):
    regclient = LibraryPackageManager().get_registry_client_instance()
    if not query:
        query = []
    if not isinstance(query, list):
        query = list(query)

    for key, values in filters.items():
        for value in values:
            query.append('%s:"%s"' % (key, value))

    result = regclient.fetch_json_data(
        "get",
        "/v2/lib/search",
        params=dict(query=" ".join(query), page=page),
        cache_valid="1d",
    )

    if json_output:
        click.echo(dump_json_to_unicode(result))
        return

    if result["total"] == 0:
        click.secho(
            "Nothing has been found by your request\n"
            "Try a less-specific search or use truncation (or wildcard) "
            "operator",
            fg="yellow",
            nl=False,
        )
        click.secho(" *", fg="green")
        click.secho("For example: DS*, PCA*, DHT* and etc.\n", fg="yellow")
        click.echo(
            "For more examples and advanced search syntax, please use documentation:"
        )
        click.secho(
            "https://docs.platformio.org/page/userguide/lib/cmd_search.html\n",
            fg="cyan",
        )
        return

    click.secho(
        "Found %d libraries:\n" % result["total"],
        fg="green" if result["total"] else "yellow",
    )

    while True:
        for item in result["items"]:
            print_lib_item(item)

        if int(result["page"]) * int(result["perpage"]) >= int(result["total"]):
            break

        if noninteractive:
            click.echo()
            click.secho(
                "Loading next %d libraries... Press Ctrl+C to stop!"
                % result["perpage"],
                fg="yellow",
            )
            click.echo()
            time.sleep(5)
        elif not click.confirm("Show next libraries?"):
            break
        result = regclient.fetch_json_data(
            "get",
            "/v2/lib/search",
            params=dict(query=" ".join(query), page=int(result["page"]) + 1),
            cache_valid="1d",
        )
Beispiel #22
0
def lib_show(library, json_output):
    lm = LibraryPackageManager()
    lib_id = lm.reveal_registry_package_id(library, silent=json_output)
    regclient = lm.get_registry_client_instance()
    lib = regclient.fetch_json_data("get", "/v2/lib/info/%d" % lib_id, cache_valid="1h")
    if json_output:
        return click.echo(dump_json_to_unicode(lib))

    title = "{ownername}/{name}".format(**lib)
    click.secho(title, fg="cyan")
    click.echo("=" * len(title))
    click.echo(lib["description"])
    click.echo()

    click.secho("ID: %d" % lib["id"])
    click.echo(
        "Version: %s, released %s"
        % (
            lib["version"]["name"],
            time.strftime("%c", util.parse_date(lib["version"]["released"])),
        )
    )
    click.echo("Manifest: %s" % lib["confurl"])
    for key in ("homepage", "repository", "license"):
        if key not in lib or not lib[key]:
            continue
        if isinstance(lib[key], list):
            click.echo("%s: %s" % (key.title(), ", ".join(lib[key])))
        else:
            click.echo("%s: %s" % (key.title(), lib[key]))

    blocks = []

    _authors = []
    for author in lib.get("authors", []):
        _data = []
        for key in ("name", "email", "url", "maintainer"):
            if not author.get(key):
                continue
            if key == "email":
                _data.append("<%s>" % author[key])
            elif key == "maintainer":
                _data.append("(maintainer)")
            else:
                _data.append(author[key])
        _authors.append(" ".join(_data))
    if _authors:
        blocks.append(("Authors", _authors))

    blocks.append(("Keywords", lib["keywords"]))
    for key in ("frameworks", "platforms"):
        if key not in lib or not lib[key]:
            continue
        blocks.append(("Compatible %s" % key, [i["title"] for i in lib[key]]))
    blocks.append(("Headers", lib["headers"]))
    blocks.append(("Examples", lib["examples"]))
    blocks.append(
        (
            "Versions",
            [
                "%s, released %s"
                % (v["name"], time.strftime("%c", util.parse_date(v["released"])))
                for v in lib["versions"]
            ],
        )
    )
    blocks.append(
        (
            "Unique Downloads",
            [
                "Today: %s" % lib["dlstats"]["day"],
                "Week: %s" % lib["dlstats"]["week"],
                "Month: %s" % lib["dlstats"]["month"],
            ],
        )
    )

    for (title, rows) in blocks:
        click.echo()
        click.secho(title, bold=True)
        click.echo("-" * len(title))
        for row in rows:
            click.echo(row)

    return True
Beispiel #23
0
def cli(
    environment,
    project_dir,
    project_conf,
    pattern,
    flags,
    severity,
    silent,
    verbose,
    json_output,
    fail_on_defect,
    skip_packages,
):
    app.set_session_var("custom_project_conf", project_conf)

    # find project directory on upper level
    if isfile(project_dir):
        project_dir = find_project_dir_above(project_dir)

    results = []
    with fs.cd(project_dir):
        config = ProjectConfig.get_instance(project_conf)
        config.validate(environment)

        default_envs = config.default_envs()
        for envname in config.envs():
            skipenv = any([
                environment and envname not in environment,
                not environment and default_envs
                and envname not in default_envs,
            ])

            env_options = config.items(env=envname, as_dict=True)
            env_dump = []
            for k, v in env_options.items():
                if k not in ("platform", "framework", "board"):
                    continue
                env_dump.append(
                    "%s: %s" % (k, ", ".join(v) if isinstance(v, list) else v))

            default_patterns = [
                config.get_optional_dir("src"),
                config.get_optional_dir("include"),
            ]
            tool_options = dict(
                verbose=verbose,
                silent=silent,
                patterns=pattern
                or env_options.get("check_patterns", default_patterns),
                flags=flags or env_options.get("check_flags"),
                severity=[
                    DefectItem.SEVERITY_LABELS[DefectItem.SEVERITY_HIGH]
                ] if silent else severity
                or config.get("env:" + envname, "check_severity"),
                skip_packages=skip_packages
                or env_options.get("check_skip_packages"),
            )

            for tool in config.get("env:" + envname, "check_tool"):
                if skipenv:
                    results.append({"env": envname, "tool": tool})
                    continue
                if not silent and not json_output:
                    print_processing_header(tool, envname, env_dump)

                ct = CheckToolFactory.new(tool, project_dir, config, envname,
                                          tool_options)

                result = {"env": envname, "tool": tool, "duration": time()}
                rc = ct.check(on_defect_callback=None if (
                    json_output or verbose
                ) else lambda defect: click.echo(repr(defect)))

                result["defects"] = ct.get_defects()
                result["duration"] = time() - result["duration"]

                result["succeeded"] = rc == 0
                if fail_on_defect:
                    result["succeeded"] = rc == 0 and not any(
                        DefectItem.SEVERITY_LABELS[
                            d.severity] in fail_on_defect
                        for d in result["defects"])
                result["stats"] = collect_component_stats(result)
                results.append(result)

                if verbose:
                    click.echo("\n".join(repr(d) for d in result["defects"]))

                if not json_output and not silent:
                    if rc != 0:
                        click.echo("Error: %s failed to perform check! Please "
                                   "examine tool output in verbose mode." %
                                   tool)
                    elif not result["defects"]:
                        click.echo("No defects found")
                    print_processing_footer(result)

        if json_output:
            click.echo(dump_json_to_unicode(results_to_json(results)))
        elif not silent:
            print_check_summary(results)

    command_failed = any(r.get("succeeded") is False for r in results)
    if command_failed:
        raise exception.ReturnErrorCode(1)
Beispiel #24
0
def lib_show(library, json_output):
    lm = LibraryManager()
    name, requirements, _ = lm.parse_pkg_uri(library)
    lib_id = lm.search_lib_id({
        "name": name,
        "requirements": requirements
    },
                              silent=json_output,
                              interactive=not json_output)
    lib = util.get_api_result("/lib/info/%d" % lib_id, cache_valid="1d")
    if json_output:
        return click.echo(dump_json_to_unicode(lib))

    click.secho(lib['name'], fg="cyan")
    click.echo("=" * len(lib['name']))
    click.secho("#ID: %d" % lib['id'], bold=True)
    click.echo(lib['description'])
    click.echo()

    click.echo(
        "Version: %s, released %s" %
        (lib['version']['name'],
         time.strftime("%c", util.parse_date(lib['version']['released']))))
    click.echo("Manifest: %s" % lib['confurl'])
    for key in ("homepage", "repository", "license"):
        if key not in lib or not lib[key]:
            continue
        if isinstance(lib[key], list):
            click.echo("%s: %s" % (key.title(), ", ".join(lib[key])))
        else:
            click.echo("%s: %s" % (key.title(), lib[key]))

    blocks = []

    _authors = []
    for author in lib.get("authors", []):
        _data = []
        for key in ("name", "email", "url", "maintainer"):
            if not author[key]:
                continue
            if key == "email":
                _data.append("<%s>" % author[key])
            elif key == "maintainer":
                _data.append("(maintainer)")
            else:
                _data.append(author[key])
        _authors.append(" ".join(_data))
    if _authors:
        blocks.append(("Authors", _authors))

    blocks.append(("Keywords", lib['keywords']))
    for key in ("frameworks", "platforms"):
        if key not in lib or not lib[key]:
            continue
        blocks.append(("Compatible %s" % key, [i['title'] for i in lib[key]]))
    blocks.append(("Headers", lib['headers']))
    blocks.append(("Examples", lib['examples']))
    blocks.append(("Versions", [
        "%s, released %s" %
        (v['name'], time.strftime("%c", util.parse_date(v['released'])))
        for v in lib['versions']
    ]))
    blocks.append(("Unique Downloads", [
        "Today: %s" % lib['dlstats']['day'],
        "Week: %s" % lib['dlstats']['week'],
        "Month: %s" % lib['dlstats']['month']
    ]))

    for (title, rows) in blocks:
        click.echo()
        click.secho(title, bold=True)
        click.echo("-" * len(title))
        for row in rows:
            click.echo(row)

    return True
Beispiel #25
0
##############################################################################

if "envdump" in COMMAND_LINE_TARGETS:
    click.echo(env.Dump())
    env.Exit(0)

if "idedata" in COMMAND_LINE_TARGETS:
    try:
        Import("projenv")
    except:  # pylint: disable=bare-except
        projenv = env
    click.echo(
        "\n%s\n"
        % dump_json_to_unicode(
            projenv.DumpIDEData()  # pylint: disable=undefined-variable
        )
    )
    env.Exit(0)

if "sizedata" in COMMAND_LINE_TARGETS:
    AlwaysBuild(
        env.Alias(
            "sizedata",
            DEFAULT_TARGETS,
            env.VerboseAction(env.DumpSizeData, "Generating memory usage report..."),
        )
    )

    Default("sizedata")
Beispiel #26
0
def device_list(  # pylint: disable=too-many-branches
    serial, logical, mdns, json_output
):
    if not logical and not mdns:
        serial = True
    data = {}
    if serial:
        data["serial"] = util.get_serial_ports()
    if logical:
        data["logical"] = util.get_logical_devices()
    if mdns:
        data["mdns"] = util.get_mdns_services()

    single_key = list(data)[0] if len(list(data)) == 1 else None

    if json_output:
        return click.echo(
            dump_json_to_unicode(data[single_key] if single_key else data)
        )

    titles = {
        "serial": "Serial Ports",
        "logical": "Logical Devices",
        "mdns": "Multicast DNS Services",
    }

    for key, value in data.items():
        if not single_key:
            click.secho(titles[key], bold=True)
            click.echo("=" * len(titles[key]))

        if key == "serial":
            for item in value:
                click.secho(item["port"], fg="cyan")
                click.echo("-" * len(item["port"]))
                click.echo("Hardware ID: %s" % item["hwid"])
                click.echo("Description: %s" % item["description"])
                click.echo("")

        if key == "logical":
            for item in value:
                click.secho(item["path"], fg="cyan")
                click.echo("-" * len(item["path"]))
                click.echo("Name: %s" % item["name"])
                click.echo("")

        if key == "mdns":
            for item in value:
                click.secho(item["name"], fg="cyan")
                click.echo("-" * len(item["name"]))
                click.echo("Type: %s" % item["type"])
                click.echo("IP: %s" % item["ip"])
                click.echo("Port: %s" % item["port"])
                if item["properties"]:
                    click.echo(
                        "Properties: %s"
                        % (
                            "; ".join(
                                [
                                    "%s=%s" % (k, v)
                                    for k, v in item["properties"].items()
                                ]
                            )
                        )
                    )
                click.echo("")

        if single_key:
            click.echo("")

    return True
Beispiel #27
0
        lambda source, target, env: env.PrintUploadInfo(),
        "Configuring upload protocol...",
    ),
)

AlwaysBuild(env.Alias("debug", DEFAULT_TARGETS))
AlwaysBuild(env.Alias("__test", DEFAULT_TARGETS))

##############################################################################

if "envdump" in COMMAND_LINE_TARGETS:
    click.echo(env.Dump())
    env.Exit(0)

if "idedata" in COMMAND_LINE_TARGETS:
    Import("projenv")
    click.echo("\n%s\n" % dump_json_to_unicode(projenv.DumpIDEData()  # pylint: disable=undefined-variable
                                               ))
    env.Exit(0)

if "sizedata" in COMMAND_LINE_TARGETS:
    AlwaysBuild(
        env.Alias(
            "sizedata",
            DEFAULT_TARGETS,
            env.VerboseAction(env.DumpSizeData,
                              "Generating memory usage report..."),
        ))

    Default("sizedata")