1 /* 2 * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 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 package org.openjdk.jigsaw.cli; 27 28 import java.lang.module.*; 29 import java.io.*; 30 import java.net.*; 31 import java.nio.file.Files; 32 import java.nio.file.Path; 33 import java.nio.file.Paths; 34 import java.security.*; 35 import java.util.*; 36 37 import static java.lang.System.out; 38 import static java.lang.System.err; 39 40 import org.openjdk.jigsaw.*; 41 import org.openjdk.jigsaw.SimpleLibrary.StorageOption; 42 import org.openjdk.internal.joptsimple.*; 43 44 45 public class Librarian { 46 47 private static final JigsawModuleSystem jms 48 = JigsawModuleSystem.instance(); 49 50 private static final File homeLibrary = Library.systemLibraryPath(); 51 52 static class Create extends Command<SimpleLibrary> { 53 protected void go(SimpleLibrary lib) 54 throws Command.Exception 55 { 56 noDry(); 57 finishArgs(); 58 File lp = libPath(opts); 59 File pp = null; 60 if (opts.has(parentPath)) 61 pp = opts.valueOf(parentPath); 62 else if (!opts.has("N")) 63 pp = homeLibrary; 64 65 File natlibs = null; 66 if (opts.has(nativeLibs)) 67 natlibs = opts.valueOf(nativeLibs); 68 File natcmds = null; 69 if (opts.has(nativeCmds)) 70 natcmds = opts.valueOf(nativeCmds); 71 File configs = null; 72 if (opts.has(configFiles)) 73 configs = opts.valueOf(configFiles); 74 75 Set<StorageOption> createOpts = new HashSet<>(); 76 if (opts.has("z")) 77 createOpts.add(StorageOption.DEFLATED); 78 79 try { 80 lib = SimpleLibrary.create(lp, pp, natlibs, natcmds, 81 configs, createOpts); 82 } catch (IOException x) { 83 throw new Command.Exception(x); 84 } 85 } 86 } 87 88 static class DumpClass extends Command<SimpleLibrary> { 89 protected void go(SimpleLibrary lib) 90 throws Command.Exception 91 { 92 noDry(); 93 String mids = takeArg(); 94 ModuleId mid = null; 95 try { 96 mid = jms.parseModuleId(mids); 97 } catch (IllegalArgumentException x) { 98 throw new Command.Exception(x.getMessage()); 99 } 100 String cn = takeArg(); 101 String ops = takeArg(); 102 finishArgs(); 103 byte[] bs = null; 104 try { 105 bs = lib.readClass(mid, cn); 106 if (bs == null) 107 throw new Command.Exception("%s: No such class in module %s", 108 cn, mid); 109 OutputStream fout = null; 110 try { 111 fout = (ops.equals("-") 112 ? System.out 113 : new FileOutputStream(ops)); 114 fout.write(bs); 115 } finally { 116 if (fout != null) 117 fout.close(); 118 } 119 } catch (IllegalArgumentException x) { 120 throw new Command.Exception(x.getMessage()); 121 } catch (IOException x) { 122 throw new Command.Exception(x); 123 } 124 } 125 } 126 127 static class Identify extends Command<SimpleLibrary> { 128 protected void go(SimpleLibrary lib) 129 throws Command.Exception 130 { 131 noDry(); 132 finishArgs(); 133 out.format("path %s%n", lib.root()); 134 out.format("version %d.%d%n", 135 lib.majorVersion(), lib.minorVersion()); 136 if (lib.natlibs() != null) 137 out.format("natlibs %s%n", lib.natlibs()); 138 if (lib.natcmds() != null) 139 out.format("natcmds %s%n", lib.natcmds()); 140 if (lib.configs() != null) 141 out.format("configs %s%n", lib.configs()); 142 SimpleLibrary plib = lib.parent(); 143 while (plib != null) { 144 out.format("parent %s%n", plib.root()); 145 plib = plib.parent(); 146 } 147 } 148 } 149 150 static class Extract extends Command<SimpleLibrary> { 151 protected void go(SimpleLibrary lib) 152 throws Command.Exception 153 { 154 noDry(); 155 while (hasArg()) { 156 File module = new File(takeArg()); 157 File destination = null; 158 try (FileInputStream fis = new FileInputStream(module); 159 DataInputStream dis = new DataInputStream(fis); 160 ModuleFile.Reader reader = new ModuleFile.Reader(dis)) { 161 162 ModuleInfo mi = jms.parseModuleInfo(reader.readStart()); 163 destination = new File(mi.id().name()); 164 Path path = destination.toPath(); 165 Files.deleteIfExists(path); 166 Files.createDirectory(path); 167 reader.readRest(destination, false); 168 } 169 catch (IOException x) { 170 // Try to cleanup if an exception is thrown 171 if (destination != null && destination.exists()) 172 try { 173 FilePaths.deleteTree(destination.toPath()); 174 } 175 catch (IOException y) { 176 throw (Command.Exception) 177 new Command.Exception(y).initCause(x); 178 } 179 throw new Command.Exception(x); 180 } 181 } 182 finishArgs(); 183 } 184 } 185 186 static class Install extends Command<SimpleLibrary> { 187 protected void go(SimpleLibrary lib) 188 throws Command.Exception 189 { 190 String key = takeArg(); 191 File kf = new File(key); 192 boolean verifySignature = !opts.has("noverify"); 193 boolean strip = opts.has("G"); 194 195 // Old form: install <classes-dir> <module-name> ... 196 // 197 if (kf.exists() && kf.isDirectory()) { 198 noDry(); 199 List<Manifest> mfs = new ArrayList<>(); 200 while (hasArg()) 201 mfs.add(Manifest.create(takeArg(), kf)); 202 finishArgs(); 203 if (mfs.isEmpty()) 204 throw new Command.Exception("%s: no module-name specified", 205 command); 206 try { 207 lib.installFromManifests(mfs, strip); 208 } catch (ConfigurationException x) { 209 throw new Command.Exception(x); 210 } catch (IOException x) { 211 throw new Command.Exception(x); 212 } 213 return; 214 } 215 216 // Install one or more module file(s) 217 // 218 if (kf.exists() && kf.isFile()) { 219 noDry(); 220 List<File> fs = new ArrayList<>(); 221 fs.add(kf); 222 while (hasArg()) 223 fs.add(new File(takeArg())); 224 finishArgs(); 225 try { 226 lib.install(fs, verifySignature, strip); 227 } catch (ConfigurationException x) { 228 throw new Command.Exception(x); 229 } catch (IOException x) { 230 throw new Command.Exception(x); 231 } catch (SignatureException x) { 232 throw new Command.Exception(x); 233 } 234 return; 235 } 236 237 // Otherwise treat args as module-id queries 238 List<ModuleIdQuery> midqs = new ArrayList<>(); 239 String s = key; 240 for (;;) { 241 ModuleIdQuery mq = null; 242 try { 243 mq = jms.parseModuleIdQuery(s); 244 } catch (IllegalArgumentException x) { 245 throw new Command.Exception(x); 246 } 247 midqs.add(mq); 248 if (!hasArg()) 249 break; 250 s = takeArg(); 251 } 252 try { 253 boolean quiet = false; // ## Need -q 254 Resolution res = lib.resolve(midqs); 255 if (res.modulesNeeded().isEmpty()) { 256 if (!quiet) 257 out.format("Nothing to install%n"); 258 return; 259 } 260 if (!quiet) { 261 out.format("To install: %s%n", 262 res.modulesNeeded() 263 .toString().replaceAll("^\\[|\\]$", "")); 264 out.format("%d bytes to download/transfer%n", 265 res.downloadRequired()); 266 out.format("%d bytes to store%n", 267 res.spaceRequired()); 268 } 269 if (dry) 270 return; 271 lib.install(res, verifySignature, strip); 272 } catch (ConfigurationException | IOException | SignatureException x) { 273 throw new Command.Exception(x); 274 } 275 276 } 277 } 278 279 // ## preinstall is used by jpkg for creating debian package. 280 // ## need to revisit this 281 static class PreInstall extends Command<SimpleLibrary> { 282 protected void go(SimpleLibrary lib) 283 throws Command.Exception 284 { 285 noDry(); 286 File classes = new File(takeArg()); 287 File dst = new File(takeArg()); 288 List<Manifest> mfs = new ArrayList<Manifest>(); 289 while (hasArg()) 290 mfs.add(Manifest.create(takeArg(), classes)); 291 finishArgs(); 292 try { 293 lib.preInstall(mfs, dst); 294 } catch (IOException x) { 295 throw new Command.Exception(x); 296 } 297 } 298 } 299 300 static class Remove extends Command<SimpleLibrary> { 301 protected void go(SimpleLibrary lib) 302 throws Command.Exception 303 { 304 if (dry && force) 305 throw new Command.Exception("%s: specify only one of " 306 + "-n (--dry-run) or -f (--force)", 307 command); 308 List<ModuleId> mids = new ArrayList<ModuleId>(); 309 try { 310 while (hasArg()) 311 mids.add(jms.parseModuleId(takeArg())); 312 } catch (IllegalArgumentException x) { 313 throw new Command.Exception(x.getMessage()); 314 } 315 boolean quiet = false; // ## Need -q 316 try { 317 if (force) 318 lib.removeForcibly(mids); 319 else 320 lib.remove(mids, dry); 321 } catch (ConfigurationException x) { 322 throw new Command.Exception(x); 323 } catch (IOException x) { 324 if (!quiet) { 325 for (Throwable t : x.getSuppressed()) 326 err.format("Warning: %s%n", t.getMessage()); 327 } 328 throw new Command.Exception(x); 329 } 330 } 331 } 332 333 static class DumpConfig extends Command<SimpleLibrary> { 334 protected void go(SimpleLibrary lib) 335 throws Command.Exception 336 { 337 noDry(); 338 String midqs = takeArg(); 339 ModuleIdQuery midq = null; 340 try { 341 midq = jms.parseModuleIdQuery(midqs); 342 } catch (IllegalArgumentException x) { 343 throw new Command.Exception(x.getMessage()); 344 } 345 finishArgs(); 346 try { 347 ModuleId mid = lib.findLatestModuleId(midq); 348 if (mid == null) 349 throw new Command.Exception(midq + ": No such module"); 350 Configuration<Context> cf = lib.readConfiguration(mid); 351 if (cf == null) 352 throw new Command.Exception(mid + ": Not a root module"); 353 cf.dump(out, verbose); 354 } catch (IOException x) { 355 throw new Command.Exception(x); 356 } 357 } 358 } 359 360 static class Config extends Command<SimpleLibrary> { 361 protected void go(SimpleLibrary lib) 362 throws Command.Exception 363 { 364 noDry(); 365 List<ModuleId> mids = new ArrayList<ModuleId>(); 366 try { 367 while (hasArg()) 368 mids.add(jms.parseModuleId(takeArg())); 369 } catch (IllegalArgumentException x) { 370 throw new Command.Exception(x.getMessage()); 371 } 372 try { 373 lib.configure(mids); 374 } catch (ConfigurationException x) { 375 throw new Command.Exception(x); 376 } catch (IOException x) { 377 throw new Command.Exception(x); 378 } 379 } 380 } 381 382 static class ReIndex extends Command<SimpleLibrary> { 383 protected void go(SimpleLibrary lib) 384 throws Command.Exception 385 { 386 noDry(); 387 List<ModuleId> mids = new ArrayList<ModuleId>(); 388 try { 389 while (hasArg()) 390 mids.add(jms.parseModuleId(takeArg())); 391 } catch (IllegalArgumentException x) { 392 throw new Command.Exception(x.getMessage()); 393 } 394 try { 395 lib.reIndex(mids); 396 } catch (ConfigurationException x) { 397 throw new Command.Exception(x); 398 } catch (IOException x) { 399 throw new Command.Exception(x); 400 } 401 } 402 } 403 404 static class Repos extends Command<SimpleLibrary> { 405 protected void go(SimpleLibrary lib) 406 throws Command.Exception 407 { 408 noDry(); 409 finishArgs(); 410 try { 411 RemoteRepositoryList rl = lib.repositoryList(); 412 int i = 0; 413 for (RemoteRepository rr : rl.repositories()) 414 out.format("%d %s%n", i++, rr.location()); 415 } catch (IOException x) { 416 throw new Command.Exception(x); 417 } 418 } 419 } 420 421 static URI parseURI(String s) 422 throws Command.Exception 423 { 424 try { 425 // if a scheme isn't specified then assume that a file path 426 if (s.indexOf(':') == -1) 427 return Paths.get(s).toUri(); 428 return new URI(s); 429 } catch (URISyntaxException x) { 430 throw new Command.Exception("URI syntax error: " 431 + x.getMessage()); 432 } 433 } 434 435 static class AddRepo extends Command<SimpleLibrary> { 436 protected void go(SimpleLibrary lib) 437 throws Command.Exception 438 { 439 noDry(); 440 URI u = parseURI(takeArg()); 441 int i = (opts.has(repoIndex) 442 ? opts.valueOf(repoIndex) 443 : Integer.MAX_VALUE); 444 finishArgs(); 445 try { 446 RemoteRepositoryList rl = lib.repositoryList(); 447 rl.add(u, i); 448 } catch (IOException x) { 449 throw new Command.Exception(x); 450 } 451 } 452 } 453 454 static class DelRepo extends Command<SimpleLibrary> { 455 protected void go(SimpleLibrary lib) 456 throws Command.Exception 457 { 458 noDry(); 459 URI u = null; 460 int i = -1; 461 if (hasArg()) { 462 String s = takeArg(); 463 if (!s.endsWith("/")) 464 s += "/"; 465 u = parseURI(s); 466 finishArgs(); 467 } 468 if (opts.has(repoIndex)) 469 i = opts.valueOf(repoIndex); 470 if (u != null && i != -1) { 471 throw new Command.Exception("del-repo: Cannot specify" 472 + " both -i and a URL"); 473 } 474 if (u == null && i == -1) { 475 throw new Command.Exception("del-repo: One of -i <index>" 476 + " or a URL required"); 477 } 478 try { 479 RemoteRepositoryList rl = lib.repositoryList(); 480 if (i != -1) { 481 rl.remove(rl.repositories().get(i)); 482 return; 483 } 484 for (RemoteRepository rr : rl.repositories()) { 485 if (rr.location().equals(u)) { 486 rl.remove(rr); 487 return; 488 } 489 } 490 throw new Command.Exception("No repository found for deletion"); 491 } catch (IOException x) { 492 throw new Command.Exception(x); 493 } 494 } 495 } 496 497 static class Refresh extends Command<SimpleLibrary> { 498 protected void go(SimpleLibrary lib) 499 throws Command.Exception 500 { 501 finishArgs(); 502 try { 503 // refresh the module directory 504 lib.refresh(); 505 506 // refresh the repository catalog 507 RemoteRepositoryList rl = lib.repositoryList(); 508 int n = 0; 509 for (RemoteRepository rr : rl.repositories()) { 510 out.format("%s - ", rr.location()); 511 out.flush(); 512 boolean stale 513 = dry ? rr.isCatalogStale() : rr.updateCatalog(force); 514 if (stale) { 515 n++; 516 out.format(dry ? "out of date%n" : "updated%n"); 517 } else { 518 out.format("up to date%n"); 519 } 520 } 521 } catch (IOException x) { 522 throw new Command.Exception(x); 523 } 524 } 525 } 526 527 private static final Map<String,Class<? extends Command<SimpleLibrary>>> commands 528 = new HashMap<>(); 529 530 static { 531 commands.put("add-repo", AddRepo.class); 532 commands.put("config", Config.class); 533 commands.put("create", Create.class); 534 commands.put("del-repo", DelRepo.class); 535 commands.put("dump-class", DumpClass.class); 536 commands.put("dump-config", DumpConfig.class); 537 commands.put("extract", Extract.class); 538 commands.put("id", Identify.class); 539 commands.put("identify", Identify.class); 540 commands.put("install", Install.class); 541 commands.put("list", Commands.ListLibrary.class); 542 commands.put("ls", Commands.ListLibrary.class); 543 commands.put("preinstall", PreInstall.class); 544 commands.put("refresh", Refresh.class); 545 commands.put("reindex", ReIndex.class); 546 commands.put("remove", Remove.class); 547 commands.put("rm", Remove.class); 548 commands.put("repos", Repos.class); 549 } 550 551 private OptionParser parser; 552 553 private static OptionSpec<Integer> repoIndex; // ## 554 private static OptionSpec<File> libPath; 555 private static OptionSpec<File> parentPath; 556 private static OptionSpec<File> nativeLibs; 557 private static OptionSpec<File> nativeCmds; 558 private static OptionSpec<File> configFiles; 559 560 private void usage() { 561 out.format("%n"); 562 out.format("usage: jmod add-repo [-i <index>] URL%n"); 563 out.format(" jmod config [<module-id> ...]%n"); 564 out.format(" jmod create [-L <library>] [-P <parent>]" + 565 " [--natlib <natlib>] [--natcmd <natcmd>] [--config <config>]%n"); 566 out.format(" jmod del-repo URL%n"); 567 out.format(" jmod dump-class <module-id> <class-name> <output-file>%n"); 568 out.format(" jmod dump-config <module-id>%n"); 569 out.format(" jmod extract <module-file> ...%n"); 570 out.format(" jmod identify%n"); 571 out.format(" jmod install [--noverify] [-n] <module-id-query> ...%n"); 572 out.format(" jmod install [--noverify] <module-file> ...%n"); 573 out.format(" jmod install <classes-dir> <module-name> ...%n"); 574 out.format(" jmod list [-v] [-p] [-R] [<module-id-query>]%n"); 575 out.format(" jmod preinstall <classes-dir> <dst-dir> <module-name> ...%n"); 576 out.format(" jmod refresh [-f] [-n] [-v]%n"); 577 out.format(" jmod reindex [<module-id> ...]%n"); 578 out.format(" jmod remove [-f] [-n] [<module-id> ...]%n"); 579 out.format(" jmod repos [-v]%n"); 580 out.format("%n"); 581 try { 582 parser.printHelpOn(out); 583 } catch (IOException x) { 584 throw new AssertionError(x); 585 } 586 out.format("%n"); 587 System.exit(0); 588 } 589 590 public static void run(String [] args) throws OptionException, Command.Exception { 591 new Librarian().exec(args); 592 } 593 594 private void exec(String[] args) throws OptionException, Command.Exception { 595 parser = new OptionParser(); 596 597 // ## Need subcommand-specific option parsing 598 libPath 599 = (parser.acceptsAll(Arrays.asList("L", "library"), 600 "Module-library location" 601 + " (default $JAVA_MODULES)") 602 .withRequiredArg() 603 .describedAs("path") 604 .ofType(File.class)); 605 parentPath 606 = (parser.acceptsAll(Arrays.asList("P", "parent-path"), 607 "Parent module-library location") 608 .withRequiredArg() 609 .describedAs("path") 610 .ofType(File.class)); 611 nativeLibs 612 = (parser.accepts("natlib", "Directory to store native libs") 613 .withRequiredArg() 614 .describedAs("dir") 615 .ofType(File.class)); 616 nativeCmds 617 = (parser.accepts("natcmd", "Directory to store native launchers") 618 .withRequiredArg() 619 .describedAs("dir") 620 .ofType(File.class)); 621 configFiles 622 = (parser.accepts("config", "Directory to store config files") 623 .withRequiredArg() 624 .describedAs("dir") 625 .ofType(File.class)); 626 parser.acceptsAll(Arrays.asList("N", "no-parent"), 627 "Use no parent library when creating"); 628 parser.acceptsAll(Arrays.asList("v", "verbose"), 629 "Enable verbose output"); 630 parser.acceptsAll(Arrays.asList("h", "?", "help"), 631 "Show this help message"); 632 parser.acceptsAll(Arrays.asList("p", "parent"), 633 "Apply operation to parent library, if any"); 634 parser.acceptsAll(Arrays.asList("z", "enable-compression"), 635 "Enable compression of module contents"); 636 repoIndex 637 = (parser.acceptsAll(Arrays.asList("i"), 638 "Repository-list index") 639 .withRequiredArg() 640 .describedAs("index") 641 .ofType(Integer.class)); 642 parser.acceptsAll(Arrays.asList("f", "force"), 643 "Force the requested operation"); 644 parser.acceptsAll(Arrays.asList("n", "dry-run"), 645 "Dry-run the requested operation"); 646 parser.acceptsAll(Arrays.asList("R", "repos"), 647 "List contents of associated repositories"); 648 parser.acceptsAll(Arrays.asList("noverify"), 649 "Do not verify module signatures. " 650 + "Treat as unsigned."); 651 parser.acceptsAll(Arrays.asList("G", "strip-debug"), 652 "Strip debug attributes during installation"); 653 654 if (args.length == 0) 655 usage(); 656 657 OptionSet opts = parser.parse(args); 658 if (opts.has("h")) 659 usage(); 660 List<String> words = opts.nonOptionArguments(); 661 if (words.isEmpty()) 662 usage(); 663 String verb = words.get(0); 664 Class<? extends Command<SimpleLibrary>> cmd = commands.get(verb); 665 if (cmd == null) 666 throw new Command.Exception("%s: unknown command", verb); 667 668 // Every command, except 'create' and 'extract', needs 669 // to have a valid reference to the library 670 SimpleLibrary lib = null; 671 if (!(verb.equals("create") || verb.equals("extract"))) { 672 File lp = libPath(opts); 673 try { 674 lib = SimpleLibrary.open(lp); 675 } catch (FileNotFoundException x) { 676 String msg = null; 677 File f = new File(x.getMessage()); 678 try { 679 f = f.getCanonicalFile(); 680 if (lp.getCanonicalFile().equals(f)) 681 msg = "No such library"; 682 else 683 msg = "Cannot open parent library " + f; 684 } catch (IOException y) { 685 throw new Command.Exception(y); 686 } 687 throw new Command.Exception("%s: %s", lp, msg); 688 } catch (IOException x) { 689 throw new Command.Exception(x); 690 } 691 } 692 try { 693 cmd.newInstance().run(lib, opts); 694 } catch (InstantiationException x) { 695 throw new AssertionError(x); 696 } catch (IllegalAccessException x) { 697 throw new AssertionError(x); 698 } 699 } 700 701 private static File libPath(OptionSet opts) { 702 if (opts.has(libPath)) { 703 return opts.valueOf(libPath); 704 } else { 705 String jm = System.getenv("JAVA_MODULES"); 706 if (jm != null) 707 return new File(jm); 708 else 709 return homeLibrary; 710 } 711 } 712 713 private Librarian() { } 714 715 public static void main(String[] args) { 716 try { 717 run(args); 718 } catch (OptionException x) { 719 err.println(x.getMessage()); 720 System.exit(1); 721 } catch (Command.Exception x) { 722 err.println(x.getMessage()); 723 x.printStackTrace(); 724 System.exit(1); 725 } 726 } 727 728 }