diff --git a/bin/follow-cvelist.py b/bin/follow-cvelist.py index a934738..ffe8578 100755 --- a/bin/follow-cvelist.py +++ b/bin/follow-cvelist.py @@ -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() @@ -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( @@ -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" @@ -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: @@ -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() @@ -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( @@ -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: @@ -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: @@ -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"] @@ -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: @@ -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: @@ -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 = "" @@ -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( [ @@ -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( @@ -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( diff --git a/bin/make-mac-prefixes.py b/bin/make-mac-prefixes.py index 0550290..74e3bd5 100755 --- a/bin/make-mac-prefixes.py +++ b/bin/make-mac-prefixes.py @@ -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 @@ -38,7 +39,7 @@ ] -def main(csvdata): +def main(csvdata: TextIO) -> List[str]: """Return processed (and optionally sorted) OUIs with ADDITIONS""" OUIs = [] @@ -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() @@ -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( @@ -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 diff --git a/bin/test-cache-enabler.py b/bin/test-cache-enabler.py index 6e5fb8b..0cac021 100755 --- a/bin/test-cache-enabler.py +++ b/bin/test-cache-enabler.py @@ -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. @@ -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"", page).group(1) + result = re.search(b"", 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)