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
This commit is contained in:
Robin Rosenberg 2012-09-14 18:48:56 +02:00 committed by Shawn O. Pearce
parent 1a07ddca85
commit caa362f20d
42 changed files with 439 additions and 228 deletions

View File

@ -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.storage.file;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.junit;version="[4.4.0,5.0.0)",
org.kohsuke.args4j;version="[2.0.12,2.1.0)",

View File

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

View File

@ -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.filter;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.spi;version="[2.0.12,2.1.0)"
Bundle-ActivationPolicy: lazy

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -217,6 +217,7 @@ public static String formatLine(String line) {
/***/ public String taggerInfo;
/***/ public String timeInMilliSeconds;
/***/ public String tooManyRefsGiven;
/***/ public char[] unknownIoErrorStdout;
/***/ public String unknownMergeStrategy;
/***/ public String unmergedPaths;
/***/ public String unsupportedOperation;

View File

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

View File

@ -55,8 +55,6 @@
import org.eclipse.jgit.dircache.DirCacheCheckout;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
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.Ref;
import org.eclipse.jgit.lib.RefComparator;
@ -116,10 +114,10 @@ protected void run() throws Exception {
dstcfg.save();
db = dst;
out.print(MessageFormat.format(
outw.print(MessageFormat.format(
CLIText.get().initializedEmptyGitRepositoryIn, gitdir));
out.println();
out.flush();
outw.println();
outw.flush();
saveRemote(uri);
final FetchResult r = runFetch();
@ -139,8 +137,7 @@ private void saveRemote(final URIish uri) throws URISyntaxException,
dstcfg.save();
}
private FetchResult runFetch() throws NotSupportedException,
URISyntaxException, TransportException {
private FetchResult runFetch() throws URISyntaxException, IOException {
final Transport tn = Transport.open(db, remoteName);
final FetchResult r;
try {

View File

@ -109,7 +109,7 @@ protected void run() throws NoHeadException, NoMessageException,
if (branchName.startsWith(Constants.R_HEADS))
branchName = branchName.substring(Constants.R_HEADS.length());
}
out.println("[" + branchName + " " + commit.name() + "] "
outw.println("[" + branchName + " " + commit.name() + "] "
+ commit.getShortMessage());
}
}

View File

@ -103,7 +103,7 @@ private void list(StoredConfig config) throws IOException,
Set<String> names = config.getNames(section);
for (String name : names) {
for (String value : config.getStringList(section, null, name))
out.println(section + "." + name + "=" + value);
outw.println(section + "." + name + "=" + value);
}
if (names.isEmpty()) {
for (String subsection : config.getSubsections(section)) {
@ -111,7 +111,7 @@ private void list(StoredConfig config) throws IOException,
for (String name : names) {
for (String value : config.getStringList(section,
subsection, name))
out.println(section + "." + subsection + "."
outw.println(section + "." + subsection + "."
+ name + "=" + value);
}
}

View File

@ -127,7 +127,7 @@ protected void run() throws Exception {
final FileResolver<DaemonClient> resolver = new FileResolver<DaemonClient>();
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.setExportAll(exportAll);
@ -152,7 +152,7 @@ protected void run() throws Exception {
service(d, n).setOverridable(false);
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,

View File

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

View File

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

View File

@ -72,7 +72,7 @@ protected void run() throws Exception {
if (gitdir != null)
command.setDirectory(new File(gitdir));
Repository repository = command.call().getRepository();
out.println(MessageFormat.format(
outw.println(MessageFormat.format(
CLIText.get().initializedEmptyGitRepositoryIn, repository
.getDirectory().getAbsolutePath()));
}

View File

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

View File

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

View File

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

View File

@ -137,6 +137,15 @@ protected void run(final String[] argv) {
err.printStackTrace();
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 {
@ -190,8 +199,8 @@ private void execute(final String[] argv) throws Exception {
try {
cmd.execute(arguments.toArray(new String[arguments.size()]));
} finally {
if (cmd.out != null)
cmd.out.flush();
if (cmd.outw != null)
cmd.outw.flush();
}
}

View File

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

View File

@ -74,7 +74,7 @@ protected void run() throws Exception {
final RevCommit b = argWalk.next();
if (b == null)
break;
out.println(b.getId().name());
outw.println(b.getId().name());
}
}
}

View File

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

View File

@ -75,6 +75,6 @@ protected void run() throws Exception {
}
rp = new org.eclipse.jgit.transport.ReceivePack(db);
rp.receive(System.in, System.out, System.err);
rp.receive(System.in, outs, System.err);
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -91,7 +91,7 @@ protected void run() throws Exception {
ListTagCommand command = git.tagList();
List<Ref> list = command.call();
for (Ref ref : list) {
out.println(Repository.shortenRefName(ref.getName()));
outw.println(Repository.shortenRefName(ref.getName()));
}
}
}

View File

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

View File

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

View File

@ -53,7 +53,7 @@ protected void run() throws Exception {
if (pkg == null || pkg.getImplementationVersion() == null)
throw die(CLIText.get().cannotReadPackageInformation);
out.println(MessageFormat.format(CLIText.get().jgitVersion, pkg.getImplementationVersion()));
outw.println(MessageFormat.format(CLIText.get().jgitVersion, pkg.getImplementationVersion()));
}
@Override

View File

@ -245,29 +245,29 @@ public int compare(Test a, Test b) {
File parent = db.getDirectory().getParentFile();
if (name.equals(Constants.DOT_GIT) && parent != null)
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);
out.format(" N=%10d min lines, %8d max lines\n", minN, maxN);
outw.format(" %12d files, %8d commits\n", files, commits);
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");
out.format("%-25s %12s ( %12s %12s )\n", //
outw.format("%-25s %12s ( %12s %12s )\n", //
"", "", "N=" + minN, "N=" + maxN);
out.println("-----------------------------------------------------"
outw.println("-----------------------------------------------------"
+ "----------------");
for (Test test : all) {
out.format("%-25s %12d ( %12d %12d )", //
outw.format("%-25s %12d ( %12d %12d )", //
test.algorithm.name, //
test.runningTimeNanos, //
test.minN.runningTimeNanos, //
test.maxN.runningTimeNanos);
out.println();
outw.println();
}
out.println();
out.flush();
outw.println();
outw.flush();
}
private static boolean isFile(TreeWalk tw, int ithTree) {

View File

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

View File

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

View File

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

View File

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

View File

@ -87,7 +87,7 @@ protected void run() throws Exception {
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)

View File

@ -344,26 +344,26 @@ private void run(Repository db) throws Exception {
File parent = db.getDirectory().getParentFile();
if (name.equals(Constants.DOT_GIT) && parent != null)
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, //
lineCnt / fileCnt);
out.format("%-20s %-15s %9s\n", "Hash", "Fold", "Max Len");
out.println("-----------------------------------------------");
outw.format("%-20s %-15s %9s\n", "Hash", "Fold", "Max Len");
outw.println("-----------------------------------------------");
String lastHashName = null;
for (Function fun : all) {
String hashName = fun.hash.name;
if (hashName.equals(lastHashName))
hashName = "";
out.format("%-20s %-15s %9d\n", //
outw.format("%-20s %-15s %9d\n", //
hashName, //
fun.fold.name, //
fun.maxChainLength);
lastHashName = fun.hash.name;
}
out.println();
out.flush();
outw.println();
outw.flush();
}
private void testOne(Function fun, RawText txt, int[] elements, int cnt) {

View File

@ -114,8 +114,8 @@ else if (version == null)
lf.unlock();
}
} else {
log.writeTo(System.out);
System.out.flush();
log.writeTo(outs);
outs.flush();
}
}
}

View File

@ -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));
}
}