-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate_java_version_consistency.py
More file actions
200 lines (155 loc) · 6.1 KB
/
validate_java_version_consistency.py
File metadata and controls
200 lines (155 loc) · 6.1 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import os
import re
import subprocess
import sys
def normalize_java_version(value):
if not value:
return None
cleaned = value.strip().strip('"\'')
if not cleaned or cleaned.startswith('${'):
return None
cleaned = cleaned.replace('JavaVersion.VERSION_', '')
if cleaned.startswith('1.'):
parts = cleaned.split('.')
if len(parts) > 1 and parts[1].isdigit():
return parts[1]
match = re.search(r'(\d+)', cleaned)
if match:
return str(int(match.group(1)))
return None
def extract_java_version_from_docker_tag(tag):
patterns = (
r'(?:^|[._-])(\d+)(?:[._-])java(?:[._-])(jre|jdk)(?:$|[._-])',
r'(?:^|[._-])java(?:[._-])(\d+)(?:$|[._-])',
r'(?:^|[._-])(\d+)(?:[._-])(jre|jdk)(?:$|[._-])',
r'^(\d+)$',
)
for pattern in patterns:
match = re.search(pattern, tag, re.IGNORECASE)
if match:
return normalize_java_version(match.group(1))
return None
def resolve_args(value, args):
def replace(match):
variable_name = match.group(1) or match.group(2)
return args.get(variable_name, match.group(0))
return re.sub(r'\$\{([^}]+)\}|\$(\w+)', replace, value)
def parse_docker_java_version(dockerfile_path):
args = {}
images = []
with open(dockerfile_path, encoding='utf-8') as dockerfile:
for raw_line in dockerfile:
line = raw_line.split('#', 1)[0].strip()
if not line:
continue
arg_match = re.match(r'^ARG\s+([A-Za-z_][A-Za-z0-9_]*)=(.+)$', line, re.IGNORECASE)
if arg_match:
args[arg_match.group(1)] = arg_match.group(2).strip()
continue
from_match = re.match(r'^FROM\s+([^\s]+)', line, re.IGNORECASE)
if from_match:
image = resolve_args(from_match.group(1).strip(), args)
images.append(image)
runtime_images = [image for image in images if image.lower() != 'scratch']
if not runtime_images:
raise RuntimeError('Could not find a runtime image in Dockerfile.')
image_ref = runtime_images[-1].split('@', 1)[0]
last_slash = image_ref.rfind('/')
last_colon = image_ref.rfind(':')
if last_colon <= last_slash:
raise RuntimeError(f'Could not determine the Java tag from Docker image "{image_ref}".')
tag = image_ref[last_colon + 1 :]
java_version = extract_java_version_from_docker_tag(tag)
if not java_version:
raise RuntimeError(
'Could not determine the Java version from Docker tag '
f'"{tag}". Expected a tag like "25", "25-jdk", or "1.0.2-25-java-jre".'
)
return java_version, image_ref
def evaluate_maven_property(expression):
result = subprocess.run(
[
'mvn',
'-q',
'-DforceStdout',
'-Dstyle.color=never',
'help:evaluate',
f'-Dexpression={expression}',
],
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
return None
lines = [line.strip() for line in result.stdout.splitlines() if line.strip()]
lines = [line for line in lines if not line.startswith('[')]
return lines[-1] if lines else None
def parse_maven_java_version():
for expression in (
'maven.compiler.release',
'maven.compiler.target',
'java.version',
):
value = evaluate_maven_property(expression)
normalized = normalize_java_version(value)
if normalized:
return normalized, f'pom.xml ({expression}={value})'
raise RuntimeError(
'Could not determine the Java version from pom.xml. '
'Expected maven.compiler.release, maven.compiler.target, or java.version.'
)
def parse_gradle_java_version(gradle_path):
with open(gradle_path, encoding='utf-8') as gradle_file:
content = gradle_file.read()
patterns = [
r'jvmTarget\s*=\s*["\']([^"\']+)["\']',
r'jvmTarget\s*=\s*JavaVersion\.VERSION_?(\d+)',
r'languageVersion(?:\.set)?\s*\(?\s*JavaLanguageVersion\.of\((\d+)\)\s*\)?',
r'sourceCompatibility\s*=\s*JavaVersion\.VERSION_?(\d+)',
r'targetCompatibility\s*=\s*JavaVersion\.VERSION_?(\d+)',
]
for pattern in patterns:
match = re.search(pattern, content, re.MULTILINE | re.DOTALL)
if match:
value = match.group(1)
normalized = normalize_java_version(value)
if normalized:
return normalized, f'{os.path.basename(gradle_path)} ({value})'
raise RuntimeError(
'Could not determine the Java version from the Gradle build file. '
'Expected compileKotlin.kotlinOptions.jvmTarget or java.toolchain.languageVersion.'
)
def main():
dockerfile_path = os.path.join(os.getcwd(), 'Dockerfile')
if not os.path.exists(dockerfile_path):
raise RuntimeError(f'Dockerfile not found at {dockerfile_path}.')
docker_version, docker_image = parse_docker_java_version(dockerfile_path)
pom_path = os.path.join(os.getcwd(), 'pom.xml')
gradle_paths = [
os.path.join(os.getcwd(), 'build.gradle.kts'),
os.path.join(os.getcwd(), 'build.gradle'),
]
if os.path.exists(pom_path):
build_version, build_source = parse_maven_java_version()
else:
existing_gradle_paths = [path for path in gradle_paths if os.path.exists(path)]
if not existing_gradle_paths:
raise RuntimeError(
'Could not find pom.xml, build.gradle.kts, or build.gradle in the working directory.'
)
build_version, build_source = parse_gradle_java_version(existing_gradle_paths[0])
if docker_version != build_version:
print(
'Java version mismatch: '
f'Dockerfile uses Java {docker_version} ({docker_image}), '
f'but {build_source} resolves to Java {build_version}.',
file=sys.stderr,
)
sys.exit(1)
print(
'Java version check passed: '
f'Dockerfile uses Java {docker_version} and {build_source} matches.'
)
if __name__ == '__main__':
main()