Skip to content

Commit

Permalink
Python quality improvements
Browse files Browse the repository at this point in the history
- mypy --strict (1.11.0)
- isort --profile black (5.13.2)
- ruff check (0.5.5)
- flake8 (7.1.0)
- black  (24.3.0)
  • Loading branch information
oh2fih committed Jul 30, 2024
1 parent 2107fe5 commit a82d7e0
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 38 deletions.
41 changes: 20 additions & 21 deletions bin/follow-cvelist.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@
import json
import os
import re
import sys
import signal
import subprocess
import sys
import time
from pathlib import Path
from typing import List, Dict
from typing import Any, Dict, List


def main(args: argparse.Namespace):
def main(args: argparse.Namespace) -> None:
cvelist = CvelistFollower(args)
cvelist.header()
cvelist.pull()
Expand Down Expand Up @@ -76,11 +76,11 @@ def __init__(self, args: argparse.Namespace):
)
exit(1)

def interrupt_handler(self, signum, frame):
def interrupt_handler(self, signum: Any, frame: Any) -> None:
"""Tells that an interrupt signal is received through variable INTERRUPT"""
self.INTERRUPT = signum

def check_interrupt(self):
def check_interrupt(self) -> None:
"""Exits if interrupt is received"""
if self.INTERRUPT:
print(
Expand All @@ -89,7 +89,7 @@ def check_interrupt(self):
)
sys.exit(0)

def header(self):
def header(self) -> None:
"""Print header"""
if self.args.cvss4:
cvss_title = "CVSS 4.0"
Expand All @@ -111,7 +111,7 @@ def header(self):
except OSError:
print(f"{''.ljust(80, '-')}", file=sys.stderr)

def history(self):
def history(self) -> None:
"""Prints CVE changes from the commit history, one commit at a time"""
history = self.args.commits
try:
Expand All @@ -132,7 +132,7 @@ def history(self):
cursor = new_cursor
self.check_interrupt()

def monitor(self):
def monitor(self) -> None:
"""Monitors new cvelistV5 commits and prints changed CVEs"""
cursor = self.get_cursor()

Expand All @@ -148,7 +148,7 @@ def monitor(self):
self.print_changes(new_cursor, cursor)
cursor = new_cursor

def pull(self):
def pull(self) -> None:
"""Runs git pull"""
if self.args.verbose > 1:
result = subprocess.run(
Expand All @@ -171,7 +171,7 @@ def get_cursor(self, offset: int = 0) -> str:
raise IndexError(f"Commit at HEAD~{offset} not found")
return result.stdout.decode("utf-8").strip()

def print_changes(self, current_commit: str, past_commit: str):
def print_changes(self, current_commit: str, past_commit: str) -> None:
"""Print summary of changed CVE"""
lines = []
try:
Expand Down Expand Up @@ -200,17 +200,16 @@ def get_changes(
changes = []
for file in self.changed_files(current_commit, past_commit):
type = re.split(r"\t+", file.decode("utf-8").strip())[0]
path = re.split(r"\t+", file.decode("utf-8").strip())[1]
path = Path(re.split(r"\t+", file.decode("utf-8").strip())[1])

if type == "D":
if self.args.ansi:
print(
f"{ANSI.code('red')}Deleted: "
f"{Path(path).stem}{ANSI.code('end')}",
f"{ANSI.code('red')}Deleted: " f"{path.stem}{ANSI.code('end')}",
file=sys.stderr,
)
else:
print(f"Deleted: {Path(path).stem}", file=sys.stderr)
print(f"Deleted: {path.stem}", file=sys.stderr)
continue

try:
Expand Down Expand Up @@ -260,7 +259,7 @@ def get_changes(
changes.append(change)
return changes

def format_line(self, line) -> str:
def format_line(self, line: Dict[str, Any]) -> str:
"""Format a line based on the selected modes"""
modified = line["modified"]

Expand Down Expand Up @@ -318,7 +317,7 @@ def format_line(self, line) -> str:
f"{cvss.ljust(10)} {line['summary']}"
)

def cvss31score(self, cve: dict) -> float:
def cvss31score(self, cve: Dict[str, Any]) -> float:
"""Gets CVSS 3.1 Score. If present in both containers, take higher"""
cvss_adp = 0.0
try:
Expand Down Expand Up @@ -349,7 +348,7 @@ def cvss31score(self, cve: dict) -> float:
cvss = max(cvss_adp, cvss_cna)
return float("%0.1f" % cvss)

def cvss40score(self, cve: dict) -> float:
def cvss40score(self, cve: Dict[str, Any]) -> float:
"""Gets CVSS 4.0 Score; only available in the cna container"""
cvss_cna = 0.0
try:
Expand All @@ -365,7 +364,7 @@ def cvss40score(self, cve: dict) -> float:
pass
return float("%0.1f" % cvss_cna)

def generate_summary(self, cve: dict) -> str:
def generate_summary(self, cve: Dict[str, Any]) -> str:
"""Generates summary from title or description & affected vendor/product"""
title = ""
description = ""
Expand Down Expand Up @@ -427,7 +426,7 @@ def generate_summary(self, cve: dict) -> str:
else:
return title

def changed_files(self, current_commit: str, past_commit: str) -> list:
def changed_files(self, current_commit: str, past_commit: str) -> List[bytes]:
"""List cve files changed between two commits; ignore delta files"""
result = subprocess.Popen(
[
Expand All @@ -446,7 +445,7 @@ def changed_files(self, current_commit: str, past_commit: str) -> list:
else:
return []

def json_at_commit(self, path: Path, commit: str) -> dict:
def json_at_commit(self, path: Path, commit: str) -> Any:
"""Dictionary of JSON file contents at given commit"""
try:
result = subprocess.run(
Expand All @@ -462,7 +461,7 @@ def json_at_commit(self, path: Path, commit: str) -> dict:
print(f"Could not parse {commit}:{path}", file=sys.stderr)
return {}

def cvelist_repo(self):
def cvelist_repo(self) -> bool:
"""Detects whether the working directory is the root of CVEProject/cvelistV5"""
try:
result = subprocess.run(
Expand Down
13 changes: 7 additions & 6 deletions bin/make-mac-prefixes.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@
# ------------------------------------------------------------------------------
# flake8: noqa: E501

import sys
import os
import csv
import os
import re
import sys
from typing import List, TextIO

# Sort the list by MAC prefix: True = sort, False = preserve original order.
SORT = False
Expand All @@ -38,7 +39,7 @@
]


def main(csvdata):
def main(csvdata: TextIO) -> List[str]:
"""Return processed (and optionally sorted) OUIs with ADDITIONS"""
OUIs = []

Expand Down Expand Up @@ -68,7 +69,7 @@ def main(csvdata):
return OUIs


def decapitalize(string):
def decapitalize(string: str) -> str:
"""Un-capitalize an all-caps company name"""
decapitalized = ""
words = string.split()
Expand All @@ -87,7 +88,7 @@ def decapitalize(string):
return decapitalized


def shorten(string):
def shorten(string: str) -> str:
"""Rules to shorten the names a bit, such as eliminating Inc."""
string = re.sub(r",.{1,6}$", "", string)
string = re.sub(
Expand All @@ -100,7 +101,7 @@ def shorten(string):
return string


def validatePrefix(prefix):
def validatePrefix(prefix: str) -> bool:
"""Validates a MAC prefix: must consist of six hexadecimal characters"""
if re.match(r"^([0-9a-fA-F]{6})$", prefix):
return True
Expand Down
25 changes: 14 additions & 11 deletions bin/test-cache-enabler.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,23 @@
# ------------------------------------------------------------------------------
# flake8: noqa: E501

import sys
import re
import os
import re
import sys
import urllib.request
from typing import List

try:
import validators # type: ignore
except ImportError:

class validators: # type: ignore
def url(url):
@staticmethod
def url(url: str) -> bool:
return True


def main(urllist):
def main(urllist: List[str]) -> None:
"""Causes the pages to be cached, gets them and prints the results as a table."""

# Enable ANSI colors on Windows.
Expand Down Expand Up @@ -69,29 +71,30 @@ def main(urllist):
print()


def getCacheTime(page):
def getCacheTime(page: bytes) -> str:
"""Parses the cache time from the Cache Enabler comment on a HTML page."""
try:
cached = re.search(b"<!-- Cache Enabler by KeyCDN (.*) -->", page).group(1)
result = re.search(b"<!-- Cache Enabler by KeyCDN (.*) -->", page)
if result:
cached = result.group(1)
return cached.decode("utf-8")
except AttributeError:
else:
return "Not cached."


def printResultLine(url, result, urlmaxlenght, SGR):
def printResultLine(url: str, result: str, urlmaxlenght: int, SGR: int) -> None:
"""Prints table formatted result line & ANSI colors."""
width = urlmaxlenght + 2
print(f"{url:{width}}{ansi(SGR)}{result:<10}{ansi(0)}")


def ansi(SGR=0):
def ansi(SGR: int = 0) -> str:
"""Returns ANSI codes used in this script. SGR = Select Graphic Rendition"""
if not isinstance(SGR, int):
SGR = 0
return f"\033[{SGR}m"


def usage():
def usage() -> None:
print(f"{os.linesep}Usage: {sys.argv[0]} https://example.com [...]")
print(f"{os.linesep}Also takes line break separated URLs from a pipe.{os.linesep}")
exit(1)
Expand Down

0 comments on commit a82d7e0

Please sign in to comment.