-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathversion_parser.py
More file actions
49 lines (36 loc) · 1.5 KB
/
Copy pathversion_parser.py
File metadata and controls
49 lines (36 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
"""Helpers for extracting a clean version string from raw command output.
Different tools print their version in different formats, e.g.:
"Python 3.12.4"
"git version 2.46.0"
"npm 10.8.2"
"openjdk 21.0.4 2024-07-16"
This module tries to pull a dotted version number out of that text, and
falls back gracefully when no clear version number can be found.
"""
import re
from typing import Optional
# Matches version-looking numbers such as 3.12, 3.12.4, or 3.12.4-beta1.
VERSION_PATTERN = re.compile(r"(\d+\.\d+(?:\.\d+)*(?:[-_][A-Za-z0-9]+)?)")
def extract_version(raw_output: Optional[str]) -> Optional[str]:
"""Extract a version number from raw command output.
Returns None if raw_output is empty/None. If no dotted version number is
found, the first non-empty line of output is returned instead, so the
caller still has something informative to show.
"""
if not raw_output:
return None
cleaned = raw_output.strip()
if not cleaned:
return None
match = VERSION_PATTERN.search(cleaned)
if match:
return match.group(1)
first_line = cleaned.splitlines()[0].strip()
return first_line if first_line else None
def clean_output(stdout: str, stderr: str) -> str:
"""Combine stdout and stderr into a single trimmed string.
Some tools (notably older Java versions) print version information to
stderr instead of stdout, so both streams are checked.
"""
combined = (stdout or "") + "\n" + (stderr or "")
return combined.strip()