Browse Source

Check for write errors in standard out and exit with error

The underlying problem is that System.out is a PrintWriter and
as such it does not throw exceptions on error, but rather just
sets a flag and continues.

This changes replaces the use of System.out with a PrintWriter-like
writer that does not catch error, but instead throw them to the
caller.

Bug: 366243
Change-Id: I44405edc4416e943b87f09a0f6ed041c6c51b046
stable-2.2
Robin Rosenberg 12 years ago committed by Shawn O. Pearce
parent
commit
caa362f20d
  1. 1
      org.eclipse.jgit.pgm.test/META-INF/MANIFEST.MF
  2. 12
      org.eclipse.jgit.pgm.test/src/org/eclipse/jgit/pgm/CLIGitCommand.java
  3. 1
      org.eclipse.jgit.pgm/META-INF/MANIFEST.MF
  4. 1
      org.eclipse.jgit.pgm/resources/org/eclipse/jgit/pgm/CLIText.properties
  5. 8
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/AbstractFetchCommand.java
  6. 6
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/AmazonS3Client.java
  7. 17
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Blame.java
  8. 20
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Branch.java
  9. 1
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/CLIText.java
  10. 10
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Checkout.java
  11. 11
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Clone.java
  12. 2
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Commit.java
  13. 4
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Config.java
  14. 4
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Daemon.java
  15. 12
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Diff.java
  16. 20
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/DiffTree.java
  17. 2
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Init.java
  18. 60
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Log.java
  19. 13
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/LsRemote.java
  20. 18
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/LsTree.java
  21. 13
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Main.java
  22. 18
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Merge.java
  23. 2
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/MergeBase.java
  24. 22
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Push.java
  25. 2
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/ReceivePack.java
  26. 22
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/RevList.java
  27. 4
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/RevParse.java
  28. 70
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Show.java
  29. 12
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/ShowRef.java
  30. 2
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Tag.java
  31. 26
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/TextBuiltin.java
  32. 2
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/UploadPack.java
  33. 2
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Version.java
  34. 20
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/debug/DiffAlgorithms.java
  35. 5
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/debug/MakeCacheTree.java
  36. 4
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/debug/ReadDirCache.java
  37. 5
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/debug/ShowCacheTree.java
  38. 22
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/debug/ShowDirCache.java
  39. 2
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/debug/ShowPackDelta.java
  40. 14
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/debug/TextHashFunctions.java
  41. 4
      org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/eclipse/Iplog.java
  42. 171
      org.eclipse.jgit/src/org/eclipse/jgit/util/io/ThrowingPrintWriter.java

1
org.eclipse.jgit.pgm.test/META-INF/MANIFEST.MF

@ -15,6 +15,7 @@ Import-Package: org.eclipse.jgit.api;version="[2.1.0,2.2.0)",
org.eclipse.jgit.revwalk;version="[2.1.0,2.2.0)", org.eclipse.jgit.revwalk;version="[2.1.0,2.2.0)",
org.eclipse.jgit.storage.file;version="[2.1.0,2.2.0)", org.eclipse.jgit.storage.file;version="[2.1.0,2.2.0)",
org.eclipse.jgit.util;version="[2.1.0,2.2.0)", org.eclipse.jgit.util;version="[2.1.0,2.2.0)",
org.eclipse.jgit.util.io;version="[2.1.0,2.2.0)",
org.hamcrest.core;bundle-version="[1.1.0,2.0.0)", org.hamcrest.core;bundle-version="[1.1.0,2.0.0)",
org.junit;version="[4.4.0,5.0.0)", org.junit;version="[4.4.0,5.0.0)",
org.kohsuke.args4j;version="[2.0.12,2.1.0)", org.kohsuke.args4j;version="[2.0.12,2.1.0)",

12
org.eclipse.jgit.pgm.test/src/org/eclipse/jgit/pgm/CLIGitCommand.java

@ -42,10 +42,7 @@
*/ */
package org.eclipse.jgit.pgm; package org.eclipse.jgit.pgm;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -84,21 +81,20 @@ public class CLIGitCommand {
clp.parseArgument(argv); clp.parseArgument(argv);
final TextBuiltin cmd = bean.getSubcommand(); final TextBuiltin cmd = bean.getSubcommand();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
cmd.outs = baos;
if (cmd.requiresRepository()) if (cmd.requiresRepository())
cmd.init(db, null); cmd.init(db, null);
else else
cmd.init(null, null); cmd.init(null, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
cmd.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
baos)));
try { try {
cmd.execute(bean.getArguments().toArray( cmd.execute(bean.getArguments().toArray(
new String[bean.getArguments().size()])); new String[bean.getArguments().size()]));
} catch (Die e) { } catch (Die e) {
return IO.readLines(e.getMessage()); return IO.readLines(e.getMessage());
} finally { } finally {
if (cmd.out != null) if (cmd.outw != null)
cmd.out.flush(); cmd.outw.flush();
} }
return IO.readLines(baos.toString()); return IO.readLines(baos.toString());
} }

1
org.eclipse.jgit.pgm/META-INF/MANIFEST.MF

@ -28,6 +28,7 @@ Import-Package: org.eclipse.jgit.api;version="[2.1.0,2.2.0)",
org.eclipse.jgit.treewalk;version="[2.1.0,2.2.0)", org.eclipse.jgit.treewalk;version="[2.1.0,2.2.0)",
org.eclipse.jgit.treewalk.filter;version="[2.1.0,2.2.0)", org.eclipse.jgit.treewalk.filter;version="[2.1.0,2.2.0)",
org.eclipse.jgit.util;version="[2.1.0,2.2.0)", org.eclipse.jgit.util;version="[2.1.0,2.2.0)",
org.eclipse.jgit.util.io;version="[2.1.0,2.2.0)",
org.kohsuke.args4j;version="[2.0.12,2.1.0)", org.kohsuke.args4j;version="[2.0.12,2.1.0)",
org.kohsuke.args4j.spi;version="[2.0.12,2.1.0)" org.kohsuke.args4j.spi;version="[2.0.12,2.1.0)"
Bundle-ActivationPolicy: lazy Bundle-ActivationPolicy: lazy

1
org.eclipse.jgit.pgm/resources/org/eclipse/jgit/pgm/CLIText.properties

@ -152,6 +152,7 @@ tagLabel=tag
taggerInfo=Tagger: {0} <{1}> taggerInfo=Tagger: {0} <{1}>
timeInMilliSeconds={0} ms timeInMilliSeconds={0} ms
tooManyRefsGiven=Too many refs given tooManyRefsGiven=Too many refs given
unknownIoErrorStdout=An unknown I/O error occurred on standard output
unknownMergeStrategy=unknown merge strategy {0} specified unknownMergeStrategy=unknown merge strategy {0} specified
unmergedPaths=Unmerged paths: unmergedPaths=Unmerged paths:
unsupportedOperation=Unsupported operation: {0} unsupportedOperation=Unsupported operation: {0}

8
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/AbstractFetchCommand.java

@ -63,7 +63,7 @@ abstract class AbstractFetchCommand extends TextBuiltin {
@Option(name = "--verbose", aliases = { "-v" }, usage = "usage_beMoreVerbose") @Option(name = "--verbose", aliases = { "-v" }, usage = "usage_beMoreVerbose")
private boolean verbose; private boolean verbose;
protected void showFetchResult(final FetchResult r) { protected void showFetchResult(final FetchResult r) throws IOException {
ObjectReader reader = db.newObjectReader(); ObjectReader reader = db.newObjectReader();
try { try {
boolean shownURI = false; boolean shownURI = false;
@ -77,13 +77,13 @@ abstract class AbstractFetchCommand extends TextBuiltin {
final String dst = abbreviateRef(u.getLocalName(), true); final String dst = abbreviateRef(u.getLocalName(), true);
if (!shownURI) { if (!shownURI) {
out.println(MessageFormat.format(CLIText.get().fromURI, outw.println(MessageFormat.format(CLIText.get().fromURI,
r.getURI())); r.getURI()));
shownURI = true; shownURI = true;
} }
out.format(" %c %-17s %-10s -> %s", type, longType, src, dst); outw.format(" %c %-17s %-10s -> %s", type, longType, src, dst);
out.println(); outw.println();
} }
} finally { } finally {
reader.release(); reader.release();

6
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/AmazonS3Client.java

@ -86,21 +86,23 @@ class AmazonS3Client extends TextBuiltin {
int len = c.getContentLength(); int len = c.getContentLength();
final InputStream in = c.getInputStream(); final InputStream in = c.getInputStream();
try { try {
outw.flush();
final byte[] tmp = new byte[2048]; final byte[] tmp = new byte[2048];
while (len > 0) { while (len > 0) {
final int n = in.read(tmp); final int n = in.read(tmp);
if (n < 0) if (n < 0)
throw new EOFException(MessageFormat.format(CLIText.get().expectedNumberOfbytes, len)); throw new EOFException(MessageFormat.format(CLIText.get().expectedNumberOfbytes, len));
System.out.write(tmp, 0, n); outs.write(tmp, 0, n);
len -= n; len -= n;
} }
outs.flush();
} finally { } finally {
in.close(); in.close();
} }
} else if ("ls".equals(op) || "list".equals(op)) { } else if ("ls".equals(op) || "list".equals(op)) {
for (final String k : s3.list(bucket, key)) for (final String k : s3.list(bucket, key))
System.out.println(k); outw.println(k);
} else if ("rm".equals(op) || "delete".equals(op)) { } else if ("rm".equals(op) || "delete".equals(op)) {
s3.delete(bucket, key); s3.delete(bucket, key);

17
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Blame.java

@ -210,17 +210,18 @@ class Blame extends TextBuiltin {
authorWidth, dateWidth); authorWidth, dateWidth);
for (int line = begin; line < end; line++) { for (int line = begin; line < end; line++) {
out.print(abbreviate(blame.getSourceCommit(line))); outw.print(abbreviate(blame.getSourceCommit(line)));
if (showSourcePath) if (showSourcePath)
out.format(pathFmt, path(line)); outw.format(pathFmt, path(line));
if (showSourceLine) if (showSourceLine)
out.format(numFmt, blame.getSourceLine(line) + 1); outw.format(numFmt, blame.getSourceLine(line) + 1);
if (!noAuthor) if (!noAuthor)
out.format(authorFmt, author(line), date(line)); outw.format(authorFmt, author(line), date(line));
out.format(lineFmt, line + 1); outw.format(lineFmt, line + 1);
out.flush(); outw.flush();
blame.getResultContents().writeLine(System.out, line); blame.getResultContents().writeLine(outs, line);
out.print('\n'); outs.flush();
outw.print('\n');
} }
} finally { } finally {
generator.release(); generator.release();

20
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Branch.java

@ -215,18 +215,18 @@ class Branch extends TextBuiltin {
private void printHead(final ObjectReader reader, final String ref, private void printHead(final ObjectReader reader, final String ref,
final boolean isCurrent, final Ref refObj) throws Exception { final boolean isCurrent, final Ref refObj) throws Exception {
out.print(isCurrent ? '*' : ' '); outw.print(isCurrent ? '*' : ' ');
out.print(' '); outw.print(' ');
out.print(ref); outw.print(ref);
if (verbose) { if (verbose) {
final int spaces = maxNameLength - ref.length() + 1; final int spaces = maxNameLength - ref.length() + 1;
out.format("%" + spaces + "s", ""); outw.format("%" + spaces + "s", "");
final ObjectId objectId = refObj.getObjectId(); final ObjectId objectId = refObj.getObjectId();
out.print(reader.abbreviate(objectId).name()); outw.print(reader.abbreviate(objectId).name());
out.print(' '); outw.print(' ');
out.print(rw.parseCommit(objectId).getShortMessage()); outw.print(rw.parseCommit(objectId).getShortMessage());
} }
out.println(); outw.println();
} }
private void delete(boolean force) throws IOException { private void delete(boolean force) throws IOException {
@ -247,9 +247,9 @@ class Branch extends TextBuiltin {
} else if (result == Result.NEW) } else if (result == Result.NEW)
throw die(MessageFormat.format(CLIText.get().branchNotFound, branch)); throw die(MessageFormat.format(CLIText.get().branchNotFound, branch));
if (remote) if (remote)
out.println(MessageFormat.format(CLIText.get().deletedRemoteBranch, branch)); outw.println(MessageFormat.format(CLIText.get().deletedRemoteBranch, branch));
else if (verbose) else if (verbose)
out.println(MessageFormat.format(CLIText.get().deletedBranch, branch)); outw.println(MessageFormat.format(CLIText.get().deletedBranch, branch));
} }
} }
} }

1
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/CLIText.java

@ -217,6 +217,7 @@ public class CLIText extends TranslationBundle {
/***/ public String taggerInfo; /***/ public String taggerInfo;
/***/ public String timeInMilliSeconds; /***/ public String timeInMilliSeconds;
/***/ public String tooManyRefsGiven; /***/ public String tooManyRefsGiven;
/***/ public char[] unknownIoErrorStdout;
/***/ public String unknownMergeStrategy; /***/ public String unknownMergeStrategy;
/***/ public String unmergedPaths; /***/ public String unmergedPaths;
/***/ public String unsupportedOperation; /***/ public String unsupportedOperation;

10
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Checkout.java

@ -84,20 +84,22 @@ class Checkout extends TextBuiltin {
String oldBranch = db.getBranch(); String oldBranch = db.getBranch();
Ref ref = command.call(); Ref ref = command.call();
if (Repository.shortenRefName(ref.getName()).equals(oldBranch)) { if (Repository.shortenRefName(ref.getName()).equals(oldBranch)) {
out.println(MessageFormat.format(CLIText.get().alreadyOnBranch, outw.println(MessageFormat.format(
CLIText.get().alreadyOnBranch,
name)); name));
return; return;
} }
if (createBranch) if (createBranch)
out.println(MessageFormat.format( outw.println(MessageFormat.format(
CLIText.get().switchedToNewBranch, CLIText.get().switchedToNewBranch,
Repository.shortenRefName(ref.getName()))); Repository.shortenRefName(ref.getName())));
else else
out.println(MessageFormat.format( outw.println(MessageFormat.format(
CLIText.get().switchedToBranch, CLIText.get().switchedToBranch,
Repository.shortenRefName(ref.getName()))); Repository.shortenRefName(ref.getName())));
} catch (RefNotFoundException e) { } catch (RefNotFoundException e) {
out.println(MessageFormat.format(CLIText.get().pathspecDidNotMatch, outw.println(MessageFormat.format(
CLIText.get().pathspecDidNotMatch,
name)); name));
} catch (RefAlreadyExistsException e) { } catch (RefAlreadyExistsException e) {
throw die(MessageFormat.format(CLIText.get().branchAlreadyExists, throw die(MessageFormat.format(CLIText.get().branchAlreadyExists,

11
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Clone.java

@ -55,8 +55,6 @@ import org.eclipse.jgit.dircache.DirCache;
import org.eclipse.jgit.dircache.DirCacheCheckout; import org.eclipse.jgit.dircache.DirCacheCheckout;
import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.errors.NotSupportedException;
import org.eclipse.jgit.errors.TransportException;
import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.RefComparator; import org.eclipse.jgit.lib.RefComparator;
@ -116,10 +114,10 @@ class Clone extends AbstractFetchCommand {
dstcfg.save(); dstcfg.save();
db = dst; db = dst;
out.print(MessageFormat.format( outw.print(MessageFormat.format(
CLIText.get().initializedEmptyGitRepositoryIn, gitdir)); CLIText.get().initializedEmptyGitRepositoryIn, gitdir));
out.println(); outw.println();
out.flush(); outw.flush();
saveRemote(uri); saveRemote(uri);
final FetchResult r = runFetch(); final FetchResult r = runFetch();
@ -139,8 +137,7 @@ class Clone extends AbstractFetchCommand {
dstcfg.save(); dstcfg.save();
} }
private FetchResult runFetch() throws NotSupportedException, private FetchResult runFetch() throws URISyntaxException, IOException {
URISyntaxException, TransportException {
final Transport tn = Transport.open(db, remoteName); final Transport tn = Transport.open(db, remoteName);
final FetchResult r; final FetchResult r;
try { try {

2
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Commit.java

@ -109,7 +109,7 @@ class Commit extends TextBuiltin {
if (branchName.startsWith(Constants.R_HEADS)) if (branchName.startsWith(Constants.R_HEADS))
branchName = branchName.substring(Constants.R_HEADS.length()); branchName = branchName.substring(Constants.R_HEADS.length());
} }
out.println("[" + branchName + " " + commit.name() + "] " outw.println("[" + branchName + " " + commit.name() + "] "
+ commit.getShortMessage()); + commit.getShortMessage());
} }
} }

4
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Config.java

@ -103,7 +103,7 @@ class Config extends TextBuiltin {
Set<String> names = config.getNames(section); Set<String> names = config.getNames(section);
for (String name : names) { for (String name : names) {
for (String value : config.getStringList(section, null, name)) for (String value : config.getStringList(section, null, name))
out.println(section + "." + name + "=" + value); outw.println(section + "." + name + "=" + value);
} }
if (names.isEmpty()) { if (names.isEmpty()) {
for (String subsection : config.getSubsections(section)) { for (String subsection : config.getSubsections(section)) {
@ -111,7 +111,7 @@ class Config extends TextBuiltin {
for (String name : names) { for (String name : names) {
for (String value : config.getStringList(section, for (String value : config.getStringList(section,
subsection, name)) subsection, name))
out.println(section + "." + subsection + "." outw.println(section + "." + subsection + "."
+ name + "=" + value); + name + "=" + value);
} }
} }

4
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Daemon.java

@ -127,7 +127,7 @@ class Daemon extends TextBuiltin {
final FileResolver<DaemonClient> resolver = new FileResolver<DaemonClient>(); final FileResolver<DaemonClient> resolver = new FileResolver<DaemonClient>();
for (final File f : directory) { for (final File f : directory) {
out.println(MessageFormat.format(CLIText.get().exporting, f.getAbsolutePath())); outw.println(MessageFormat.format(CLIText.get().exporting, f.getAbsolutePath()));
resolver.exportDirectory(f); resolver.exportDirectory(f);
} }
resolver.setExportAll(exportAll); resolver.setExportAll(exportAll);
@ -152,7 +152,7 @@ class Daemon extends TextBuiltin {
service(d, n).setOverridable(false); service(d, n).setOverridable(false);
d.start(); d.start();
out.println(MessageFormat.format(CLIText.get().listeningOn, d.getAddress())); outw.println(MessageFormat.format(CLIText.get().listeningOn, d.getAddress()));
} }
private DaemonService service(final org.eclipse.jgit.transport.Daemon d, private DaemonService service(final org.eclipse.jgit.transport.Daemon d,

12
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Diff.java

@ -49,7 +49,7 @@ import static org.eclipse.jgit.lib.Constants.HEAD;
import static org.eclipse.jgit.lib.Constants.OBJECT_ID_STRING_LENGTH; import static org.eclipse.jgit.lib.Constants.OBJECT_ID_STRING_LENGTH;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.PrintWriter; import java.io.IOException;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -69,13 +69,14 @@ import org.eclipse.jgit.treewalk.AbstractTreeIterator;
import org.eclipse.jgit.treewalk.CanonicalTreeParser; import org.eclipse.jgit.treewalk.CanonicalTreeParser;
import org.eclipse.jgit.treewalk.FileTreeIterator; import org.eclipse.jgit.treewalk.FileTreeIterator;
import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.eclipse.jgit.treewalk.filter.TreeFilter;
import org.eclipse.jgit.util.io.ThrowingPrintWriter;
import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option; import org.kohsuke.args4j.Option;
@Command(common = true, usage = "usage_ShowDiffs") @Command(common = true, usage = "usage_ShowDiffs")
class Diff extends TextBuiltin { class Diff extends TextBuiltin {
private final DiffFormatter diffFmt = new DiffFormatter( // private final DiffFormatter diffFmt = new DiffFormatter( //
new BufferedOutputStream(System.out)); new BufferedOutputStream(outs));
@Argument(index = 0, metaVar = "metaVar_treeish") @Argument(index = 0, metaVar = "metaVar_treeish")
private AbstractTreeIterator oldTree; private AbstractTreeIterator oldTree;
@ -202,8 +203,8 @@ class Diff extends TextBuiltin {
} }
if (showNameAndStatusOnly) { if (showNameAndStatusOnly) {
nameStatus(out, diffFmt.scan(oldTree, newTree)); nameStatus(outw, diffFmt.scan(oldTree, newTree));
out.flush(); outw.flush();
} else { } else {
diffFmt.format(oldTree, newTree); diffFmt.format(oldTree, newTree);
@ -214,7 +215,8 @@ class Diff extends TextBuiltin {
} }
} }
static void nameStatus(PrintWriter out, List<DiffEntry> files) { static void nameStatus(ThrowingPrintWriter out, List<DiffEntry> files)
throws IOException {
for (DiffEntry ent : files) { for (DiffEntry ent : files) {
switch (ent.getChangeType()) { switch (ent.getChangeType()) {
case ADD: case ADD:

20
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/DiffTree.java

@ -82,19 +82,19 @@ class DiffTree extends TextBuiltin {
final int nTree = walk.getTreeCount(); final int nTree = walk.getTreeCount();
while (walk.next()) { while (walk.next()) {
for (int i = 1; i < nTree; i++) for (int i = 1; i < nTree; i++)
out.print(':'); outw.print(':');
for (int i = 0; i < nTree; i++) { for (int i = 0; i < nTree; i++) {
final FileMode m = walk.getFileMode(i); final FileMode m = walk.getFileMode(i);
final String s = m.toString(); final String s = m.toString();
for (int pad = 6 - s.length(); pad > 0; pad--) for (int pad = 6 - s.length(); pad > 0; pad--)
out.print('0'); outw.print('0');
out.print(s); outw.print(s);
out.print(' '); outw.print(' ');
} }
for (int i = 0; i < nTree; i++) { for (int i = 0; i < nTree; i++) {
out.print(walk.getObjectId(i).name()); outw.print(walk.getObjectId(i).name());
out.print(' '); outw.print(' ');
} }
char chg = 'M'; char chg = 'M';
@ -108,11 +108,11 @@ class DiffTree extends TextBuiltin {
else if (m0 != m1 && walk.idEqual(0, 1)) else if (m0 != m1 && walk.idEqual(0, 1))
chg = 'T'; chg = 'T';
} }
out.print(chg); outw.print(chg);
out.print('\t'); outw.print('\t');
out.print(walk.getPathString()); outw.print(walk.getPathString());
out.println(); outw.println();
} }
} }
} }

2
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Init.java

@ -72,7 +72,7 @@ class Init extends TextBuiltin {
if (gitdir != null) if (gitdir != null)
command.setDirectory(new File(gitdir)); command.setDirectory(new File(gitdir));
Repository repository = command.call().getRepository(); Repository repository = command.call().getRepository();
out.println(MessageFormat.format( outw.println(MessageFormat.format(
CLIText.get().initializedEmptyGitRepositoryIn, repository CLIText.get().initializedEmptyGitRepositoryIn, repository
.getDirectory().getAbsolutePath())); .getDirectory().getAbsolutePath()));
} }

60
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Log.java

@ -80,7 +80,7 @@ class Log extends RevWalkTextBuiltin {
Format.DEFAULT); Format.DEFAULT);
private final DiffFormatter diffFmt = new DiffFormatter( // private final DiffFormatter diffFmt = new DiffFormatter( //
new BufferedOutputStream(System.out)); new BufferedOutputStream(outs));
private Map<AnyObjectId, Set<Ref>> allRefsByPeeledObjectId; private Map<AnyObjectId, Set<Ref>> allRefsByPeeledObjectId;
@ -231,43 +231,43 @@ class Log extends RevWalkTextBuiltin {
@Override @Override
protected void show(final RevCommit c) throws Exception { protected void show(final RevCommit c) throws Exception {
out.print(CLIText.get().commitLabel); outw.print(CLIText.get().commitLabel);
out.print(" "); outw.print(" ");
c.getId().copyTo(outbuffer, out); c.getId().copyTo(outbuffer, outw);
if (decorate) { if (decorate) {
Collection<Ref> list = allRefsByPeeledObjectId.get(c); Collection<Ref> list = allRefsByPeeledObjectId.get(c);
if (list != null) { if (list != null) {
out.print(" ("); outw.print(" (");
for (Iterator<Ref> i = list.iterator(); i.hasNext(); ) { for (Iterator<Ref> i = list.iterator(); i.hasNext(); ) {
out.print(i.next().getName()); outw.print(i.next().getName());
if (i.hasNext()) if (i.hasNext())
out.print(" "); outw.print(" ");
} }
out.print(")"); outw.print(")");
} }
} }
out.println(); outw.println();
final PersonIdent author = c.getAuthorIdent(); final PersonIdent author = c.getAuthorIdent();
out.println(MessageFormat.format(CLIText.get().authorInfo, author.getName(), author.getEmailAddress())); outw.println(MessageFormat.format(CLIText.get().authorInfo, author.getName(), author.getEmailAddress()));
out.println(MessageFormat.format(CLIText.get().dateInfo, outw.println(MessageFormat.format(CLIText.get().dateInfo,
dateFormatter.formatDate(author))); dateFormatter.formatDate(author)));
out.println(); outw.println();
final String[] lines = c.getFullMessage().split("\n"); final String[] lines = c.getFullMessage().split("\n");
for (final String s : lines) { for (final String s : lines) {
out.print(" "); outw.print(" ");
out.print(s); outw.print(s);
out.println(); outw.println();
} }
out.println(); outw.println();
if (showNotes(c)) if (showNotes(c))
out.println(); outw.println();
if (c.getParentCount() == 1 && (showNameAndStatusOnly || showPatch)) if (c.getParentCount() == 1 && (showNameAndStatusOnly || showPatch))
showDiff(c); showDiff(c);
out.flush(); outw.flush();
} }
/** /**
@ -315,23 +315,23 @@ class Log extends RevWalkTextBuiltin {
if (blobId == null) if (blobId == null)
return false; return false;
if (emptyLine) if (emptyLine)
out.println(); outw.println();
out.print("Notes"); outw.print("Notes");
if (label != null) { if (label != null) {
out.print(" ("); outw.print(" (");
out.print(label); outw.print(label);
out.print(")"); outw.print(")");
} }
out.println(":"); outw.println(":");
try { try {
RawText rawText = new RawText(argWalk.getObjectReader() RawText rawText = new RawText(argWalk.getObjectReader()
.open(blobId).getCachedBytes(Integer.MAX_VALUE)); .open(blobId).getCachedBytes(Integer.MAX_VALUE));
for (int i = 0; i < rawText.size(); i++) { for (int i = 0; i < rawText.size(); i++) {
out.print(" "); outw.print(" ");
out.println(rawText.getString(i)); outw.println(rawText.getString(i));
} }
} catch (LargeObjectException e) { } catch (LargeObjectException e) {
out.println(MessageFormat.format( outw.println(MessageFormat.format(
CLIText.get().noteObjectTooLargeToPrint, blobId.name())); CLIText.get().noteObjectTooLargeToPrint, blobId.name()));
} }
return true; return true;
@ -342,12 +342,12 @@ class Log extends RevWalkTextBuiltin {
final RevTree b = c.getTree(); final RevTree b = c.getTree();
if (showNameAndStatusOnly) if (showNameAndStatusOnly)
Diff.nameStatus(out, diffFmt.scan(a, b)); Diff.nameStatus(outw, diffFmt.scan(a, b));
else { else {
out.flush(); outw.flush();
diffFmt.format(a, b); diffFmt.format(a, b);
diffFmt.flush(); diffFmt.flush();
} }
out.println(); outw.println();
} }
} }

13
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/LsRemote.java

@ -45,6 +45,8 @@
package org.eclipse.jgit.pgm; package org.eclipse.jgit.pgm;
import java.io.IOException;
import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option; import org.kohsuke.args4j.Option;
import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.AnyObjectId;
@ -77,10 +79,11 @@ class LsRemote extends TextBuiltin {
} }
} }
private void show(final AnyObjectId id, final String name) { private void show(final AnyObjectId id, final String name)
out.print(id.name()); throws IOException {
out.print('\t'); outw.print(id.name());
out.print(name); outw.print('\t');
out.println(); outw.print(name);
outw.println();
} }
} }

18
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/LsTree.java

@ -68,17 +68,17 @@ class LsTree extends TextBuiltin {
while (walk.next()) { while (walk.next()) {
final FileMode mode = walk.getFileMode(0); final FileMode mode = walk.getFileMode(0);
if (mode == FileMode.TREE) if (mode == FileMode.TREE)
out.print('0'); outw.print('0');
out.print(mode); outw.print(mode);
out.print(' '); outw.print(' ');
out.print(Constants.typeString(mode.getObjectType())); outw.print(Constants.typeString(mode.getObjectType()));
out.print(' '); outw.print(' ');
out.print(walk.getObjectId(0).name()); outw.print(walk.getObjectId(0).name());
out.print('\t'); outw.print('\t');
out.print(walk.getPathString()); outw.print(walk.getPathString());
out.println(); outw.println();
} }
} }
} }

13
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Main.java

@ -137,6 +137,15 @@ public class Main {
err.printStackTrace(); err.printStackTrace();
System.exit(1); System.exit(1);
} }
if (System.out.checkError()) {
System.err.println(CLIText.get().unknownIoErrorStdout);
System.exit(1);
}
if (System.err.checkError()) {
// No idea how to present an error here, most likely disk full or
// broken pipe
System.exit(1);
}
} }
private void execute(final String[] argv) throws Exception { private void execute(final String[] argv) throws Exception {
@ -190,8 +199,8 @@ public class Main {
try { try {
cmd.execute(arguments.toArray(new String[arguments.size()])); cmd.execute(arguments.toArray(new String[arguments.size()]));
} finally { } finally {
if (cmd.out != null) if (cmd.outw != null)
cmd.out.flush(); cmd.outw.flush();
} }
} }

18
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Merge.java

@ -88,13 +88,13 @@ class Merge extends TextBuiltin {
switch (result.getMergeStatus()) { switch (result.getMergeStatus()) {
case ALREADY_UP_TO_DATE: case ALREADY_UP_TO_DATE:
case FAST_FORWARD: case FAST_FORWARD:
out.println(result.getMergeStatus().toString()); outw.println(result.getMergeStatus().toString());
break; break;
case CONFLICTING: case CONFLICTING:
for (String collidingPath : result.getConflicts().keySet()) for (String collidingPath : result.getConflicts().keySet())
out.println(MessageFormat.format(CLIText.get().mergeConflict, outw.println(MessageFormat.format(CLIText.get().mergeConflict,
collidingPath)); collidingPath));
out.println(CLIText.get().mergeFailed); outw.println(CLIText.get().mergeFailed);
break; break;
case FAILED: case FAILED:
for (Map.Entry<String, MergeFailureReason> entry : result for (Map.Entry<String, MergeFailureReason> entry : result
@ -102,21 +102,21 @@ class Merge extends TextBuiltin {
switch (entry.getValue()) { switch (entry.getValue()) {
case DIRTY_WORKTREE: case DIRTY_WORKTREE:
case DIRTY_INDEX: case DIRTY_INDEX:
out.println(CLIText.get().dontOverwriteLocalChanges); outw.println(CLIText.get().dontOverwriteLocalChanges);
out.println(" " + entry.getKey()); outw.println(" " + entry.getKey());
break; break;
case COULD_NOT_DELETE: case COULD_NOT_DELETE:
out.println(CLIText.get().cannotDeleteFile); outw.println(CLIText.get().cannotDeleteFile);
out.println(" " + entry.getKey()); outw.println(" " + entry.getKey());
break; break;
} }
break; break;
case MERGED: case MERGED:
out.println(MessageFormat.format(CLIText.get().mergeMadeBy, outw.println(MessageFormat.format(CLIText.get().mergeMadeBy,
mergeStrategy.getName())); mergeStrategy.getName()));
break; break;
case NOT_SUPPORTED: case NOT_SUPPORTED:
out.println(MessageFormat.format( outw.println(MessageFormat.format(
CLIText.get().unsupportedOperation, result.toString())); CLIText.get().unsupportedOperation, result.toString()));
} }
} }

2
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/MergeBase.java

@ -74,7 +74,7 @@ class MergeBase extends TextBuiltin {
final RevCommit b = argWalk.next(); final RevCommit b = argWalk.next();
if (b == null) if (b == null)
break; break;
out.println(b.getId().name()); outw.println(b.getId().name());
} }
} }
} }

22
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Push.java

@ -132,7 +132,7 @@ class Push extends TextBuiltin {
} }
private void printPushResult(final ObjectReader reader, final URIish uri, private void printPushResult(final ObjectReader reader, final URIish uri,
final PushResult result) { final PushResult result) throws IOException {
shownURI = false; shownURI = false;
boolean everythingUpToDate = true; boolean everythingUpToDate = true;
@ -160,14 +160,15 @@ class Push extends TextBuiltin {
AbstractFetchCommand.showRemoteMessages(result.getMessages()); AbstractFetchCommand.showRemoteMessages(result.getMessages());
if (everythingUpToDate) if (everythingUpToDate)
out.println(CLIText.get().everythingUpToDate); outw.println(CLIText.get().everythingUpToDate);
} }
private void printRefUpdateResult(final ObjectReader reader, private void printRefUpdateResult(final ObjectReader reader,
final URIish uri, final PushResult result, final RemoteRefUpdate rru) { final URIish uri, final PushResult result, final RemoteRefUpdate rru)
throws IOException {
if (!shownURI) { if (!shownURI) {
shownURI = true; shownURI = true;
out.println(MessageFormat.format(CLIText.get().pushTo, uri)); outw.println(MessageFormat.format(CLIText.get().pushTo, uri));
} }
final String remoteName = rru.getRemoteName(); final String remoteName = rru.getRemoteName();
@ -247,16 +248,17 @@ class Push extends TextBuiltin {
} }
private void printUpdateLine(final char flag, final String summary, private void printUpdateLine(final char flag, final String summary,
final String srcRef, final String destRef, final String message) { final String srcRef, final String destRef, final String message)
out.format(" %c %-17s", flag, summary); throws IOException {
outw.format(" %c %-17s", flag, summary);
if (srcRef != null) if (srcRef != null)
out.format(" %s ->", abbreviateRef(srcRef, true)); outw.format(" %s ->", abbreviateRef(srcRef, true));
out.format(" %s", abbreviateRef(destRef, true)); outw.format(" %s", abbreviateRef(destRef, true));
if (message != null) if (message != null)
out.format(" (%s)", message); outw.format(" (%s)", message);
out.println(); outw.println();
} }
} }

2
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/ReceivePack.java

@ -75,6 +75,6 @@ class ReceivePack extends TextBuiltin {
} }
rp = new org.eclipse.jgit.transport.ReceivePack(db); rp = new org.eclipse.jgit.transport.ReceivePack(db);
rp.receive(System.in, System.out, System.err); rp.receive(System.in, outs, System.err);
} }
} }

22
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/RevList.java

@ -53,29 +53,29 @@ class RevList extends RevWalkTextBuiltin {
@Override @Override
protected void show(final RevCommit c) throws Exception { protected void show(final RevCommit c) throws Exception {
if (c.has(RevFlag.UNINTERESTING)) if (c.has(RevFlag.UNINTERESTING))
out.print('-'); outw.print('-');
c.getId().copyTo(outbuffer, out); c.getId().copyTo(outbuffer, outw);
if (parents) if (parents)
for (int i = 0; i < c.getParentCount(); i++) { for (int i = 0; i < c.getParentCount(); i++) {
out.print(' '); outw.print(' ');
c.getParent(i).getId().copyTo(outbuffer, out); c.getParent(i).getId().copyTo(outbuffer, outw);
} }
out.println(); outw.println();
} }
@Override @Override
protected void show(final ObjectWalk ow, final RevObject obj) protected void show(final ObjectWalk ow, final RevObject obj)
throws Exception { throws Exception {
if (obj.has(RevFlag.UNINTERESTING)) if (obj.has(RevFlag.UNINTERESTING))
out.print('-'); outw.print('-');
obj.getId().copyTo(outbuffer, out); obj.getId().copyTo(outbuffer, outw);
final String path = ow.getPathString(); final String path = ow.getPathString();
if (path != null) { if (path != null) {
out.print(' '); outw.print(' ');
out.print(path); outw.print(path);
} else if (obj instanceof RevTree) } else if (obj instanceof RevTree)
out.print(' '); outw.print(' ');
out.println(); outw.println();
} }
} }

4
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/RevParse.java

@ -65,10 +65,10 @@ class RevParse extends TextBuiltin {
if (all) { if (all) {
Map<String, Ref> allRefs = db.getAllRefs(); Map<String, Ref> allRefs = db.getAllRefs();
for (final Ref r : allRefs.values()) for (final Ref r : allRefs.values())
out.println(r.getObjectId().name()); outw.println(r.getObjectId().name());
} else { } else {
for (final ObjectId o : commits) for (final ObjectId o : commits)
out.println(o.name()); outw.println(o.name());
} }
} }
} }

70
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Show.java

@ -198,16 +198,16 @@ class Show extends TextBuiltin {
break; break;
case Constants.OBJ_TREE: case Constants.OBJ_TREE:
out.print("tree "); outw.print("tree ");
out.print(objectName); outw.print(objectName);
out.println(); outw.println();
out.println(); outw.println();
show((RevTree) obj); show((RevTree) obj);
break; break;
case Constants.OBJ_BLOB: case Constants.OBJ_BLOB:
db.open(obj, obj.getType()).copyTo(System.out); db.open(obj, obj.getType()).copyTo(System.out);
System.out.flush(); outw.flush();
break; break;
default: default:
@ -223,32 +223,32 @@ class Show extends TextBuiltin {
} }
} }
private void show(RevTag tag) { private void show(RevTag tag) throws IOException {
out.print(CLIText.get().tagLabel); outw.print(CLIText.get().tagLabel);
out.print(" "); outw.print(" ");
out.print(tag.getTagName()); outw.print(tag.getTagName());
out.println(); outw.println();
final PersonIdent tagger = tag.getTaggerIdent(); final PersonIdent tagger = tag.getTaggerIdent();
if (tagger != null) { if (tagger != null) {
out.println(MessageFormat.format(CLIText.get().taggerInfo, outw.println(MessageFormat.format(CLIText.get().taggerInfo,
tagger.getName(), tagger.getEmailAddress())); tagger.getName(), tagger.getEmailAddress()));
final TimeZone taggerTZ = tagger.getTimeZone(); final TimeZone taggerTZ = tagger.getTimeZone();
fmt.setTimeZone(taggerTZ != null ? taggerTZ : myTZ); fmt.setTimeZone(taggerTZ != null ? taggerTZ : myTZ);
out.println(MessageFormat.format(CLIText.get().dateInfo, outw.println(MessageFormat.format(CLIText.get().dateInfo,
fmt.format(tagger.getWhen()))); fmt.format(tagger.getWhen())));
} }
out.println(); outw.println();
final String[] lines = tag.getFullMessage().split("\n"); final String[] lines = tag.getFullMessage().split("\n");
for (final String s : lines) { for (final String s : lines) {
out.print(" "); outw.print(" ");
out.print(s); outw.print(s);
out.println(); outw.println();
} }
out.println(); outw.println();
} }
private void show(RevTree obj) throws MissingObjectException, private void show(RevTree obj) throws MissingObjectException,
@ -258,45 +258,45 @@ class Show extends TextBuiltin {
walk.addTree(obj); walk.addTree(obj);
while (walk.next()) { while (walk.next()) {
out.print(walk.getPathString()); outw.print(walk.getPathString());
final FileMode mode = walk.getFileMode(0); final FileMode mode = walk.getFileMode(0);
if (mode == FileMode.TREE) if (mode == FileMode.TREE)
out.print('/'); outw.print("/");
out.println(); outw.println();
} }
} }
private void show(RevWalk rw, final RevCommit c) throws Exception { private void show(RevWalk rw, final RevCommit c) throws Exception {
char[] outbuffer = new char[Constants.OBJECT_ID_LENGTH * 2]; char[] outbuffer = new char[Constants.OBJECT_ID_LENGTH * 2];
out.print(CLIText.get().commitLabel); outw.print(CLIText.get().commitLabel);
out.print(" "); outw.print(" ");
c.getId().copyTo(outbuffer, out); c.getId().copyTo(outbuffer, outw);
out.println(); outw.println();
final PersonIdent author = c.getAuthorIdent(); final PersonIdent author = c.getAuthorIdent();
out.println(MessageFormat.format(CLIText.get().authorInfo, outw.println(MessageFormat.format(CLIText.get().authorInfo,
author.getName(), author.getEmailAddress())); author.getName(), author.getEmailAddress()));
final TimeZone authorTZ = author.getTimeZone(); final TimeZone authorTZ = author.getTimeZone();
fmt.setTimeZone(authorTZ != null ? authorTZ : myTZ); fmt.setTimeZone(authorTZ != null ? authorTZ : myTZ);
out.println(MessageFormat.format(CLIText.get().dateInfo, outw.println(MessageFormat.format(CLIText.get().dateInfo,
fmt.format(author.getWhen()))); fmt.format(author.getWhen())));
out.println(); outw.println();
final String[] lines = c.getFullMessage().split("\n"); final String[] lines = c.getFullMessage().split("\n");
for (final String s : lines) { for (final String s : lines) {
out.print(" "); outw.print(" ");
out.print(s); outw.print(s);
out.println(); outw.println();
} }
out.println(); outw.println();
if (c.getParentCount() == 1) { if (c.getParentCount() == 1) {
rw.parseHeaders(c.getParent(0)); rw.parseHeaders(c.getParent(0));
showDiff(c); showDiff(c);
} }
out.flush(); outw.flush();
} }
private void showDiff(RevCommit c) throws IOException { private void showDiff(RevCommit c) throws IOException {
@ -304,12 +304,12 @@ class Show extends TextBuiltin {
final RevTree b = c.getTree(); final RevTree b = c.getTree();
if (showNameAndStatusOnly) if (showNameAndStatusOnly)
Diff.nameStatus(out, diffFmt.scan(a, b)); Diff.nameStatus(outw, diffFmt.scan(a, b));
else { else {
out.flush(); outw.flush();
diffFmt.format(a, b); diffFmt.format(a, b);
diffFmt.flush(); diffFmt.flush();
} }
out.println(); outw.println();
} }
} }

12
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/ShowRef.java

@ -45,6 +45,7 @@
package org.eclipse.jgit.pgm; package org.eclipse.jgit.pgm;
import java.io.IOException;
import java.util.Map; import java.util.Map;
import java.util.SortedMap; import java.util.SortedMap;
@ -71,10 +72,11 @@ class ShowRef extends TextBuiltin {
return RefComparator.sort(all.values()); return RefComparator.sort(all.values());
} }
private void show(final AnyObjectId id, final String name) { private void show(final AnyObjectId id, final String name)
out.print(id.name()); throws IOException {
out.print('\t'); outw.print(id.name());
out.print(name); outw.print('\t');
out.println(); outw.print(name);
outw.println();
} }
} }

2
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Tag.java

@ -91,7 +91,7 @@ class Tag extends TextBuiltin {
ListTagCommand command = git.tagList(); ListTagCommand command = git.tagList();
List<Ref> list = command.call(); List<Ref> list = command.call();
for (Ref ref : list) { for (Ref ref : list) {
out.println(Repository.shortenRefName(ref.getName())); outw.println(Repository.shortenRefName(ref.getName()));
} }
} }
} }

26
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/TextBuiltin.java

@ -49,7 +49,10 @@ import static org.eclipse.jgit.lib.Constants.R_REMOTES;
import static org.eclipse.jgit.lib.Constants.R_TAGS; import static org.eclipse.jgit.lib.Constants.R_TAGS;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.text.MessageFormat; import java.text.MessageFormat;
@ -59,6 +62,7 @@ import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.pgm.opt.CmdLineParser; import org.eclipse.jgit.pgm.opt.CmdLineParser;
import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.util.io.ThrowingPrintWriter;
import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.Option; import org.kohsuke.args4j.Option;
@ -79,7 +83,17 @@ public abstract class TextBuiltin {
@Option(name = "--help", usage = "usage_displayThisHelpText", aliases = { "-h" }) @Option(name = "--help", usage = "usage_displayThisHelpText", aliases = { "-h" })
private boolean help; private boolean help;
/** Writer to output to, typically this is standard output. */
protected ThrowingPrintWriter outw;
/** Stream to output to, typically this is standard output. */ /** Stream to output to, typically this is standard output. */
protected OutputStream outs;
/**
* Stream to output to, typically this is standard output.
*
* @deprecated Use outw instead
*/
protected PrintWriter out; protected PrintWriter out;
/** Git repository the command was invoked within. */ /** Git repository the command was invoked within. */
@ -114,12 +128,16 @@ public abstract class TextBuiltin {
final String outputEncoding = repository != null ? repository final String outputEncoding = repository != null ? repository
.getConfig() .getConfig()
.getString("i18n", null, "logOutputEncoding") : null; .getString("i18n", null, "logOutputEncoding") : null;
if (outs == null)
outs = new FileOutputStream(FileDescriptor.out);
BufferedWriter bufw;
if (outputEncoding != null) if (outputEncoding != null)
out = new PrintWriter(new BufferedWriter( bufw = new BufferedWriter(new OutputStreamWriter(outs,
new OutputStreamWriter(System.out, outputEncoding))); outputEncoding));
else else
out = new PrintWriter(new BufferedWriter( bufw = new BufferedWriter(new OutputStreamWriter(outs));
new OutputStreamWriter(System.out))); out = new PrintWriter(bufw);
outw = new ThrowingPrintWriter(bufw);
} catch (IOException e) { } catch (IOException e) {
throw die(CLIText.get().cannotCreateOutputStream); throw die(CLIText.get().cannotCreateOutputStream);
} }

2
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/UploadPack.java

@ -81,6 +81,6 @@ class UploadPack extends TextBuiltin {
up = new org.eclipse.jgit.transport.UploadPack(db); up = new org.eclipse.jgit.transport.UploadPack(db);
if (0 <= timeout) if (0 <= timeout)
up.setTimeout(timeout); up.setTimeout(timeout);
up.upload(System.in, System.out, System.err); up.upload(System.in, outs, System.err);
} }
} }

2
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Version.java

@ -53,7 +53,7 @@ class Version extends TextBuiltin {
if (pkg == null || pkg.getImplementationVersion() == null) if (pkg == null || pkg.getImplementationVersion() == null)
throw die(CLIText.get().cannotReadPackageInformation); throw die(CLIText.get().cannotReadPackageInformation);
out.println(MessageFormat.format(CLIText.get().jgitVersion, pkg.getImplementationVersion())); outw.println(MessageFormat.format(CLIText.get().jgitVersion, pkg.getImplementationVersion()));
} }
@Override @Override

20
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/debug/DiffAlgorithms.java

@ -245,29 +245,29 @@ class DiffAlgorithms extends TextBuiltin {
File parent = db.getDirectory().getParentFile(); File parent = db.getDirectory().getParentFile();
if (name.equals(Constants.DOT_GIT) && parent != null) if (name.equals(Constants.DOT_GIT) && parent != null)
name = parent.getName(); name = parent.getName();
out.println(name + ": start at " + startId.name()); outw.println(name + ": start at " + startId.name());
} }
out.format(" %12d files, %8d commits\n", files, commits); outw.format(" %12d files, %8d commits\n", files, commits);
out.format(" N=%10d min lines, %8d max lines\n", minN, maxN); outw.format(" N=%10d min lines, %8d max lines\n", minN, maxN);
out.format("%-25s %12s ( %12s %12s )\n", // outw.format("%-25s %12s ( %12s %12s )\n", //
"Algorithm", "Time(ns)", "Time(ns) on", "Time(ns) on"); "Algorithm", "Time(ns)", "Time(ns) on", "Time(ns) on");
out.format("%-25s %12s ( %12s %12s )\n", // outw.format("%-25s %12s ( %12s %12s )\n", //
"", "", "N=" + minN, "N=" + maxN); "", "", "N=" + minN, "N=" + maxN);
out.println("-----------------------------------------------------" outw.println("-----------------------------------------------------"
+ "----------------"); + "----------------");
for (Test test : all) { for (Test test : all) {
out.format("%-25s %12d ( %12d %12d )", // outw.format("%-25s %12d ( %12d %12d )", //
test.algorithm.name, // test.algorithm.name, //
test.runningTimeNanos, // test.runningTimeNanos, //
test.minN.runningTimeNanos, // test.minN.runningTimeNanos, //
test.maxN.runningTimeNanos); test.maxN.runningTimeNanos);
out.println(); outw.println();
} }
out.println(); outw.println();
out.flush(); outw.flush();
} }
private static boolean isFile(TreeWalk tw, int ithTree) { private static boolean isFile(TreeWalk tw, int ithTree) {

5
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/debug/MakeCacheTree.java

@ -44,6 +44,7 @@
package org.eclipse.jgit.pgm.debug; package org.eclipse.jgit.pgm.debug;
import java.io.IOException;
import java.text.MessageFormat; import java.text.MessageFormat;
import org.eclipse.jgit.dircache.DirCache; import org.eclipse.jgit.dircache.DirCache;
@ -59,8 +60,8 @@ class MakeCacheTree extends TextBuiltin {
show(tree); show(tree);
} }
private void show(final DirCacheTree tree) { private void show(final DirCacheTree tree) throws IOException {
out.println(MessageFormat.format(CLIText.get().cacheTreePathInfo outw.println(MessageFormat.format(CLIText.get().cacheTreePathInfo
, tree.getPathString(), tree.getEntrySpan(), tree.getChildCount())); , tree.getPathString(), tree.getEntrySpan(), tree.getChildCount()));
for (int i = 0; i < tree.getChildCount(); i++) for (int i = 0; i < tree.getChildCount(); i++)

4
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/debug/ReadDirCache.java

@ -57,7 +57,7 @@ class ReadDirCache extends TextBuiltin {
for (int i = 0; i < cnt; i++) for (int i = 0; i < cnt; i++)
db.readDirCache(); db.readDirCache();
final long end = System.currentTimeMillis(); final long end = System.currentTimeMillis();
out.print(" "); outw.print(" ");
out.println(MessageFormat.format(CLIText.get().averageMSPerRead, (end - start) / cnt)); outw.println(MessageFormat.format(CLIText.get().averageMSPerRead, (end - start) / cnt));
} }
} }

5
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/debug/ShowCacheTree.java

@ -44,6 +44,7 @@
package org.eclipse.jgit.pgm.debug; package org.eclipse.jgit.pgm.debug;
import java.io.IOException;
import java.text.MessageFormat; import java.text.MessageFormat;
import org.eclipse.jgit.dircache.DirCache; import org.eclipse.jgit.dircache.DirCache;
@ -61,8 +62,8 @@ class ShowCacheTree extends TextBuiltin {
show(tree); show(tree);
} }
private void show(final DirCacheTree tree) { private void show(final DirCacheTree tree) throws IOException {
out.println(MessageFormat.format(CLIText.get().cacheTreePathInfo outw.println(MessageFormat.format(CLIText.get().cacheTreePathInfo
, tree.getPathString(), tree.getEntrySpan(), tree.getChildCount())); , tree.getPathString(), tree.getEntrySpan(), tree.getChildCount()));
for (int i = 0; i < tree.getChildCount(); i++) for (int i = 0; i < tree.getChildCount(); i++)

22
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/debug/ShowDirCache.java

@ -68,17 +68,17 @@ class ShowDirCache extends TextBuiltin {
final Date mtime = new Date(ent.getLastModified()); final Date mtime = new Date(ent.getLastModified());
final int stage = ent.getStage(); final int stage = ent.getStage();
out.print(mode); outw.print(mode);
out.format(" %6d", len); outw.format(" %6d", len);
out.print(' '); outw.print(' ');
out.print(fmt.format(mtime)); outw.print(fmt.format(mtime));
out.print(' '); outw.print(' ');
out.print(ent.getObjectId().name()); outw.print(ent.getObjectId().name());
out.print(' '); outw.print(' ');
out.print(stage); outw.print(stage);
out.print('\t'); outw.print('\t');
out.print(ent.getPathString()); outw.print(ent.getPathString());
out.println(); outw.println();
} }
} }
} }

2
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/debug/ShowPackDelta.java

@ -87,7 +87,7 @@ class ShowPackDelta extends TextBuiltin {
throw die("Object " + obj.name() + " is not a delta"); throw die("Object " + obj.name() + " is not a delta");
} }
out.println(BinaryDelta.format(delta)); outw.println(BinaryDelta.format(delta));
} }
private byte[] getDelta(ObjectReader reader, RevObject obj) private byte[] getDelta(ObjectReader reader, RevObject obj)

14
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/debug/TextHashFunctions.java

@ -344,26 +344,26 @@ class TextHashFunctions extends TextBuiltin {
File parent = db.getDirectory().getParentFile(); File parent = db.getDirectory().getParentFile();
if (name.equals(Constants.DOT_GIT) && parent != null) if (name.equals(Constants.DOT_GIT) && parent != null)
name = parent.getName(); name = parent.getName();
out.println(name + ":"); outw.println(name + ":");
} }
out.format(" %6d files; %5d avg. unique lines/file\n", // outw.format(" %6d files; %5d avg. unique lines/file\n", //
fileCnt, // fileCnt, //
lineCnt / fileCnt); lineCnt / fileCnt);
out.format("%-20s %-15s %9s\n", "Hash", "Fold", "Max Len"); outw.format("%-20s %-15s %9s\n", "Hash", "Fold", "Max Len");
out.println("-----------------------------------------------"); outw.println("-----------------------------------------------");
String lastHashName = null; String lastHashName = null;
for (Function fun : all) { for (Function fun : all) {
String hashName = fun.hash.name; String hashName = fun.hash.name;
if (hashName.equals(lastHashName)) if (hashName.equals(lastHashName))
hashName = ""; hashName = "";
out.format("%-20s %-15s %9d\n", // outw.format("%-20s %-15s %9d\n", //
hashName, // hashName, //
fun.fold.name, // fun.fold.name, //
fun.maxChainLength); fun.maxChainLength);
lastHashName = fun.hash.name; lastHashName = fun.hash.name;
} }
out.println(); outw.println();
out.flush(); outw.flush();
} }
private void testOne(Function fun, RawText txt, int[] elements, int cnt) { private void testOne(Function fun, RawText txt, int[] elements, int cnt) {

4
org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/eclipse/Iplog.java

@ -114,8 +114,8 @@ class Iplog extends TextBuiltin {
lf.unlock(); lf.unlock();
} }
} else { } else {
log.writeTo(System.out); log.writeTo(outs);
System.out.flush(); outs.flush();
} }
} }
} }

171
org.eclipse.jgit/src/org/eclipse/jgit/util/io/ThrowingPrintWriter.java

@ -0,0 +1,171 @@
/*
* Copyright (C) 2012, Robin Rosenberg <robin.rosenberg@dewire.com>
* and other copyright owners as documented in the project's IP log.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Distribution License v1.0 which
* accompanies this distribution, is reproduced below, and is
* available at http://www.eclipse.org/org/documents/edl-v10.php
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name of the Eclipse Foundation, Inc. nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.eclipse.jgit.util.io;
import java.io.IOException;
import java.io.Writer;
import java.security.AccessController;
import java.security.PrivilegedAction;
import org.eclipse.jgit.util.SystemReader;
/**
* An alternative PrintWriter that doesn't catch exceptions.
*/
public class ThrowingPrintWriter extends Writer {
private final Writer out;
private final String LF;
/**
* Construct a JGitPrintWriter
*
* @param out
* the underlying {@link Writer}
*/
public ThrowingPrintWriter(Writer out) {
this.out = out;
LF = AccessController.doPrivileged(new PrivilegedAction<String>() {
public String run() {
return SystemReader.getInstance().getProperty("line.separator");
}
});
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
out.write(cbuf, off, len);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
out.close();
}
/**
* Print a string and terminate with a line feed.
*
* @param s
* @throws IOException
*/
public void println(String s) throws IOException {
print(s + LF);
}
/**
* Print a platform dependent new line
*
* @throws IOException
*/
public void println() throws IOException {
print(LF);
}
/**
* Print a char
*
* @param value
* @throws IOException
*/
public void print(char value) throws IOException {
print(String.valueOf(value));
}
/**
* Print an int as string
*
* @param value
* @throws IOException
*/
public void print(int value) throws IOException {
print(String.valueOf(value));
}
/**
* Print a long as string
*
* @param value
* @throws IOException
*/
public void print(long value) throws IOException {
print(String.valueOf(value));
}
/**
* Print a short as string
*
* @param value
* @throws IOException
*/
public void print(short value) throws IOException {
print(String.valueOf(value));
}
/**
* Print a formatted message according to
* {@link String#format(String, Object...)}.
*
* @param fmt
* @param args
* @throws IOException
*/
public void format(String fmt, Object... args) throws IOException {
print(String.format(fmt, args));
}
/**
* Print an object's toString representations
*
* @param any
* @throws IOException
*/
public void print(Object any) throws IOException {
out.write(String.valueOf(any));
}
}
Loading…
Cancel
Save