[script] bugtracker

Autres projets et contributions
Avatar de l’utilisateur
papajoke
Elfe
Messages : 784
Inscription : sam. 30 août 2014, 19:54

[script] bugtracker

Message par papajoke »

bonjour

Avec les bugs dans gitlab, j'ai du mal à avoir un bon aperçu des bugs (bug lié à quel paquet ?)

Un script pour notre terminal écrit en python
Il ne fonctionne que pour les utilisateurs inscrits sur gitlab, il faut créer un TOKEN et le passer au script.

Le résultat donne un affichage (couleur) du type:

Code : Tout sélectionner

python-pyarrow: Arbitrary code executaion vulnerability: CVE-2023-47248         2023-11-15  (2) (8)
  2-high confirmed
  https://gitlab.archlinux.org/archlinux/packaging/packages/python-pyarrow/-/issues/3

python-pipenv-to-requirements: FTBS lacks setuptools as makedep         2023-11-17  (1) ()
  4-low confirmed
  https://gitlab.archlinux.org/archlinux/packaging/packages/python-pipenv-to-requirements/-/issues/1
Note: les numéros après la date sont : les assignés et nombre de réponses dans le sujet

Code : Tout sélectionner

#!/usr/bin/env python

import argparse
from enum import Enum
import json
import os
from urllib import request, error
import sys

TOKEN = os.getenv('API_GITLAB_ARCH', "XXXX-XXXXXXXXXXXXXXX")


class Colors(Enum):
    BLUE = '\033[94m'
    GREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    GRAY = '\033[90m'
    SOMBRE = '\033[96m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'

    def format(self, text) -> str:
        return f"{self.value}{text}{self.ENDC.value}"


class Severities(Enum):
    critical = 1
    high = 2
    medium = 3
    low = 4
    lowest = 5

    @classmethod
    def from_txt(cls, txt):
        return cls(int(txt[0]))

    def __str__(self):
        return f"{self.value}-{self.name}"


def format_severity(severity: Severities) -> str:
    if severity.value < 3:
        return Colors.FAIL.format(severity)
    return str(severity)


def download(search: str, severity_mini: int) -> list:
    search = f"&search={search}" if search else ""
    url = f"https://gitlab.archlinux.org/api/v4/groups/11323/issues?scope=all&sort=desc{search}&order_by=created_at&state=opened&per_page=100&page=1&labels=scope::bug"
    # url = url + ",severity::1-critical,severity::2-high,severity::3-medium" # TODO ?
    hdr = {"PRIVATE-TOKEN": TOKEN, "User-Agent": "Arch-issues/1.0 (archlinux; Linux)"}
    req = request.Request(url, headers=hdr)
    try:
        with request.urlopen(req) as response:
            return json.loads(response.read())
    except (error.HTTPError, error.URLError) as err:
        print("Web error:", err)
    return []


def get_package_name(url: str) -> str:
    url = url.removeprefix("https://gitlab.archlinux.org/archlinux/packaging/packages/")
    return url.split("/", maxsplit=2)[0]


def get_labels(labels: list):
    ret = ['', '']
    for label in labels:
        if label.startswith("severity::"):
            ret[0] = Severities.from_txt(label[10:])
        elif label.startswith("status::"):
            ret[1] = label[8:]
    return ret[0], ret[1]


if __name__ == "__main__":

    parser = argparse.ArgumentParser(
                    prog="arch-issues",
                    description="Archlinux bugtracker",
                    epilog="Positional argument = text to search",
    )
    # -s , -c : only for dev
    parser.add_argument("-s", "--save", action="store_true", help="Save in cache", default=False)
    parser.add_argument("-c", "--cache", action="store_true", help="Use cache", default=False)
    parser.add_argument("-p", type=int, choices=[x.value for x in Severities], default=Severities.lowest.value, help="Minimum severity (default: lowest)")
    args, search = parser.parse_known_args()
    search = " ".join(search)

    datas = []
    # exit(0)

    if not args.cache:
        datas = download(search, args.p)
    else:
        with open("arch.issues.json") as fjson:
            datas = json.load(fjson)

    if not datas:
        exit(2)

    if args.save:
        with open("arch.issues.json", "w") as fjson:
            fjson.write(json.dumps(datas, indent=2))

    for item in reversed(datas):
        severity, status = get_labels(item['labels'])
        if severity.value > args.p:
            continue
        print()
        severity = format_severity(severity)
        nb_assign = len(item['assignees'])
        nb_assign = f"{nb_assign}" if nb_assign > 0 else ''
        # `user_notes_count` == messages in issue
        print(
            f"{Colors.BOLD.format(get_package_name(item['web_url']))}:",
            f"{Colors.BLUE.format(item['title'])}",
            f"\t{item['created_at'][0:10]}",
            f" ({nb_assign}) ({item['user_notes_count'] if item['user_notes_count'] else ''})"
        )
        print(f"  {severity} {status}")
        print(f"  {Colors.GRAY.format(item['web_url'])}")

    print()
Arch stable - Kde 5 / zsh - btrfs/mbr - Intel Core i3 - 6Go RAM - GeForce 405 video-nouveau
Répondre