aboutsummaryrefslogtreecommitdiff
blob: 8ad253997c69086985bd33a3333d712954ceb0cd (plain)
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
#!/@GENTOO_PORTAGE_EPREFIX@usr/bin/python -E
# -*- coding: UTF-8 -*-

# Copyright 2004-2013 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: $

from java_config_2.OutputFormatter import OutputFormatter
from java_config_2.EnvironmentManager import EnvironmentManager
from java_config_2.Errors import *

import os
import sys
try:
    # Python 3.
    from subprocess import getoutput
except ImportError:
    # Python 2.
    from commands import getoutput

from optparse import OptionParser, OptionGroup

def version(option, opt, value, parser):
    printer._print("%H%BJava Configuration Utility %GVersion @PACKAGE_VERSION@")
    raise SystemExit()

def nocolor(option, opt, value, parser):
    printer.setColorOutputStatus(False)

def get_command(command):
    try:
        printer._print(manager.get_active_vm().find_exec(command))
    except PermissionError:
        fatalError("The " + command + " executable was not found in the Java path")

def java(option, opt, value, parser):
    get_command('java')

def javac(option, opt, value, parser):
    get_command('javac')

def jar(option, opt, value, parser):
    get_command('jar')

def query_active_vm(var):
    try:
        printer._print(manager.get_active_vm().query(var))
    except EnvironmentUndefinedError:
        fatalError("%s could not be found in the active VM environment" % var)

def query_active_vm_cb(option, opt, value, parse, *args):
    return query_active_vm(args[0])

def tools(option, opt, value, parser):
    jh = ''
    try:
        jh = manager.get_active_vm().query('JAVA_HOME')
    except EnvironmentUndefinedError:
        fatalError("JAVA_HOME not found in the active VM environment")
    tools_jar = jh + '/lib/tools.jar'
    if os.path.exists(tools_jar):
        printer._print(tools_jar)
    else:
        sys.exit(1);

def show_active_vm(option, opt, value, parser):
    printer._print(manager.get_active_vm().name())

def java_version(option, opt, value, parser):
    try:
        printer._print(getoutput('%s -version' % manager.get_active_vm().find_exec('java')))
    except PermissionError:
        fatalError("The java executable was not found in the Java path")

def query_pkg_path(option, opt, value, parser, query):
    error = False
    try:
        packages = value.split(',')
        missing_deps = set()
        if not parser.values.with_deps:
            path = manager.build_path(packages, query)
        else:
            path = manager.build_dep_path(packages, query, missing_deps)

        printer._print(':'.join(path))

        if len(missing_deps) > 0:
            for dep in missing_deps:
                printer._printError("Dependency package %s was not found!" % dep)
            error = True

    except UnexistingPackageError as e:
        printer._printError("Package %s was not found!" % e.package)
        error = True

    if error:
        sys.exit(1)

def query_pkg(option, opt, value, parser):
    error = False
    query = parser.values.query
    if query:
        try:
            package = manager.get_package(value)
            if package.query(query):
                printer._print(package.query(query))
            else:
                printer._printError('Package %s does not define %s in it\'s package.env.' % (package.name(), query))
        except UnexistingPackageError as e:
            printer._printError("Package %s was not found!" % e.package)
        except PermissionError as e:
            printer._printError("You do not have enough permissions to read the package's package.env")
            error = True
    else:
        printer._printError("No query parameter was specified, unable to retrieve package.env value.")
        error = True

    if error:
        sys.exit(1)

def get_virtual_providers( option, opt, value, parser):
    if manager.get_virtual(value):
        output = manager.get_virtual(value).get_packages()
        printer._print(','.join(output))
    else:
        printer._printError("Virtual package %s was not found" % value)
        sys.exit(1)

def get_env(option, opt, value, parser):
    for env in value.split(','):
        query_active_vm(env)

def exec_cmd(option, opt, value, parser):
    for cmd in iter(value.split(',')):
        os.system(cmd)

def list_available_packages(option, opt, value, parser):
    for package in manager.get_packages().values():
        printer._print("[%s] %s (%s)" % (package.name(), package.description(), package.file()))

def list_available_vms(option, opt, value, parser):
    vm_list = manager.get_virtual_machines()
    try:
        active = manager.get_active_vm()
    except InvalidVMError:
        active = None

    found_build_only = False
    printer._print('%HThe following VMs are available for generation-2:%$')
    for i, vm in vm_list.items():
        if vm is active:
            if not vm.is_build_only():
                printer._print('%G' + '*)\t%s [%s]%s' % (vm.query('VERSION'), vm.name(), '%$'))
            else:
                printer._print('%G' + '*)\t%s [%s]%s' % (vm.query('VERSION'), vm.name(), '%$') + '%r (Build Only)%$')
                found_build_only = True
        else:
            if not vm.is_build_only():
                printer._print('%i)\t%s [%s]' % (i, vm.query('VERSION'), vm.name()))
            else:
                printer._print('%i)\t%s [%s]' % (i, vm.query('VERSION'), vm.name()) + '%r (Build Only)%$')
                found_build_only = True

    if (found_build_only):
        printer._print('')
        printer._print('%r' + 'VMs marked as Build Only may contain Security Vulnerabilities and/or be EOL.')
        printer._print('%r' + 'Gentoo recommends not setting these VMs as either your System or User VM.')
        printer._print('%r' + 'Please see http://www.gentoo.org/doc/en/java.xml#build-only for more information')

def print_environment(option, opt, value, parser):
    vm = manager.get_vm(value) 
    if vm:
        manager.create_env_entry(vm, printer, "%s=%s")
    else:
        fatalError("Could not find a vm matching: %s" % value)

def set_system_vm(option, opt, value, parser):
    vm = manager.get_vm(value)

    if not vm:
        fatalError("Could not find a vm matching: %s" % value)
    else:
        try:
            manager.set_system_vm(vm)
            printer._print("Now using %s as your generation-2 system JVM" % (vm) )
            if vm.is_build_only():
                printer._printWarning("%s is marked as a build-only JVM. Using this vm is not recommended. " % (vm))
                printer._printWarning("Please see http://www.gentoo.org/doc/en/java.xml#build-only for more information.")
        except PermissionError:
            fatalError("You do not have enough permissions to set the system VM!")
        except EnvironmentUndefinedError:
            fatalError("The selected VM is missing critical environment variables.")
        except InvalidConfigError as e:
            fatalError("Target file already exists and is not a symlink: %s" % e.file)

def set_user_vm(option, opt, value, parser):
    vm = manager.get_vm(value)

    if not vm:
        fatalError("Could not find a vm matching: %s" % value)
    else:
        if os.getuid() is 0:
            fatalError("The user 'root' should always use the System VM")
        else:
            try:
                manager.set_user_vm(vm)
                printer._print("Now using %s as your user JVM" % (vm))
                if vm.is_build_only():
                    printer._printWarning("%s is marked as a build-only JVM. Using this vm is not recommended. " % (vm))
                    printer._printWarning("Please see http://www.gentoo.org/doc/en/java.xml#build-only for more information.")
            except PermissionError:
                fatalError("You do not have enough permissions to set the VM!")
            except InvalidConfigError as e:
                fatalError("Target file already exists and is not a symlink: %s" % e.file)

# Deprecated
def system_classpath_target():
    # TODO: MAKE THIS MODULAR!! (compnerd)
    return [{'file': manager.eprefix + '/etc/env.d/21java-classpath', 'format': '%s=%s\n' }]

def user_classpath_target():
    # TODO: MAKE THIS MODULAR!! (compnerd)
    return [
            {'file': os.path.join(os.environ.get("HOME"), '.gentoo' + manager.eprefix + '/java-env-classpath'),     'format': 'export %s=%s\n' },
            {'file': os.path.join(os.environ.get("HOME"), '.gentoo' + manager.eprefix + '/java-env-classpath.csh'), 'format': 'setenv %s %s\n' }
        ]
# Deprecated
def set_system_classpath(option, opt, value, parser):
    deprecation_notice()
    if os.getuid() is 0:
        pkgs = value.split(',')
        manager.set_classpath(system_classpath_target(), pkgs)
        
        for package in pkgs:
            printer._printError("Package %s was not found!" % package)
            
        update_env()
    else:
       fatalError("You do not have enough permissions to set the system classpath!")

# Deprecated
def set_user_classpath(option, opt, value, parser):
    deprecation_notice()
    pkgs = value.split(',')
    manager.set_classpath(user_classpath_target(), pkgs)

    for package in pkgs:
        printer._printError("Package %s was not found!" % package)

    user_update_env()

# Deprecated
def append_system_classpath(option, opt, value, parser):
    deprecation_notice()
    if os.getuid() is 0:
        pkgs = value.split(',')
        manager.append_classpath(system_classpath_target(), pkgs)

        for package in pkgs:
            printer._printError("Package %s was not found!" % package)

        update_env()
    else:
        fatalError("You do not have enough permissioins to append to the system classpath!")

# Deprecated
def append_user_classpath(option, opt, value, parser):
    deprecation_notice()
    pkgs = value.split(',')
    manager.append_classpath(user_classpath_target(),  pkgs)

    for package in pkgs:
        printer._printError("Package %s was not found!" % package)

    user_update_env()

# Deprecated
def clean_system_classpath(option, opt, value, parser):
    deprecation_notice()
    if os.getuid() is 0:
        manager.clean_classpath(system_classpath_target())
        update_env()
    else:
        fatalError("You do not have enough permissions to clean the system classpath!")

# Deprecated
def clean_user_classpath(option, opt, value, parser):
    deprecation_notice()
    manager.clean_classpath(user_classpath_target())

def select_vm(option, opt, value, parser):
    if value == '':
        return

    vm = manager.get_vm(value)
    if vm:
        manager.set_active_vm(manager.get_vm(value))
    else:
        fatalError("The vm could not be found")

def update_env():
    printer._print(getoutput(manager.eprefix + "/usr/sbin/env-update"))
    printer._printAlert("If you want the changes too take effect in your current session, you should update\n\
            your environment by running: source " + manager.eprefix + "/etc/profile")

def user_update_env():
    printer._printAlert("Environment files in ~/.gentoo" + manager.eprefix + "/ have been updated. You should source these from your shell's profile.\n\
            If you want the changes too take effect in your current sessiosn, you should resource these files")

def deprecation_notice():
    printer._printWarning("Setting a user and system classpath is deprecated, this option will be removed from future versions.")

def fatalError(msg):
    printer._printError(msg)
    sys.exit(1)

if __name__ == '__main__':
    global printer, manager
    printer = OutputFormatter(True, True)
    manager = EnvironmentManager(os.getenv('ROOT', ''), os.getenv('EPREFIX', '@GENTOO_PORTAGE_EPREFIX@'))

    usage =  "java-config [options]\n\n"
    usage += "Java Configuration Utility Version @PACKAGE_VERSION@\n"
    usage += "Copyright 2004-2013 Gentoo Foundation\n"
    usage += "Distributed under the terms of the GNU General Public License v2\n"
    usage += "Please contact the Gentoo Java Herd <java@gentoo.org> with problems."

    parser = OptionParser(usage)
    parser.add_option("-V", "--version",
                    action="callback", callback=version,
                    help="Print version information")
    parser.add_option("--select-vm",
                    action="callback", callback=select_vm,
                    type="string", dest="vm",
                    help="Use this vm instead of the active vm when returning information")
    parser.add_option("-n", "--nocolor",
                    action="callback", callback=nocolor,
                    help="Disable color output")

    # Queries
    group = OptionGroup(parser, "Queries")
    group.add_option("-J", "--java",
                    action="callback", callback=java,
                    help="Print the location of the java executable")
    group.add_option("-c", "--javac",
                    action="callback", callback=javac,
                    help="Print the location of the javac executable")
    group.add_option("-j", "--jar",
                    action="callback", callback=jar,
                    help="Print the location of the jar executable")
    group.add_option("-t", "--tools",
                    action="callback", callback=tools,
                    help="Print the path to tools.jar")
    group.add_option("-f", "--show-active-vm",
                    action="callback", callback=show_active_vm,
                    help="Print the active Virtual Machine")
    group.add_option("-v", "--java-version",
                    action="callback", callback=java_version,
                    help="Print version information for the active VM")
    group.add_option("-g", "--get-env",
                    action="callback", callback=get_env,
                    type="string", dest="var",
                    help="Print an environment variable from the active VM")
    group.add_option("-P", "--print",
                    action="callback", callback=print_environment,
                    type="string", dest="vm",
                    help="Print the environment for the specified VM")
    group.add_option("-e", "--exec_cmd",
                    action="callback", callback=exec_cmd,
                    type="string", dest="command",
                    help="Execute something which is in JAVA_HOME")
    group.add_option("-L", "--list-available-vms",
                    action="callback", callback=list_available_vms,
                    help="List available Java Virtual Machines")
    group.add_option("-l", "--list-available-packages",
                    action="callback", callback=list_available_packages,
                    help="List all available packages on the system.")
    group.add_option("-d", "--with-dependencies",
                    action="store_true",
                    default=False, dest="with_deps",
                    help="Include package dependencies in --classpath and --library calls")
    group.add_option("-p", "--classpath",
                    action="callback", callback=query_pkg_path, callback_args = ("CLASSPATH",),
                    type="string", dest="package(s)",
                    help="Print entries in the environment classpath for these packages")
    group.add_option("--package",
                    action="callback", callback=query_pkg,
                    type="string", dest="package(s)",
                    help="Retrieve a value from a packages package.env file, value is specified by --query")
    group.add_option("-q", "--query",
                    action="store",
                    type="string", dest="query",
                    help="Value to retieve from packages package.env file, specified by --package")
    group.add_option("-i", "--library",
                    action="callback", callback=query_pkg_path, callback_args = ("LIBRARY_PATH",),
                    type="string", dest="package(s)",
                    help="Print java library paths for these packages")
    group.add_option("-r", "--runtime",
                    action="callback", callback=query_active_vm_cb, callback_args=("BOOTCLASSPATH",),
                    help="Print the runtime classpath")
    group.add_option("-O", "--jdk-home",
                    action="callback", callback=query_active_vm_cb, callback_args=("JAVA_HOME",),
                    help="Print the location of the active JAVA_HOME")
    group.add_option("-o", "--jre-home",
                    action="callback", callback=query_active_vm_cb, callback_args=("JAVA_HOME",),
                    help="Print the location of the active JAVA_HOME")
    parser.add_option_group(group)

    # Experimental
    group = OptionGroup(parser, "Experimental")
    group.add_option("--get-virtual-providers",
                    action="callback", callback=get_virtual_providers,
                    type="string", dest="package(s)",
                    help="Return a list of packages that provide a virtual")
    parser.add_option_group(group)

    # Deprecated
    group = OptionGroup(parser, "Deprecated",
                        "Use eselect java-vm instead. Report usability issues "
                        "so they can be taken care of.")
    group.add_option("-S", "--set-system-vm",
                    action="callback", callback=set_system_vm,
                    type="string", dest="vm",
                    help="Set the default Java VM for the system")
    group.add_option("-s", "--set-user-vm",
                    action="callback", callback=set_user_vm,
                    type="string", dest="vm",
                    help="Set the default Java VM for the user")
    parser.add_option_group(group)

    # Doomed
    group = OptionGroup(parser, "TO BE REMOVED",
                        "Those options will soon be removed.")
    group.add_option("-A", "--set-system-classpath",
                    action="callback", callback=set_system_classpath,
                    type="string", dest="package(s)",
                    help="Set the system classpath to include the libraries")
    group.add_option("-B", "--append-system-classpath",
                    action="callback", callback=append_system_classpath,
                    type="string", dest="package(s)",
                    help="Append the libraries to the system classpath")
    group.add_option("-X", "--clean-system-classpath",
                    action="callback", callback=clean_system_classpath,
                    help="Clean the current system classpath")
    group.add_option("-a", "--set-user-classpath",
                    action="callback", callback=set_user_classpath,
                    type="string", dest="package(s)",
                    help="Set the user classpath to include the libraries")
    group.add_option("-b", "--append-user-classpath",
                    action="callback", callback=append_user_classpath,
                    type="string", dest="package(s)",
                    help="Append the libraries to the user classpath")
    group.add_option("-x", "--clean-user-classpath",
                    action="callback", callback=clean_user_classpath,
                    help="Clean the current user classpath")
    parser.add_option_group(group)

    if len(sys.argv) < 2: 
        parser.print_help()
    else:
        try:
            # Makes sure that --nocolor and --query are always 
            # the first argument(s)
            # because otherwise callbacks before it will output
            # colored output or --query param will not be set for
            # the query_pkg callback

            args = sys.argv[1:]
            for opt in ('-q', '--query'):
                try:
                    args.remove(opt)
                    args.insert(0, opt)
                except ValueError:
                    pass
            args = sys.argv[1:]
            for opt in ( '-n', '--nocolor'):
                try:
                    args.remove(opt)
                    args.insert(0,opt)
                except ValueError:
                    pass

            (options, args) = parser.parse_args(args=args)
        except InvalidVMError:
            fatalError("The active vm could not be found")
        except ProviderUnavailableError as e:
            message = "No providers are available, please ensure you have one of the following VM's or Package's;\n"
            message += "VM's (Your active vm must be one of these): " + e.vms() + "\n"
            message += "Packages's: " + e.packages() + "\n"
            fatalError(message)

# vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap: