Esempio n. 1
0
 public void run() {
   ConsoleReader console = null;
   try {
     console = new ConsoleReader(in, out);
     console.println(WELCOME_MESSAGE);
     String statement = null;
     while ((statement = console.readLine(PROMPT)) != null) {
       if ("exit".equals(statement.trim())) {
         return;
       } else {
         try {
           dynJS.eval(context, statement);
         } catch (DynJSException e) {
           console.println(e.getClass().getSimpleName());
           console.println(e.getLocalizedMessage());
           console.println("Error parsing statement: " + statement.toString());
         } catch (Exception e) {
           e.printStackTrace(new PrintWriter(out));
         }
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 @Override
 public void packageVersionResolutionFailed(FqPackageName packageName) {
   clearProgressBar();
   try {
     reader.println("Could not resolve " + packageName);
     reader.println("Tried:");
     for (String failedDownload : failedDownloads) {
       reader.println("* " + failedDownload);
     }
   } catch (IOException ignored) {
   }
 }
Esempio n. 3
0
 private void cleanUp() throws IOException {
   if (_history instanceof PersistentHistory) {
     ((PersistentHistory) _history).flush();
   }
   _console.println();
   _console.flush();
 }
Esempio n. 4
0
  /** Executes the map command using the provided options. */
  @Override
  protected void runInternal(GeogitCLI cli) throws IOException {

    if (args == null || args.isEmpty() || args.size() != 1) {
      printUsage(cli);
      throw new CommandFailedException();
    }

    String path = args.get(0);

    geogit = cli.getGeogit();

    ObjectId oldTreeId = geogit.getRepository().workingTree().getTree().getId();

    ObjectId newTreeId = geogit.command(OSMUnmapOp.class).setPath(path).call().getId();

    ConsoleReader console = cli.getConsole();
    if (newTreeId.equals(oldTreeId)) {
      console.println(
          "No differences were found after unmapping.\n"
              + "No changes have been made to the working tree");
    } else {
      // print something?
    }
  }
Esempio n. 5
0
 private void initAdminShell() throws IOException {
   if (_history != null) {
     _console.setHistory(_history);
   }
   _console.addCompleter(_userAdminShell);
   _console.println(_userAdminShell.getHello());
   _console.flush();
 }
Esempio n. 6
0
  @Override
  public void runInternal(GeogitCLI cli) throws Exception {
    checkState(cli.getGeogit() != null, "Not a geogit repository: " + cli.getPlatform().pwd());
    String ref;
    if (refList.isEmpty()) {
      ref = null;
    } else {
      ref = refList.get(0);
    }
    Iterator<RevObject> iter =
        cli.getGeogit() //
            .command(WalkGraphOp.class)
            .setReference(ref) //
            // .setStrategy(lsStrategy) //
            .call();

    final ConsoleReader console = cli.getConsole();
    if (!iter.hasNext()) {
      if (ref == null) {
        console.println("The working tree is empty");
      } else {
        console.println("The specified path is empty");
      }
      return;
    }

    Function<RevObject, CharSequence> printFunctor =
        new Function<RevObject, CharSequence>() {
          @Override
          public CharSequence apply(RevObject input) {
            if (verbose) {
              return String.format("%s: %s %s", input.getId(), input.getType(), input);
            } else {
              return String.format("%s: %s", input.getId(), input.getType());
            }
          }
        };

    Iterator<CharSequence> lines = Iterators.transform(iter, printFunctor);

    while (lines.hasNext()) {
      console.println(lines.next());
    }
    console.flush();
  }
 @Override
 public void packageResolveFailed(DependencyResolutionException exception) {
   clearProgressBar();
   Artifact artifact = exception.getResult().getRoot().getArtifact();
   try {
     reader.println(
         String.format(
             "Could not resolve dependencies for %s.%s version %s",
             artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()));
     reader.println("The following artifacts could not be located:");
     for (ArtifactResult result : exception.getResult().getArtifactResults()) {
       if (result.isMissing()) {
         reader.println("* " + result.getRequest().getArtifact());
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Esempio n. 8
0
  @Override
  public void runInternal(GeogitCLI cli) throws IOException {
    ImmutableList<ObjectId> updatedObjects = cli.getGeogit().command(RebuildGraphOp.class).call();

    final ConsoleReader console = cli.getConsole();
    if (updatedObjects.size() > 0) {
      if (quiet) {
        console.println(updatedObjects.size() + " graph elements (commits) were fixed.");
      } else {
        console.println(
            "The following graph elements (commits) were incomplete or missing and have been fixed:");
        for (ObjectId object : updatedObjects) {
          console.println(object.toString());
        }
      }
    } else {
      console.println("No missing or incomplete graph elements (commits) were found.");
    }
  }
 @Override
 public void packageLoadSucceeded(FqPackageName name, String version) {
   clearProgressBar();
   try {
     reader.println(
         String.format(
             "Loaded %s.%s version %s.", name.getGroupId(), name.getPackageName(), version));
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Esempio n. 10
0
 @Override
 public void start(Application app) throws IOException {
   super.start(app);
   updatePrompt();
   // register completors
   console.addCompleter(new CompositeCompletor(this, app.getCommandRegistry()));
   String line = console.readLine();
   while (line != null) {
     line = line.trim();
     try {
       if (line.length() > 0) {
         if (!execute(line)) {
           break;
         }
         // println();
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
     line = console.readLine();
   }
   console.print("Bye");
   console.println();
 }
Esempio n. 11
0
  @Override
  public void runInternal(GeogigCLI cli) throws IOException {
    checkParameter(patchFiles.size() < 2, "Only one single patch file accepted");
    checkParameter(!patchFiles.isEmpty(), "No patch file specified");

    ConsoleReader console = cli.getConsole();
    GeoGIG geogig = cli.getGeogig();

    File patchFile = new File(patchFiles.get(0));
    checkParameter(patchFile.exists(), "Patch file cannot be found");
    FileInputStream stream;
    try {
      stream = new FileInputStream(patchFile);
    } catch (FileNotFoundException e1) {
      throw new CommandFailedException("Can't open patch file " + patchFile, e1);
    }
    BufferedReader reader = null;
    try {
      reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
      Closeables.closeQuietly(reader);
      Closeables.closeQuietly(stream);
      throw new CommandFailedException("Error reading patch file " + patchFile, e);
    }
    Patch patch = PatchSerializer.read(reader);
    Closeables.closeQuietly(reader);
    Closeables.closeQuietly(stream);

    if (reverse) {
      patch = patch.reversed();
    }

    if (summary) {
      console.println(patch.toString());
    } else if (check) {
      VerifyPatchResults verify =
          cli.getGeogig().command(VerifyPatchOp.class).setPatch(patch).call();
      Patch toReject = verify.getToReject();
      Patch toApply = verify.getToApply();
      if (toReject.isEmpty()) {
        console.println("Patch can be applied.");
      } else {
        console.println("Error: Patch cannot be applied\n");
        console.println("Applicable entries:\n");
        console.println(toApply.toString());
        console.println("\nConflicting entries:\n");
        console.println(toReject.toString());
      }
    } else {
      try {
        Patch rejected =
            geogig.command(ApplyPatchOp.class).setPatch(patch).setApplyPartial(reject).call();
        if (reject) {
          if (rejected.isEmpty()) {
            console.println("Patch applied succesfully");
          } else {
            int accepted = patch.count() - rejected.count();
            StringBuilder sb = new StringBuilder();
            File file = new File(patchFile.getAbsolutePath() + ".rej");
            sb.append("Patch applied only partially.\n");
            sb.append(Integer.toString(accepted) + " changes were applied.\n");
            sb.append(Integer.toString(rejected.count()) + " changes were rejected.\n");
            BufferedWriter writer = Files.newWriter(file, Charsets.UTF_8);
            PatchSerializer.write(writer, patch);
            writer.flush();
            writer.close();
            sb.append(
                "Patch file with rejected changes created at " + file.getAbsolutePath() + "\n");
            throw new CommandFailedException(sb.toString());
          }
        } else {
          console.println("Patch applied succesfully");
        }
      } catch (CannotApplyPatchException e) {
        throw new CommandFailedException(e);
      }
    }
  }
Esempio n. 12
0
 @Override
 public void println() throws IOException {
   console.flush();
   console.println();
 }
Esempio n. 13
0
  private void runAsciiMode() throws IOException {
    Ansi.setEnabled(_useColors);
    while (true) {
      String prompt = Ansi.ansi().bold().a(_userAdminShell.getPrompt()).boldOff().toString();
      Object result;
      try {
        String str = _console.readLine(prompt);
        try {
          if (str == null) {
            throw new CommandExitException();
          }
          result = _userAdminShell.executeCommand(str);
        } catch (IllegalArgumentException e) {
          result = e.toString();
        } catch (SerializationException e) {
          result = "There is a bug here, please report to [email protected]";
          _logger.error("This must be a bug, please report to [email protected].", e);
        } catch (CommandSyntaxException e) {
          result = e;
        } catch (CommandExitException e) {
          break;
        } catch (CommandPanicException e) {
          result =
              "Command '"
                  + str
                  + "' triggered a bug ("
                  + e.getTargetException()
                  + "); the service log file contains additional information. Please "
                  + "contact [email protected].";
        } catch (CommandException e) {
          result = e.getMessage();
        } catch (NoRouteToCellException e) {
          result = "Cell name does not exist or cell is not started: " + e.getMessage();
          _logger.warn(
              "The cell the command was sent to is no " + "longer there: {}", e.getMessage());
        } catch (RuntimeException e) {
          result =
              String.format(
                  "Command '%s' triggered a bug (%s); please"
                      + " locate this message in the log file of the admin service and"
                      + " send an email to [email protected] with this line and the"
                      + " following stack-trace",
                  str, e);
          _logger.error((String) result, e);
        }
      } catch (InterruptedIOException e) {
        _console.getCursorBuffer().clear();
        _console.println();
        result = null;
      } catch (InterruptedException e) {
        _console.println("^C");
        _console.flush();
        _console.getCursorBuffer().clear();
        result = null;
      } catch (IOException e) {
        throw e;
      } catch (Exception e) {
        result = e.getMessage();
        if (result == null) {
          result = e.getClass().getSimpleName() + ": (null)";
        }
      }

      if (result != null) {
        if (result instanceof CommandSyntaxException) {
          CommandSyntaxException e = (CommandSyntaxException) result;
          Ansi sb = Ansi.ansi();
          sb.fg(RED).a("Syntax error: ").a(e.getMessage()).newline();
          String help = e.getHelpText();
          if (help != null) {
            sb.fg(CYAN);
            sb.a("Help : ").newline();
            sb.a(help);
          }
          _console.println(sb.reset().toString());
        } else {
          String s;
          s = Strings.toMultilineString(result);
          if (!s.isEmpty()) {
            _console.println(s);
            _console.flush();
          }
        }
      }
      _console.flush();
    }
  }
Esempio n. 14
0
  /**
   * Executes the log command using the provided options.
   *
   * @param cli
   * @throws IOException
   * @see org.geogit.cli.AbstractCommand#runInternal(org.geogit.cli.GeogitCLI)
   */
  @Override
  public void runInternal(GeogitCLI cli) throws Exception {
    final Platform platform = cli.getPlatform();
    Preconditions.checkState(
        cli.getGeogit() != null, "Not a geogit repository: " + platform.pwd().getAbsolutePath());

    Preconditions.checkArgument(
        !(args.summary && args.oneline), "--summary and --oneline cannot be used together");
    Preconditions.checkArgument(
        !(args.stats && args.oneline), "--stats and --oneline cannot be used together");
    Preconditions.checkArgument(
        !(args.stats && args.oneline), "--name-only and --oneline cannot be used together");

    geogit = cli.getGeogit();

    LogOp op =
        geogit.command(LogOp.class).setTopoOrder(args.topo).setFirstParentOnly(args.firstParent);

    refs = Maps.newHashMap();
    if (args.decoration) {
      Optional<Ref> head = geogit.command(RefParse.class).setName(Ref.HEAD).call();
      refs.put(head.get().getObjectId(), Ref.HEAD);
      ImmutableSet<Ref> set = geogit.command(ForEachRef.class).call();
      for (Ref ref : set) {
        ObjectId id = ref.getObjectId();
        if (refs.containsKey(id)) {
          refs.put(id, refs.get(id) + ", " + ref.getName());
        } else {
          refs.put(id, ref.getName());
        }
      }
    }
    if (args.all) {
      ImmutableSet<Ref> refs = geogit.command(ForEachRef.class).call();
      List<ObjectId> list = Lists.newArrayList();
      for (Ref ref : refs) {
        list.add(ref.getObjectId());
      }
      Optional<Ref> head = geogit.command(RefParse.class).setName(Ref.HEAD).call();
      if (head.isPresent()) {
        Ref ref = head.get();
        if (ref instanceof SymRef) {
          ObjectId id = ref.getObjectId();
          list.remove(id);
          list.add(id); // put the HEAD ref in the last position, to give it preference
        }
      }
      for (ObjectId id : list) {
        op.addCommit(id);
      }
    } else if (args.branch != null) {
      Optional<Ref> obj = geogit.command(RefParse.class).setName(args.branch).call();
      Preconditions.checkArgument(obj.isPresent(), "Wrong branch name: " + args.branch);
      op.addCommit(obj.get().getObjectId());
    }

    if (args.author != null && !args.author.isEmpty()) {
      op.setAuthor(args.author);
    }
    if (args.committer != null && !args.committer.isEmpty()) {
      op.setCommiter(args.committer);
    }
    if (args.skip != null) {
      op.setSkip(args.skip.intValue());
    }
    if (args.limit != null) {
      op.setLimit(args.limit.intValue());
    }
    if (args.since != null || args.until != null) {
      Date since = new Date(0);
      Date until = new Date();
      if (args.since != null) {
        since = new Date(geogit.command(ParseTimestamp.class).setString(args.since).call());
      }
      if (args.until != null) {
        until = new Date(geogit.command(ParseTimestamp.class).setString(args.until).call());
        if (args.all) {
          throw new IllegalStateException(
              "Cannot specify 'until' commit when listing all branches");
        }
      }
      op.setTimeRange(new Range<Date>(Date.class, since, until));
    }
    if (!args.sinceUntilPaths.isEmpty()) {
      List<String> sinceUntil =
          ImmutableList.copyOf((Splitter.on("..").split(args.sinceUntilPaths.get(0))));
      Preconditions.checkArgument(
          sinceUntil.size() == 1 || sinceUntil.size() == 2,
          "Invalid refSpec format, expected [<until>]|[<since>..<until>]: %s",
          args.sinceUntilPaths.get(0));

      String sinceRefSpec;
      String untilRefSpec;
      if (sinceUntil.size() == 1) {
        // just until was given
        sinceRefSpec = null;
        untilRefSpec = sinceUntil.get(0);
      } else {
        sinceRefSpec = sinceUntil.get(0);
        untilRefSpec = sinceUntil.get(1);
      }
      if (sinceRefSpec != null) {
        Optional<ObjectId> since;
        since = geogit.command(RevParse.class).setRefSpec(sinceRefSpec).call();
        Preconditions.checkArgument(since.isPresent(), "Object not found '%s'", sinceRefSpec);
        op.setSince(since.get());
      }
      if (untilRefSpec != null) {
        if (args.all) {
          throw new IllegalStateException(
              "Cannot specify 'until' commit when listing all branches");
        }
        Optional<ObjectId> until;
        until = geogit.command(RevParse.class).setRefSpec(untilRefSpec).call();
        Preconditions.checkArgument(until.isPresent(), "Object not found '%s'", sinceRefSpec);
        op.setUntil(until.get());
      }
    }
    if (!args.pathNames.isEmpty()) {
      for (String s : args.pathNames) {
        op.addPath(s);
      }
    }
    Iterator<RevCommit> log = op.call();
    console = cli.getConsole();
    Terminal terminal = console.getTerminal();
    switch (args.color) {
      case never:
        useColor = false;
        break;
      case always:
        useColor = true;
        break;
      default:
        useColor = terminal.isAnsiSupported();
    }

    if (!log.hasNext()) {
      console.println("No commits to show");
      console.flush();
      return;
    }

    LogEntryPrinter printer;
    if (args.oneline) {
      printer = new OneLineConverter();
    } else {
      LOG_DETAIL detail;
      if (args.summary) {
        detail = LOG_DETAIL.SUMMARY;
      } else if (args.names) {
        detail = LOG_DETAIL.NAMES_ONLY;
      } else if (args.stats) {
        detail = LOG_DETAIL.STATS;
      } else {
        detail = LOG_DETAIL.NOTHING;
      }

      printer = new StandardConverter(detail, geogit.getPlatform());
    }

    while (log.hasNext()) {
      printer.print(log.next());
      console.flush();
    }
  }