Best Python code snippet using lisa_python
__init__.py
Source:__init__.py  
...68            print(result)69            raise Exception("Unknown notarization result")70    else:71        raise Exception("Gave up notarization")72def get_package_information() -> PackageInformation:73    global _package_information74    if _package_information is None:75        _package_information = PackageInformation()76        with open("PACKAGE.FS", "r") as f:77            for line in f:78                try:79                    key, value = line.split("=", 1)80                    key = key.strip()81                    value = value.strip()82                    value = value.strip('"')83                    _package_information.values[key] = value84                except ValueError:85                    pass86    return _package_information87def get_app_name() -> str:88    return get_package_information().display_name + ".app"89def get_architecture() -> str:90    machine = platform.machine()91    if machine == "arm64":92        arch = "ARM64"93    else:94        arch = "x86-64"  # FIXME95    return arch96def get_bundle_name() -> str:97    package_information = get_package_information()98    if package_information.type == "fs-library-plugin":99        return get_framework_name()100    else:101        return get_app_name()102def get_bundle_path(prefix: str = "fsbuild/_build/") -> str:103    pretty_name = get_package_information().pretty_name104    bundle_name = get_bundle_name()105    arch = get_architecture()106    path = f"{prefix}{pretty_name}/macOS/{arch}/{bundle_name}"107    return path108def get_dmg_path() -> str:109    package_information = get_package_information()110    pretty_name = package_information.pretty_name111    version = package_information.version112    arch = get_architecture()113    os_dist = get_operating_system_dist()114    path = f"fsbuild/_dist/{pretty_name}_{version}_{os_dist}_{arch}.dmg"115    return path116def get_framework_name() -> str:117    return get_package_information().pretty_name + ".framework"118def get_notarization_itc_provider() -> str:119    return os.environ.get("NOTARIZATION_PROVIDER", "")120def get_notarization_username() -> str:121    return os.environ.get("NOTARIZATION_USERNAME", "")122def get_operating_system_dist() -> str:123    env_value = os.environ.get("SYSTEM_OS_DIST", "")124    if env_value:125        return env_value126    elif sys.platform == "linux":127        return "Linux"128    elif sys.platform == "darwin":129        return "macOS"130    elif sys.platform == "win32":131        return "Windows"132    return "Unknown"133def is_macos() -> bool:134    return sys.platform == "darwin"135def notarize_app(path_to_notarize: str, bundle_id: str) -> str:136    assert path.exists(path_to_notarize)137    print(f"Notarizing {path.basename(path_to_notarize)}")138    result = shell(139        "xcrun altool --notarize-app -t osx "140        "-f {path_to_notarize} "141        "--primary-bundle-id {bundle_id} "142        "-u {apple_id_user} "143        "-p @env:NOTARIZATION_PASSWORD "144        "-itc_provider {itc_provider} "145        "--output-format xml".format(146            apple_id_user=get_notarization_username(),147            bundle_id=bundle_id,148            itc_provider=get_notarization_itc_provider(),149            path_to_notarize=path_to_notarize,150        )151    )152    print(result)153    root = xml.etree.ElementTree.fromstring(result)154    dict_node = root.find("dict")155    assert dict_node is not None156    dict_node_2 = dict_node.find("dict")157    assert dict_node_2 is not None158    string_node = dict_node_2.find("string")159    assert string_node is not None160    request_uuid = string_node.text161    assert request_uuid162    print(request_uuid)163    return request_uuid164def run(args: List[str]) -> str:165    print(quote_args(args))166    # p = subprocess.Popen(args, stdout = subprocess.PIPE)167    # assert p.wait() == 0168    # assert p.stdout169    # output = p.stdout.read().decode("UTF-8")170    # assert p.wait() == 0171    # return output172    return subprocess.check_output(args).decode("UTF-8")173def run_codesign(args: List[str]) -> None:174    # Signing sometimes fails due to Apple errors (timeouts, etc). So we try175    # multiple times before giving up.176    for i in range(20):177        try:178            shell(quote_args(args))179        except Exception:180            time.sleep(1.0 * i)181            print("Attempt", i + 2)182        else:183            break184    else:185        raise Exception("Giving up signing")186def quote_arg(arg: str) -> str:187    if " " in arg:188        return f'"{arg}"'189    return arg190def quote_args(args: List[str]) -> str:191    return " ".join(f"{quote_arg(a)}" for a in args)192def shell(cmd: str) -> str:193    print(cmd)194    return subprocess.run(195        cmd, shell=True, check=True, stdout=subprocess.PIPE196    ).stdout.decode("UTF-8")197class Version:198    def __init__(self, version: str) -> None:199        self.version = version200        m = re.match("([0-9.]+[0-9])(.*)", version)201        assert m is not None202        parts = m.group(1).split(".")203        assert 2 <= len(parts) <= 4204        self.major = int(parts[0])205        self.minor = int(parts[1])206        self.build: Optional[int]207        if len(parts) > 3:208            self.build = int(parts[3])209        else:210            self.build = None211        if len(parts) > 2:212            self.revision = int(parts[2])213        else:214            self.revision = 0215        self.tag = m.group(2)216        self.commit = ""217    def set_last(self, n: int) -> None:218        if self.build is not None:219            self.build = n220        else:221            self.revision = n222    def __str__(self) -> str:223        numbers = [self.major, self.minor, self.revision]224        if self.build is not None:225            numbers.append(self.build)226        version = ".".join(str(x) for x in numbers)227        return version + self.tag228def num_commits_since(base: str) -> int:229    to = "HEAD"230    result = int(231        subprocess.check_output(232            ["git", "rev-list", f"{base}..{to}", "--count"]233        ).decode()234    )235    return result236def find_last_commit_for_file(path: str) -> str:237    commit = subprocess.check_output(238        ["git", "log", "-n", "1", "--pretty=format:%H", "--", path]239    ).decode()240    return commit241def find_last_commit() -> str:242    commit = subprocess.check_output(243        ["git", "log", "-n", "1", "--pretty=format:%H"]244    ).decode()245    return commit246def update_configure_ac(version: Version, commit: str = "") -> None:247    print("Updating configure.ac")248    lines: List[str] = []249    with open("configure.ac", "r", encoding="UTF-8") as f:250        for line in f:251            if line.startswith("m4_define([fsbuild_version"):252                if "_major" in line:253                    k = "FSBUILD_VERSION_MAJOR"254                    v = str(version.major)255                    # d = "Major version"256                elif "_minor" in line:257                    k = "FSBUILD_VERSION_MINOR"258                    v = str(version.minor)259                    # d = "Minor version"260                elif "_revision" in line:261                    k = "FSBUILD_VERSION_REVISION"262                    v = str(version.revision)263                    # d = "Revision"264                else:265                    k = "FSBUILD_VERSION"266                    v = str(version)267                    # d = "Full version"268                line = "m4_define([{}], [{}])\n".format(k.lower(), v)269            # if line.startswith("AC_DEFINE_UNQUOTED([FSBUILD_VERSION"):270            #     if "_MAJOR" in line:271            #         k = "FSBUILD_VERSION_MAJOR"272            #         v = version.major273            #         d = "Major version"274            #     elif "_MINOR" in line:275            #         k = "FSBUILD_VERSION_MINOR"276            #         v = version.minor277            #         d = "Minor version"278            #     elif "_REVISION" in line:279            #         k = "FSBUILD_VERSION_REVISION"280            #         v = version.revision281            #         d = "Revision"282            #     else:283            #         k = "FSBUILD_VERSION"284            #         v = str(version)285            #         d = "Full version"286            #     line = "AC_DEFINE_UNQUOTED([{}], [{}], [{}])\n".format(k, v, d)287            if line.startswith("m4_define([fsbuild_commit"):288                line = "m4_define([{}], [{}])\n".format(289                    "fsbuild_commit", commit290                )291            # if line.startswith("AC_DEFINE_UNQUOTED([FSBUILD_COMMIT"):292            #     k = "FSBUILD_COMMIT"293            #     v = commit294            #     d = "Package commit"295            #     line = "AC_DEFINE_UNQUOTED([{}], [{}], [{}])\n".format(k, v, d)296            lines.append(line)297    with open("configure.ac", "w", encoding="UTF-8") as f:298        for line in lines:299            f.write(line)300def update_debian_changelog(version: Version) -> None:301    print("Updating debian/changelog")302    lines: List[str] = []303    first_line = True304    first_line_changed = False305    deb_package = "unknown"306    deb_version = str(version)307    # deb_version = deb_version.replace("alpha", "~alpha")308    # deb_version = deb_version.replace("beta", "~beta")309    # deb_version = deb_version.replace("dev", "~dev")310    with open("debian/changelog", "r", encoding="UTF-8") as f:311        for line in f:312            if first_line:313                first_line = False314                deb_package = line.split(" ", 1)[0]315                lines.append(316                    "{} ({}-0) unstable; urgency=low\n".format(317                        deb_package, deb_version318                    )319                )320                if lines[-1] != line:321                    first_line_changed = True322            elif line.startswith(" -- ") and first_line_changed:323                # Only update date if version was changed324                author, date = line.split("  ")325                date = datetime.datetime.utcnow().strftime(326                    "%a, %d %b %Y %H:%M:%S +0000"327                )328                lines.append("{}  {}\n".format(author, date))329            else:330                lines.append(line)331    with open("debian/changelog", "w", encoding="UTF-8") as f:332        for line in lines:333            f.write(line)334def update_spec_file(path: str, version: Version) -> None:335    print("Updating", path)336    lines: List[str] = []337    rpm_version = str(version)338    # rpm_version = rpm_version.replace("alpha", "-0.1alpha")339    # rpm_version = rpm_version.replace("beta", "-0.1~beta")340    # rpm_version = rpm_version.replace("dev", "-0.1dev")341    # if not "-" in rpm_version:342    #     rpm_version += "-1"343    with open(path, "r", encoding="UTF-8") as f:344        for line in f:345            if line.startswith("%define fsbuild_version "):346                lines.append(347                    "%define fsbuild_version {}\n".format(rpm_version)348                )349            # elif line.startswith("%define unmangled_version "):350            #     lines.append("%define unmangled_version {0}\n".format(version))351            else:352                lines.append(line)353    with open(path, "w", newline="\n") as f:354        f.write("".join(lines))355def update_package_fs(version: Version) -> None:356    print("Updating PACKAGE.FS")357    lines: List[str] = []358    with open("PACKAGE.FS", "r", encoding="UTF-8") as f:359        for line in f:360            if line.startswith("PACKAGE_VERSION="):361                lines.append(f"PACKAGE_VERSION={str(version)}\n")362            elif line.startswith("PACKAGE_VERSION_MAJOR="):363                lines.append(f"PACKAGE_VERSION_MAJOR={str(version.major)}\n")364            elif line.startswith("PACKAGE_VERSION_MINOR="):365                lines.append(f"PACKAGE_VERSION_MINOR={str(version.minor)}\n")366            elif line.startswith("PACKAGE_VERSION_REVISION="):367                lines.append(368                    f"PACKAGE_VERSION_REVISION={str(version.revision)}\n"369                )370            elif line.startswith("PACKAGE_VERSION_TAG="):371                lines.append(f"PACKAGE_VERSION_TAG={str(version.tag)}\n")372            elif line.startswith("PACKAGE_COMMIT="):373                lines.append(f"PACKAGE_COMMIT={version.commit}\n")374            else:375                lines.append(line)376    with open("PACKAGE.FS", "w", newline="\n") as f:377        f.write("".join(lines))378def update_version_fs(version: Version) -> None:379    print("Updating VERSION.FS")380    with open("VERSION.FS", "w") as f:381        f.write(str(version))382        f.write("\n")383def update_commit_fs(version: Version) -> None:384    print("Updating COMMIT.FS")385    with open("COMMIT.FS", "w") as f:386        if version.commit:387            f.write(version.commit)388            f.write("\n")389def calculate_version(390    auto_revision: bool = False,391    increment_revision: bool = False,392    include_commit: bool = False,393) -> Version:394    # with open("fsbuild/VERSION") as f:395    with open("BASEVERSION.FS") as f:396        version_str = f.read().strip()397    if version_str.startswith("BASEVERSION_FS="):398        version_str = version_str[len("BASEVERSION_FS=") :].strip()399    # with open("PACKAGE.FS") as f:400    #     for line in f:401    #         if line.startswith("PACKAGE_VERSION="):402    #             version_str = line[16:].strip()403    version = Version(version_str)404    if auto_revision:405        version_commit = find_last_commit_for_file("BASEVERSION.FS")406        increment = num_commits_since(version_commit)407        if increment_revision:408            increment += 1409        if version.build is not None:410            version.build += increment411        else:412            version.revision += increment413    if "--commit" in sys.argv:414        version.commit = find_last_commit()415    if True:416        branch = None417        github_ref = os.environ.get("GITHUB_REF")418        if github_ref is not None:419            if github_ref.startswith("refs/heads/"):420                branch = github_ref[len("refs/heads/") :]421            if github_ref.startswith("refs/pull/"):422                branch = "pull" + github_ref[len("refs/pull/") :].replace(423                    "/", ""424                )425        if not branch:426            branch = subprocess.check_output(427                ["git", "symbolic-ref", "--short", "HEAD"], encoding="UTF-8"428            ).strip()429        if branch == "stable":430            version.tag = ""431        elif branch:432            version.tag = f"-{branch}"433        else:434            raise Exception("Cannot calculate version tag from git ref")435    return version436def update_version(version: Version) -> None:437    if os.path.exists("VERSION.FS"):438        update_version_fs(version)439    if os.path.exists("COMMIT.FS"):440        update_commit_fs(version)441    if os.path.exists("configure.ac"):442        update_configure_ac(version)443    if os.path.exists("debian/changelog"):444        update_debian_changelog(version)445    if os.path.exists("PACKAGE.FS"):446        update_package_fs(version)447    for filename in os.listdir("."):448        if filename.endswith(".spec"):449            update_spec_file(filename, version)450def version_main() -> None:451    # For date/time formatting452    locale.setlocale(locale.LC_TIME, "C")453    # auto_revision = "--auto" in sys.argv454    auto_revision = True455    increment_revision = "--next" in sys.argv456    # include_commit = "--commit" in sys.argv457    include_commit = True458    # if "--auto-next" in sys.argv:459    #     auto_revision = True460    #     increment_revision = True461    version = calculate_version(462        auto_revision=auto_revision,463        increment_revision=increment_revision,464        include_commit=include_commit,465    )466    for arg in sys.argv:467        if arg.startswith("--build="):468            version.build = int(arg[8:])469        elif arg.startswith("--revision="):470            version.revision = int(arg[11:])471        elif arg.startswith("--last="):472            version.set_last(int(arg[7:]))473    print(str(version))474    if "--print" in sys.argv:475        # Only print version476        pass477    else:478        update_version(version)479def build_dmg_main():480    if not is_macos():481        print("Not building DMG on non-macOS platform")482        return483    dmg_path = get_dmg_path()484    bundle_path = get_bundle_path()485    package_information = get_package_information()486    print(f"Building {path.basename(dmg_path)}")487    if not path.exists(path.dirname(dmg_path)):488        os.makedirs(path.dirname(dmg_path))489    if os.path.exists(dmg_path):490        os.unlink(dmg_path)491    tool = "appdmg"492    if tool == "appdmg":493        bundle_path = get_bundle_path(prefix="")494        settings_path = "fsbuild/_build/appdmg.json"495        with open(settings_path, "w", encoding="UTF-8") as f:496            json.dump(497                {498                    "title": package_information.display_name,499                    "contents": [500                        {501                            "x": 192,502                            "y": 344,503                            "type": "file",504                            "path": bundle_path,505                        },506                        {507                            "x": 448,508                            "y": 344,509                            "type": "link",510                            "path": "/Applications",511                        },512                    ],513                },514                f,515            )516        subprocess.check_call(517            [518                "appdmg",519                settings_path,520                dmg_path,521            ]522        )523    elif tool == "dmgbuild":  # type: ignore524        bundle_path = get_bundle_path()525        settings_path = "fsbuild/_build/dmgbuild-settings.py"526        with open(settings_path, "w", encoding="UTF-8") as f:527            f.write("format = 'UDZO'\n")528            f.write("files = [\n")529            f.write(f"    '{bundle_path}',\n")530            f.write("]\n")531            f.write("symlinks = { 'Applications': '/Applications' }\n")532            f.write("badge_icon = 'icon/fs-uae-launcher.icns'\n")533        subprocess.check_call(534            [535                "dmgbuild",536                "-s",537                settings_path,538                "FS-UAE-Launcher",539                dmg_path,540            ]541        )542    else:543        raise Exception("Unknown dmg builder")544def sign_main():545    if get_package_information().type == "fs-data-plugin":546        print("Not signing data plugin")547    elif is_macos():548        args = [549            "codesign",550            "--force",551            "--deep",552            "--options",553            "runtime",554            "--sign",555            "Developer ID Application",556            "--digest-algorithm=sha1,sha256",557        ]558        if os.path.exists("fsbuild/Entitlements.plist"):559            args.extend(["--entitlements", "fsbuild/Entitlements.plist"])560        args.append(get_bundle_path())561        run_codesign(args)562    else:563        print("Skipping sign step (no signatures for this platform)")564def sign_dmg_main():565    if not is_macos():566        print("Not signing DMG on non-macOS platform")567        return568    args = [569        "codesign",570        "--force",571        "--sign",572        "Developer ID Application",573        "--digest-algorithm=sha1,sha256",574    ]575    args.append(get_dmg_path())576    run_codesign(args)577def notarize_for_macos():578    bundle_id = get_package_information().bundle_id579    bundle_path = get_bundle_path()580    bundle_name = os.path.basename(bundle_path)581    bundle_parent_dir = os.path.dirname(bundle_path)582    shell("rm -f fsbuild/_build/notarize.zip")583    zip = "../../../notarize.zip"584    shell(585        f'cd {bundle_parent_dir} && ditto -c -k --keepParent "{bundle_name}" "{zip}"'586    )587    request_uuid = notarize_app("fsbuild/_build/notarize.zip", bundle_id)588    check_notarization_result(request_uuid)589    if bundle_path.endswith(".framework"):590        print(591            "Does not seem to be possible to staple tickets to frameworks? (error 73)"592        )593        print("Exiting...")594        sys.exit(0)595    run(["xcrun", "stapler", "staple", bundle_path])596def notarize_main():597    if get_package_information().type == "fs-data-plugin":598        print("Not notarizing data plugin")599    elif is_macos():600        notarize_for_macos()601    else:602        print("Skipping sign step (no signatures for this platform)")603def notarize_dmg_main():604    if not is_macos():605        print("Not notarizing DMG on non-macOS platform")606        return607    package_information = get_package_information()608    bundle_id = package_information.bundle_id609    dmg_path = get_dmg_path()610    assert path.exists(dmg_path)611    request_uuid = notarize_app(dmg_path, bundle_id)612    check_notarization_result(request_uuid)613    print('xcrun stapler staple "{}"'.format(dmg_path))614    assert os.system('xcrun stapler staple "{}"'.format(dmg_path)) == 0615    print("-" * 80)616    print(f"[FSBUILD] Notarized {dmg_path}")617def verify_download(archive: str, h: Any, checksum: str) -> bool:618    with open(archive, "rb") as f:619        actual_checksum = h(f.read()).hexdigest()620    result = actual_checksum == checksum621    if result:622        print("Checksum verified")623    else:624        print("Checksum verification failed")625        print("Expected", checksum)626        print("But got:", actual_checksum)627    return result628def download_main():629    url = sys.argv[1]630    checksum = sys.argv[2]631    if checksum.startswith("sha256:"):632        h = hashlib.sha256633        checksum = checksum[7:]634    else:635        raise Exception("Unknown hash function")636    archive = url.split("/")[-1]637    if not os.path.exists("fsbuild/_sources"):638        os.makedirs("fsbuild/_sources")639    archive = os.path.join("fsbuild/_sources", archive)640    if os.path.exists(archive):641        if verify_download(archive, h, checksum):642            sys.exit(0)643        print("Removing archive", archive)644        os.remove(archive)645    # FIXME: Replace use of wget, just use python instead646    if os.system(f'cd fsbuild/_sources && wget "{url}"') != 0:647        print("Failed to download")648        sys.exit(1)649    if not verify_download(archive, h, checksum):650        sys.exit(2)651def execute_discord_webhook(name: str, link: str) -> None:652    import requests653    webhook_url = os.getenv("DISCORD_WEBHOOK_URL")654    if not webhook_url:655        return656    content = (657        f"`{name}` was built and uploaded to a Dropbox "658        f"[shared folder]({link})"659    )660    requests.post(webhook_url, {"content": content, "username": "Builder"})661def get_upload_branch_name() -> Optional[str]:662    ref = os.getenv("GITHUB_REF", "")663    try:664        branch = ref.split("refs/heads/", 1)[1]665    except IndexError:666        return None667    if "/" in branch:668        return None669    return branch[0].upper() + branch[1:]670def upload(package: str, version: str, path: str) -> None:671    import dropbox  # type: ignore672    dbx: Any = dropbox.Dropbox(os.getenv("DROPBOX_ACCESS_TOKEN"))  # type: ignore673    print("Upload", path)674    name = os.path.basename(path)675    assert package.lower() in name.lower()676    assert version in name677    branch = get_upload_branch_name()678    if not branch:679        print("No upload branch name, skipping upload")680        return681    dst = f"/Builds/CI/{package}/{branch}/{version}/{name}"682    with open(path, "rb") as f:683        dbx.files_upload(f.read(), dst)684    print("Uploaded ->", dst)685    if os.getenv("DISCORD_WEBHOOK_URL"):686        result: Any = dbx.sharing_list_shared_links(f"/Builds/CI/{package}")687        for link in result.links:688            if link.path_lower == f"/Builds/CI/{package}".lower():689                url = link.url690                print("Found Dropbox shared link:", url)691                break692        else:693            # Fallback URL, use first result returned694            url = result.links[0].url695            print("Found Dropbox shared (fallback) link:", url)696        execute_discord_webhook(name, url)697def upload_main():698    dist_dir = "fsbuild/_dist"699    upload_items = os.listdir(dist_dir)700    package = get_package_information()701    for item in upload_items:702        upload(703            package.pretty_name,704            package.version,705            os.path.join(dist_dir, item),706        )707if __name__ == "__main__":708    if len(sys.argv) < 2:709        print("Missing command")710        sys.exit(1)711    elif sys.argv[1] == "build-dmg":712        build_dmg_main()713    elif sys.argv[1] == "download":714        download_main()...update_dashboard.py
Source:update_dashboard.py  
...26        27        all_packages = os.listdir('libraries/')28        packages = get_packages(sort_key = 'First Release Date')29        for count, package in enumerate(packages):30            first_release = get_package_information(package, 'First Release Date')31            last_release = get_package_information(package, 'Last Release Date')32            stars = get_package_information(package, 'GitHub Stars')33            forks = get_package_information(package, 'GitHub Forks')34            watchers = get_package_information(package, 'GitHub Watchers')35            contributors = get_package_information(package, 'GitHub Contributors')36            ci_badge = get_package_information(package, 'ci_badge')37            ci_target = get_package_information(package, 'ci_target')38            coverage_badge = get_package_information(package, 'coverage_badge')39            coverage_target = get_package_information(package, 'coverage_target')40            docs_badge = get_package_information(package, 'docs_badge')41            docs_target = get_package_information(package, 'docs_target')42            codeclimate_badge = get_package_information(package, 'codeclimate_badge')43            codeclimate_target = get_package_information(package, 'codeclimate_target')44            pepy_downloads_badge = get_package_information(package, 'pepy_downloads_badge')45            pepy_downloads_target = get_package_information(package, 'pepy_downloads_target')46            syntek_package_health_badge = get_package_information(package, 'syntek_package_heath_badge')47            syntek_package_health_target = get_package_information(package, 'syntek_package_heath_target')48            lines_of_code = get_package_information(package, 'loc')49           50            homepage = get_package_information(package, 'home_page')51            if homepage is None:52                homepage = 'Not Found'53            54            fileout.write('  <tr>\n')55           56            short_homepage = homepage57            host_logo = 'None'58            logo_spacer = ''59            try:60                short_homepage = homepage.split('/')[2]61                host_logo = short_homepage.split('.')[0]62                if host_logo == 'weisslab':63                    host_logo = 'gitlab'64            except:65                logo_spacer = '.%20%20%20'66                pass67            68            package_badge = str('https://img.shields.io/badge/' + logo_spacer +69                    str(count) + '-' + package.replace('-', '‑') +70                    '-orange?style=flat&logo=' + host_logo)71            WriteCellWithLinkedImage(fileout, package_badge , 72                    homepage, 'Library Homepage')73            74            weeks_up = 075            try:76                time_up = datetime.now() - datetime.fromisoformat(first_release)77                weeks_up = int(time_up.days/7)78            except ValueError:79                pass80            81            weeks_up_badge = None82            weeks_up_target = None83            if weeks_up > 0:84                weeks_up_badge = str('https://img.shields.io/badge/Weeks%20Up-' + 85                    str(weeks_up) + '-green?style=flat')86                weeks_up_target = str(homepage + '/releases')87            WriteCellWithLinkedImage(fileout, weeks_up_badge, 88                    weeks_up_target, 'Total Weeks Up')89            90            last_release_badge = None91            last_release_target = None92            if last_release != 'n/a':93                last_release_badge = str('https://img.shields.io/badge/Last%20Release-' +94                    str(last_release).split('T')[0].replace('-', '%20') + '-green?style=flat') 95                last_release_target = str(homepage + '/releases')96            97            WriteCellWithLinkedImage(fileout, last_release_badge, 98                    last_release_target, 'Last Release Date')99            WriteCellWithLinkedImage(fileout, ci_badge, 100                    ci_target, 'CI Status')101            WriteCellWithLinkedImage(fileout, docs_badge, 102                    docs_target, 'Docs Status')103            WriteCellWithLinkedImage(fileout, coverage_badge, 104                    coverage_target, 'Code Coverage')105            loc_badge = None106            loc_link = str('loc/' + package + '.html')107            if lines_of_code is not None:108                loc_badge = str('https://img.shields.io/badge/LOC-' +109                    str(lines_of_code) + '-blue?style=flat')110             111            WriteCellWithLinkedImage(fileout, loc_badge, loc_link, 'Lines of Code')112            WriteCellWithLinkedImage(fileout, pepy_downloads_badge, 113                    pepy_downloads_target, 'All Downloads from PePy')114            github_user = get_package_information(package, 'GitHub User')115            stars_badge = None116            forks_badge = None117            watchers_badge = None118            contrib_badge = None119            if github_user is not None:120                stars_badge = str('https://img.shields.io/github/stars/' + github_user + '/' + package +121                    '?style=social')122                forks_badge = str('https://img.shields.io/github/forks/' + github_user + '/' + package +123                    '?style=social')124                watchers_badge = str('https://img.shields.io/github/watchers/' + github_user + '/' + package +125                    '?style=social')126                contrib_badge = str('https://img.shields.io/badge/contrib-' + 127                        str(contributors) 128                        + '-lightgrey?style=social&logo=github')129            WriteCellWithLinkedImage(fileout, stars_badge, 130                    str(homepage + '/stargazers'), 'GitHub Stars')131            132            WriteCellWithLinkedImage(fileout, forks_badge, 133                    str(homepage + '/forks'), 'GitHub Forks')134            135            WriteCellWithLinkedImage(fileout, watchers_badge, 136                    str(homepage + '/watchers'), 'GitHub Watchers')137            WriteCellWithLinkedImage(fileout, contrib_badge, 138                    str(homepage + '/graphs/contributors'), 'GitHub Contributors')139            140            WriteCellWithLinkedImage(fileout, syntek_package_health_badge, 141                    syntek_package_health_target, 'SynTek Package Health')142            143            WriteCellWithLinkedImage(fileout, codeclimate_badge, 144                    codeclimate_target, 'SynTek Package Health')145            fileout.write('  </tr>\n')146        147        fileout.write(tail)148    head = ""149    with open('html/excluded.html.in.head', 'r') as filein:150        head = filein.read()151    tail = ""152    with open('html/excluded.html.in.tail', 'r') as filein:153        tail = filein.read()154    with open('html/exclusions.html' , 'w') as fileout:155        fileout.write(head)156        excluded_packages = get_packages(sort_key = None, 157                                         path = 'libraries/exclusions/',158                                         exclusions_path = 'not a path')159        for new_count, package in enumerate(excluded_packages):160            homepage = get_package_information(package, 'home_page')161            if homepage is None:162                homepage = 'Not Found'163            164            fileout.write('  <tr>\n')165           166            short_homepage = homepage167            host_logo = 'None'168            logo_spacer = ''169            try:170                short_homepage = homepage.split('/')[2]171                host_logo = short_homepage.split('.')[0]172                if host_logo == 'weisslab':173                    host_logo = 'gitlab'174            except:175                logo_spacer = '.%20%20%20'176                pass177            178            package_badge = str('https://img.shields.io/badge/' + logo_spacer +179                    str(count+new_count+1) + '-' + package.replace('-', '‑') +180                    '-orange?style=flat&logo=' + host_logo)181            WriteCellWithLinkedImage(fileout, package_badge , 182                    homepage, 'Library Homepage')183            reason = get_package_information(package, 'obsolete', 184                                             path = 'libraries/exclusions/')185            fileout.write('    <td>\n')186            fileout.write('      <p>' + str(reason) + '</p>\n')187            fileout.write('    </td>\n')188            fileout.write('  </tr>\n')189   ...get_badges.py
Source:get_badges.py  
...23            24    for package in packages:25        26        print("Getting badges for ", package)27        ci_badge = get_package_information(package, 'ci_badge')28        ci_target = get_package_information(package, 'ci_target')29        coverage_badge = get_package_information(package, 'coverage_badge')30        coverage_target = get_package_information(package, 'coverage_target')31        docs_badge = get_package_information(package, 'docs_badge')32        docs_target = get_package_information(package, 'docs_target')33        codeclimate_badge = get_package_information(package, 'codeclimate_badge')34        codeclimate_target = get_package_information(package, 'codeclimate_target')35        pepy_downloads_badge = get_package_information(package, 'pepy_downloads_badge')36        pepy_downloads_target = get_package_information(package, 'pepy_downloads_target')37        syntek_package_heath_badge = get_package_information(package, 'syntek_package_heath_badge')38        syntek_package_heath_target = get_package_information(package, 'syntek_package_heath_target')39        40        homepage = get_package_information(package, 'home_page')41        if homepage is not None:42            43            project_name = homepage44            split_name = project_name.split('/')45            try:46                project_name = split_name[-2] + '/' + split_name[-1]47            except IndexError:48                pass49            if ci_badge is None:50                ci_badge = str(homepage + '/workflows/.github/workflows/ci.yml/badge.svg')51            if ci_target is None:52                ci_target = str(homepage + '/actions')53            if coverage_badge is None:54                coverage_badge = str('https://coveralls.io/repos/github/' + project_name + '/badge.svg?branch=master&service=github')...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
