Skip to content

Commit aa3824d

Browse files
committed
added remove_jdks.py
1 parent 62001df commit aa3824d

File tree

3 files changed

+125
-59
lines changed

3 files changed

+125
-59
lines changed

mx.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18446,7 +18446,7 @@ def alarm_handler(signum, frame):
1844618446
abort(1, killsig=signal.SIGINT)
1844718447

1844818448
# The version must be updated for every PR (checked in CI) and the comment should reflect the PR's issue
18449-
version = VersionSpec("6.23.7") # GR-45977: Add --deferred-tty option to mx benchmark to print output only at the end of the command.
18449+
version = VersionSpec("6.23.8") # GR-46197 - add remove_jdks.py
1845018450

1845118451
currentUmask = None
1845218452
_mx_start_datetime = datetime.utcnow()

remove_jdks.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#!/usr/bin/env python3
2+
# ----------------------------------------------------------------------------------------------------
3+
#
4+
# Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
5+
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
6+
#
7+
# This code is free software; you can redistribute it and/or modify it
8+
# under the terms of the GNU General Public License version 2 only, as
9+
# published by the Free Software Foundation.
10+
#
11+
# This code is distributed in the hope that it will be useful, but WITHOUT
12+
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13+
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14+
# version 2 for more details (a copy is included in the LICENSE file that
15+
# accompanied this code).
16+
#
17+
# You should have received a copy of the GNU General Public License version
18+
# 2 along with this work; if not, write to the Free Software Foundation,
19+
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20+
#
21+
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22+
# or visit www.oracle.com if you need additional information or have any
23+
# questions.
24+
#
25+
# ----------------------------------------------------------------------------------------------------
26+
27+
from argparse import ArgumentParser
28+
import os, shutil
29+
import select_jdk
30+
31+
if __name__ == '__main__':
32+
parser = ArgumentParser(prog='remove_jdks', usage='%(prog)s [options]' + """
33+
Removes JDKs available to the select_jdk command.""")
34+
35+
parser.add_argument('-f', '--force', action='store_true', help='remove selected JDKs without confirmation')
36+
args = parser.parse_args()
37+
38+
jdks = select_jdk.choose_jdks()
39+
if jdks:
40+
for jdk in jdks:
41+
jdk_base = jdk.java_home
42+
if jdk_base.endswith('/Contents/Home'):
43+
jdk_base = jdk_base[0:-len('/Contents/Home')]
44+
if not args.force:
45+
answer = input(f'Remove {jdk_base}? [Yn]> ')
46+
if answer not in ('', 'Y', 'y'):
47+
continue
48+
tmp_jdk_base = f'{jdk_base}.{os.getpid()}'
49+
try:
50+
# Move the directory to a new name to make the
51+
# removal as atomic as possible from the perspective
52+
# of other processes.
53+
os.rename(jdk_base, tmp_jdk_base)
54+
except OSError as e:
55+
print(e)
56+
continue
57+
print(f'Removing {jdk_base}... ', end='')
58+
shutil.rmtree(tmp_jdk_base)
59+
print(' done')

select_jdk.py

Lines changed: 65 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#!/usr/bin/env python3
22
# ----------------------------------------------------------------------------------------------------
33
#
4-
# Copyright (c) 2018, 2018, Oracle and/or its affiliates. All rights reserved.
4+
# Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved.
55
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
66
#
77
# This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,8 @@
2929
from os.path import exists, expanduser, join, isdir, isfile, realpath, dirname, abspath, basename, getmtime
3030
from io import StringIO
3131

32+
default_jdk_cache_path = join(expanduser('~'), '.mx', 'jdk_cache')
33+
3234
def is_valid_jdk(jdk):
3335
"""
3436
Determines if `jdk` looks like a valid JDK directory.
@@ -243,6 +245,64 @@ def sort_key(self):
243245
def __lt__(self, other):
244246
return self.sort_key() < other.sort_key()
245247

248+
def choose_jdks(jdk_cache_path=default_jdk_cache_path, only_list=False):
249+
jdks = {}
250+
if exists(jdk_cache_path):
251+
with open(jdk_cache_path) as fp:
252+
line_num = 1
253+
for line in fp.readlines():
254+
jdk = JDKInfo.load_from_jdk_cache(line.strip(), jdk_cache_path, line_num)
255+
line_num += 1
256+
if jdk:
257+
jdks[jdk.java_home] = jdk
258+
base_dir = dirname(jdk.java_home)
259+
if base_dir.endswith('/Contents/Home'):
260+
base_dir = base_dir[0:-len('/Contents/Home')]
261+
for java_home in find_jdks_in(base_dir):
262+
if java_home not in jdks:
263+
jdks[java_home] = JDKInfo.for_java_home(java_home)
264+
for java_home in find_system_jdks():
265+
if java_home not in jdks:
266+
jdks[java_home] = JDKInfo.for_java_home(java_home)
267+
268+
sorted_jdks = sorted(jdks.values())
269+
choices = list(enumerate(sorted_jdks))
270+
col2_width = max(((len(jdk.name + '-' + jdk.java_specification_version)) for jdk in sorted_jdks)) + 1
271+
col3_width = max(((len(jdk.java_vm_version)) for jdk in sorted_jdks)) + 1
272+
if choices:
273+
tmp_cache_path_fd, tmp_cache_path = tempfile.mkstemp(dir=dirname(jdk_cache_path))
274+
# Windows will complain about tmp_cache_path being in use by another process
275+
# when calling os.rename if we don't close the file descriptor.
276+
os.close(tmp_cache_path_fd)
277+
278+
java_home = os.environ.get('JAVA_HOME', '')
279+
extra_java_homes = os.environ.get('EXTRA_JAVA_HOMES', '').split(os.pathsep)
280+
with open(tmp_cache_path, 'w') as fp:
281+
for index, jdk in choices:
282+
col1 = f'[{index}]'
283+
col2 = f'{jdk.name}-{jdk.java_specification_version}'
284+
col3 = jdk.java_vm_version
285+
col4 = jdk.java_home
286+
if only_list:
287+
print(f'{col2:{col2_width}} {col3:{col3_width}} {col4}')
288+
else:
289+
line = f'{col1:>5} {col2:{col2_width}} {col3:{col3_width}} {col4}'
290+
if jdk.java_home == java_home:
291+
line = colorize(f'{line} {{JAVA_HOME}}', 'green')
292+
elif jdk.java_home in extra_java_homes:
293+
line = colorize(f'{line} {{EXTRA_JAVA_HOMES[{extra_java_homes.index(jdk.java_home)}]}}', 'cyan')
294+
print(line)
295+
print(f'{jdk.as_jdk_cache_line()}', file=fp)
296+
if only_list:
297+
os.unlink(tmp_cache_path)
298+
else:
299+
os.unlink(jdk_cache_path)
300+
os.rename(tmp_cache_path, jdk_cache_path)
301+
choices = {str(index):jdk for index, jdk in choices}
302+
jdks = [choices[n] for n in input('Select JDK(s) (separate multiple choices by whitespace)> ').split() if n in choices]
303+
if jdks:
304+
return jdks
305+
246306
if __name__ == '__main__':
247307
parser = ArgumentParser(prog='select_jdk', usage='%(prog)s [options] [<primary jdk> [<secondary jdk>...]]' + """
248308
Selects values for the JAVA_HOME, EXTRA_JAVA_HOMES and PATH environment variables based on
@@ -297,7 +357,7 @@ def __lt__(self, other):
297357
else:
298358
args.shell = 'sh'
299359

300-
jdk_cache_path = join(expanduser('~'), '.mx', 'jdk_cache')
360+
jdk_cache_path = default_jdk_cache_path
301361
if len(args.jdks) != 0:
302362
if args.list:
303363
print('warning: ignore --list option since JDKs were specified on the command line')
@@ -313,59 +373,6 @@ def __lt__(self, other):
313373
print(f'{jdk.as_jdk_cache_line()}', file=fp)
314374
apply_selection(args, abspath(args.jdks[0]), [abspath(a) for a in args.jdks[1:]])
315375
else:
316-
jdks = {}
317-
if exists(jdk_cache_path):
318-
with open(jdk_cache_path) as fp:
319-
line_num = 1
320-
for line in fp.readlines():
321-
jdk = JDKInfo.load_from_jdk_cache(line.strip(), jdk_cache_path, line_num)
322-
line_num += 1
323-
if jdk:
324-
jdks[jdk.java_home] = jdk
325-
base_dir = dirname(jdk.java_home)
326-
if base_dir.endswith('/Contents/Home'):
327-
base_dir = base_dir[0:-len('/Contents/Home')]
328-
for java_home in find_jdks_in(base_dir):
329-
if java_home not in jdks:
330-
jdks[java_home] = JDKInfo.for_java_home(java_home)
331-
for java_home in find_system_jdks():
332-
if java_home not in jdks:
333-
jdks[java_home] = JDKInfo.for_java_home(java_home)
334-
335-
sorted_jdks = sorted(jdks.values())
336-
choices = list(enumerate(sorted_jdks))
337-
col2_width = max(((len(jdk.name + '-' + jdk.java_specification_version)) for jdk in sorted_jdks)) + 1
338-
col3_width = max(((len(jdk.java_vm_version)) for jdk in sorted_jdks)) + 1
339-
if choices:
340-
tmp_cache_path_fd, tmp_cache_path = tempfile.mkstemp(dir=dirname(jdk_cache_path))
341-
# Windows will complain about tmp_cache_path being in use by another process
342-
# when calling os.rename if we don't close the file descriptor.
343-
os.close(tmp_cache_path_fd)
344-
345-
java_home = os.environ.get('JAVA_HOME', '')
346-
extra_java_homes = os.environ.get('EXTRA_JAVA_HOMES', '').split(os.pathsep)
347-
with open(tmp_cache_path, 'w') as fp:
348-
for index, jdk in choices:
349-
col1 = f'[{index}]'
350-
col2 = f'{jdk.name}-{jdk.java_specification_version}'
351-
col3 = jdk.java_vm_version
352-
col4 = jdk.java_home
353-
if args.list:
354-
print(f'{col2:{col2_width}} {col3:{col3_width}} {col4}')
355-
else:
356-
line = f'{col1:>5} {col2:{col2_width}} {col3:{col3_width}} {col4}'
357-
if jdk.java_home == java_home:
358-
line = colorize(f'{line} {{JAVA_HOME}}', 'green')
359-
elif jdk.java_home in extra_java_homes:
360-
line = colorize(f'{line} {{EXTRA_JAVA_HOMES[{extra_java_homes.index(jdk.java_home)}]}}', 'cyan')
361-
print(line)
362-
print(f'{jdk.as_jdk_cache_line()}', file=fp)
363-
if args.list:
364-
os.unlink(tmp_cache_path)
365-
else:
366-
os.unlink(jdk_cache_path)
367-
os.rename(tmp_cache_path, jdk_cache_path)
368-
choices = {str(index):jdk for index, jdk in choices}
369-
jdks = [choices[n] for n in input('Select JDK(s) (separate multiple choices by whitespace)> ').split() if n in choices]
370-
if jdks:
371-
apply_selection(args, jdks[0].java_home, [jdk.java_home for jdk in jdks[1:]])
376+
jdks = choose_jdks(jdk_cache_path, args.list)
377+
if jdks:
378+
apply_selection(args, jdks[0].java_home, [jdk.java_home for jdk in jdks[1:]])

0 commit comments

Comments
 (0)