auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public XDocResourceKey(Project.NameKey project, String r, ObjectId revId) { this.project = project; this.resource = r; this.revId = revId; }

Target:
Why this is needed?
Source:
private SecureStore getSecureStore(String className, Injector injector) { try { @SuppressWarnings("unchecked") Class<? extends SecureStore> clazz = (Class<? extends SecureStore>) Class.forName(className); return injector.getInstance(clazz); } catch (ClassNotFoundException e) { throw new RuntimeException( String.format("Cannot load SecureStore implementation: %s"), e); } }

Target:
Bug: Format string "%s" needs argument 1 but only 0 are provided
Source:
private PatchSet getBasePatchSet(Change change, Ref ref) throws IOException, InvalidChangeOperationException { try { int pos = ref.getName().lastIndexOf("/"); String psId = ref.getName().substring(++pos); return db.get().patchSets().get(new PatchSet.Id( change.getId(), Integer.valueOf(psId))); } catch (OrmException e) { throw new IOException(e); } }

Target:
pos + 1, since you're not depending on the side effect.
Source:
public Response<TreeSet<String>> apply(ChangeResource req) throws AuthException, OrmException, IOException, BadRequestException { ChangeControl control = req.getControl(); ChangeNotes notes = control.getNotes().load(); Set<String> hashtags = notes.getHashtags(); if (hashtags == null) { hashtags = ImmutableSet.of(); } return Response.ok(new TreeSet<String>(hashtags)); }

Target:
Make it Response<? extends Set<String>>
Source:
public Set<AccountGroup.UUID> getAllOwners() { Set<AccountGroup.UUID> result = new HashSet<AccountGroup.UUID>(); for (ProjectState p : tree()) { result.addAll(p.localOwners); } return result; }

Target:
In any event, since we're on Java7, just: new HashSet<>();
Source:
void onAdd(ClickEvent e) { String hashtag = hashtagTextBox.getText(); while (hashtag.startsWith("#")) { hashtag = hashtag.substring(1); } if (!hashtag.isEmpty()) { addHashtag(hashtag); } }

Target:
If the string retrieved from hashtagTextBox is "#test1,#test2", you will only remove the hashtag from the first hashtag. Perhaps do the check in the RESTApi instead?
Source:
static public void setLevel(int value) { level.set(value); }

Target:
nit: public static void But public here is irrelevant. Its only as visible as the inner class, which is package access. You can skip the public keyword.
Source:
public int weigh(EntryKey k, Boolean v) { // Size of EntryKey, 64-bit JVM. return 16 + 2 * (16 + 20) + 8 + 8 + 2 * k.mergeStrategy.length() + 1; // Size of Boolean. }

Target:
Aren't these static strings held and reused? We shouldn't have to charge for the weight of the merge strategy string. Actual memory used per entry is pointer sized not string length.
Source:
public static ChangeData createForTest(Change.Id id, int currentPatchSetId) { ChangeData cd = new ChangeData(null, null, null, null, null, null, null, null, null, null, null, null, null, id); cd.currentPatchSet = new PatchSet(new PatchSet.Id(id, currentPatchSetId)); return cd; }

Target:
Unneeded change. This only used in RegexPathPredicateTest, that is in the same package.
Source:
private List<SubmitRecord> ruleError(String err, Exception e) { if (logErrors) { if (err == null) { log.error(err); } else { log.error(err, e); } return defaultRuleError(); } else { return createRuleError(err); } }

Target:
e == null
Source:
public void readGroupList() throws IOException { groupList = GroupList.parse(readUTF8(GroupList.FILE_NAME), this); }

Target:
Inline this method or at least make it private.
Source:
public boolean matches(NameKey name) { boolean isMatch; if (projectPatterns.isEmpty()) { isMatch = true; } else { isMatch = false; String projectName = name.get(); for (String pattern : projectPatterns) { isMatch = matchesPattern(projectName, pattern); if (isMatch) { break; } } } return isMatch; }

Target:
Done
Source:
public BinaryResult apply(ChangeResource rsrc) throws AuthException, IOException, InvalidChangeOperationException, OrmException, NoSuchChangeException { Optional<ChangeEdit> edit = editUtil.byChange(rsrc.getChange()); // TODO(davido): Clean this up by returning 404 when edit doesn't exist. // Client should call GET /changes/{id}/revisions/current/commit in this // case; or, to be consistent with GET content logic, the client could // call directly the right endpoint. String m = edit.isPresent() ? edit.get().getEditCommit().getFullMessage() : changeUtil.getMessage(rsrc.getChange()); return BinaryResult.create(m).base64(); }

Target:
never thrown?
Source:
public CommentLinkInfo(Pattern pattern, String link) { this.pattern = pattern; this.link = checkNotNull(link); }

Target:
checkNotNull(pattern), too?
Source:
public static Change.Id changeIdFromDraftComments(String refName) { int d = refName.lastIndexOf('-'); return new Change.Id(Integer.parseInt(refName.substring(d + 1), 10)); }

Target:
This is optional, it's the default, and Java doesn't do anything dumb like treat leading 0s as octal.
Source:
public CheckResult check(Change c) { reset(); change = c; try { checkImpl(); CheckResult result = new CheckResult(); result.messages = messages; return result; } finally { if (rw != null) { rw.release(); } if (repo != null) { repo.close(); } } }

Target:
This return value in unexpected. This method doesn't render ChangeInfo. So no reason to instantiate CheckResult. Just return messages.
Source:
static boolean needsQuotedPrintableWithinPhrase(final int cp) { switch (cp) { case '!': case '*': case '+': case '-': case '/': case '=': case '_': return false; default: if ((cp >= 'a' && cp <= 'z') || (cp >= 'A' && cp <= 'Z') || (cp >= '0' && cp <= '9')) { return false; } else { return true; } } }

Target:
I think we prefer this to be written like: 'a' <= cp && cp <= 'z' as this is closer to the mathematical notation: 'a' <= cp <= 'z' Looking at our codebase there are many places with this pattern. Same for the following 2 lines
Source:
private static void validateRequestMethod(HttpServletRequest req) throws MethodNotAllowedException { if (!"GET".equals(req.getMethod()) && !"HEAD".equals(req.getMethod())) { throw new MethodNotAllowedException(); } }

Target:
Or: if (!(req.getMethod().equals("GET") || req.getMethod().equals("HEAD")))
Source:
public void onLoad(Screen screen) { String projectName = URL.decode(screen.getToken(1)); String fileName = URL.decode(screen.getToken(2)); screen.show(new XDocScreen(projectName, "HEAD", fileName)); screen.setWindowTitle(getFileName(fileName)); }

Target:
Rename this to `path` to make it consistent with the parameter name on getFileName?
Source:
private int getPermittedLimit() { if (!enforceVisibility) { return Integer.MAX_VALUE; } return userProvider.get().getCapabilities() .getRange(GlobalCapability.QUERY_LIMIT) .getMax(); }

Target:
I would wrap the user code: if (enforceVisibility) { return userProvider.get()... } return Integer.MAX_VALUE;
Source:
void onEditMode(@SuppressWarnings("unused") ClickEvent e) { fileTableMode = FileTable.Mode.EDIT; refreshFileTable(); editMode.setVisible(false); reply.setVisible(false); addFile.setVisible(true); reviewMode.setVisible(true); }

Target:
Toggling edit mode in file table, doesn't imply that we have a change edit yet: it is still possible to post reviews?
Source:
public Object apply(RevisionResource rsrc) throws AuthException, BadRequestException, ResourceConflictException, Exception { return Response.withMustRevalidate(delegate.get().format(rsrc)); }

Target:
All these exceptions are unsed. "Exception" is never used in real code, only in unit tests.
Source:
public Object apply(RevisionResource rsrc) throws AuthException, BadRequestException, ResourceConflictException, Exception { return Response.withMustRevalidate(delegate.format(rsrc)); }

Target:
This is GetRevisionActions, why is it returning a ChangeInfo? "Actions for this revision" sounds like a Map<String, ActionInfo>, no?
Source:
private boolean haveGitHubIdEntry(ReviewDb db, Account.Id accountId, AccountExternalId.Key key) throws OrmException { boolean found = false; for (AccountExternalId id : db.accountExternalIds().byAccount(accountId)) { if (id.getKey().equals(key)) { found = true; break; } } return found; }

Target:
Local variable is not necessary. Instead, here we can just do: return true;
Source:
public Rule[] blockPluginRules() { return new Rule[]{ toc(), note(), cols(), }; }

Target:
Alphabetize these?
Source:
public void execute() throws UpdateException, RestApiException { try { executeRefUpdates(); executeChangeOps(); reindexChanges(); // Fire ref update events only after all mutations are finished, since // callers may assume a patch set ref being created means the change was // created, or a branch advancing meaning some changes were closed. gitRefUpdated.fire(project, batchRefUpdate); executePostOps(); } catch (UpdateException | RestApiException e) { // Propagate REST API exceptions thrown by operations. Most operations // should throw non-REST exceptions like NoSuchChangeException, under the // assumption that validation is done by REST API handlers in advance of // executing the batch. They commonly throw ResourceConflictException to // indicate an atomic operation failure. throw e; } catch (Exception e) { Throwables.propagateIfPossible(e); throw new UpdateException(e); } }

Target:
batchRefUpdate can be null now and we would get an NPE inside the fire method.
Source:
private int getPluginsLoadTimeout(final Config cfg) { long cfgValue = ConfigUtil.getTimeUnit(cfg, "plugins", null, "jsLoadTimeout", DEFAULT_JS_LOAD_TIMEOUT, TimeUnit.MILLISECONDS); if (cfgValue < 0) { return 0; } return (int) cfgValue; }

Target:
method should be static
Source:
public synchronized void unregister(URI key) { if (locks.containsKey(key)) { LockProvider provider = locks.get(key); if (provider != null) { provider.decreateCount(); if (provider.getRegisterCount() < 1) { locks.remove(key); } } } }

Target:
Unnecessary given the next two lines which perform a get and test for null on the result.
Source:
private RemoteConfig selectDefaultRemoteConfig() { for (final RemoteConfig rc : configuredRemotes) if (getTextForRemoteConfig(rc) == Constants.DEFAULT_REMOTE_NAME) return rc; return configuredRemotes.get(0); }

Target:
Use .equals()
Source:
protected MergeChunk(int sequenceIndex, int begin, int end, ConflictState conflictState) { super(); this.sequenceIndex = sequenceIndex; this.begin = begin; this.end = end; this.conflictState = conflictState; }

Target:
Style-nit: We don't call super if there are no arguments to it.
Source:
public TagOperation(Repository repo, Tag tag, boolean shouldMoveTag) { this.tag = tag; this.repo = repo; tagName = tag.getTag(); this.shouldMoveTag = shouldMoveTag; refName = Constants.R_TAGS + tagName; }

Target:
tagName is redundant. Use local variablesl later on if necessary
Source:
public void setSelectedElement(ObjectId objectId) { if (null == objectId) { return; } for (int i = 0; i < commits.size(); i++) if (objectId.equals(commits.get(i).objectId)) { combo.select(i); break; } }

Target:
Why not the more straightforward objectId == null? (this isn't C)
Source:
public CommitCommand setCommitter(String name, String email) { this.committer = new PersonIdent(name, email); return this; }

Target:
Style-nit: I think I would prefer this to be defined as: public CommitCommand setCommitter(String name, String email) { return setCommitter(new PersonIdent(name, email)); }
Source:
public CommitCommand commit() { return (new CommitCommand(this)); }

Target:
Style-nit: We don't put parens around return. Thus: return new CommitCommand(this);
Source:
public LogCommand log() { return (new LogCommand(this)); }

Target:
style: extra parentheses
Source:
public Repository getRepository() { return(repo); }

Target:
style: extra parentheses
Source:
public void execute(IAction action) { IHistoryView view = TeamUI.showHistoryFor(TeamUIPlugin.getActivePage(), getSelectedResources()[0], null); IHistoryPage page = view.getHistoryPage(); if (page instanceof GitHistoryPage){ GitHistoryPage gitHistoryPage = (GitHistoryPage) page; gitHistoryPage.setCompareMode(true); } }

Target:
The API says null can be returned, we should check for this.
Source:
private void removeEmptyParents(File f) { File parentFile = f.getParentFile(); while (!parentFile.equals(repo.getWorkDir())) { if (parentFile.list().length == 0) parentFile.delete(); else break; parentFile = parentFile.getParentFile(); } }

Target:
I would be willing to bet you a beer next time we meet up in person that just doing: if (!parentFile.delete()) break; is faster. We have to do a system call to read the directory contents, and the operating system is forbidden from letting us remove a directory so long as it has at least one file/directory within it. So we can accomplish both tasks in one system call by trying the delete, and aborting as soon as it doesn't work.
Source:
public GitIndex getIndex() throws IOException { if (isBare()) throw new IOException( JGitText.get().bareRepositoryNoWorkdirAndIndex); if (index == null) { index = new GitIndex(this); index.read(); } else { index.rereadIfNecessary(); } return index; }

Target:
Why do we throw IOException here and IllegalStateException in getIndexFile()? Can we at least throw the same type consistently?
Source:
public boolean isBare() { boolean bareSet = getConfig().getString( ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_BARE) != null; if (bareSet) // if "bareness" was set in the config, use this value return getConfig().getBoolean(ConfigConstants.CONFIG_CORE_SECTION, ConfigConstants.CONFIG_KEY_BARE, false); if (gitDirExplicit && workDir == null) return true; // if the directory is .git, then we are probably not bare if (getDirectory().getName().equals(Constants.DOT_GIT)) return false; return true; }

Target:
With all of the logic in the constructor, I wonder if we can simplify this method down to: public boolean isBare() { return workDir == null; }
Source:
public void resourceChanged(IResourceChangeEvent event) { if (event.getType() == IResourceChangeEvent.POST_CHANGE) { state = true; } }

Target:
style nit: no braces around single line
Source:
public boolean containsRepo(String projectName) { SWTBotTable table = bot.table(0); int repoCount = configuredRepoCount(); for (int i = 0; i < repoCount; i++) { String rowName = table.getTableItem(i).getText(); if (rowName.contains(projectName)) { return true; } } return false; }

Target:
style nit: no braces around single line
Source:
private String getMemberRelPath(Repository repo, IResource member) { String repoWorkDir = repo.getWorkDir().toString(); if (!"/".equals(File.separator)) { //$NON-NLS-1$ // fix file separator issue on windows repoWorkDir = repoWorkDir.replace(File.separatorChar, '/'); } String memberRelPath = member.getLocation().toString(); memberRelPath = memberRelPath.replace(repoWorkDir, ""); //$NON-NLS-1$ if (memberRelPath.startsWith("/")) { //$NON-NLS-1$ memberRelPath = memberRelPath.substring(1); } return memberRelPath; }

Target:
style nit: no braces around single line
Source:
public void flushVariants(IResource resource, int depth) throws TeamException { if (!gsdData.getData(resource.getProject()).shouldIncludeLocal()) { store.flushBytes(resource, depth); } }

Target:
style nit: no braces around single line
Source:
protected int hashLine(final byte[] raw, int ptr, final int end) { int hash = 5381; for (; ptr < end; ptr++) { if (!RawCharUtil.isWhitespace(raw[ptr])) { hash = (hash << 5) ^ (raw[ptr] & 0xff); } } return hash; }

Target:
Performance-nit: Same nit as above, pull raw[ptr] into a local variable so its not evaluated twice.
Source:
FileHeader(final byte[] b, final int offset) { changeType = ChangeType.MODIFY; // unless otherwise designated buf = b; startOffset = offset; patchType = PatchType.UNIFIED; }

Target:
Please don't move this line around in the constructor, its not essential to the patch.
Source:
public void setUp() throws Exception { super.setUp(); iProject = project.project; if (!gitDir.exists()) new FileRepository(gitDir).create(); new ConnectProviderOperation(iProject, gitDir).execute(null); testRepo = new TestRepository(gitDir); testRepo.connect(iProject); repo = RepositoryMapping.getMapping(iProject).getRepository(); }

Target:
Now I get an error at the next statement: java.lang.IllegalStateException: Repository already exists Can you use new TestRepository(Repository repository) instead? You have created an instance of FileRepository before.
Source:
private DiffEntry bestPathMatch(DiffEntry src, List<DiffEntry> list) { DiffEntry best = null; int score = -1; for (DiffEntry d : list) { if (sameType(mode(d), mode(src))) { int tmp = SimilarityRenameDetector .nameScore(path(d), path(src)); if (tmp > score) { best = d; score = tmp; } } } return best; }

Target:
Style-nit: This can be a static method.
Source:
public void close() throws IOException { try { super.close(); } finally { is.close(); } }

Target:
There is no need to call super.close() on InputStream. It is a no-op method. Instead you just need to do is.close();
Source:
protected void createButtonsForButtonBar(Composite parent) { // OK button only createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); setTitle(myTitle); }

Target:
If a TitleAreaDialog is going to be used (which I am not really convinced is necessary in this scenario), please also set a description. Also, it feels kind of weird to me to be setting a title of a dialog in a method that's meant for the creation of buttons.
Source:
public String getMessage() { return name; }

Target:
that's wrong, should be: return message;
Source:
private static int lastIndexOfTrim(byte[] raw, char ch, int pos) { while (pos >= 0 && raw[pos] == ' ') { pos--; } while (pos >= 0 && raw[pos] != ch) { pos--; } return pos; }

Target:
Style-nit: We don't use curly braces around simple loops.
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + remoteCommit.hashCode(); result = prime * result + baseCommit.hashCode(); result = prime * result + getLocation().hashCode(); return result; }

Target:
It seems like an NPE can occur here. In GitModelCommit's constructors, there is a code path where the 'baseCommit' field is set to 'null'.
Source:
public static int formatBase10(final byte[] b, int o, int value) { if (value == 0) { b[--o] = '0'; return o; } final boolean isneg = value < 0; if (isneg) { value = -value; } while (value != 0) { b[--o] = base10byte[value % 10]; value /= 10; } if (isneg) b[--o] = '-'; return o; }

Target:
Style-nit: The curly braces aren't necessary. I'm going to cherry-pick this directly onto master, its a simple bug fix that I don't want to be held up on the DIRC version 3 code.
Source:
public List<Attribute> getAttributes(String entryPath, boolean isDirectory) { if (rules.isEmpty()) return Collections.emptyList(); // Parse rules in the reverse order that they were read for (int i = rules.size() - 1; i > -1; i--) { AttributesRule rule = rules.get(i); if (rule.isMatch(entryPath, isDirectory)) { return rule.getAttributes(); } } return Collections.emptyList(); }

Target:
Done
Source:
public boolean equals(Object obj) { if (obj == null || obj.getClass() != getClass()) { return false; } final Attribute attribute = (Attribute) obj; return CompareUtils.areEqual(key, attribute.getKey()) && CompareUtils.areEqual(value, attribute.getValue()); }

Target:
We prefer to write: if (obj instanceof Attribute) { Attribute other = (Attribute)obj; ... } return false; as this does both the null test and the type test at the same time. It also permits us to compare a subclass according to our current semantics.
Source:
public int hashCode() { return key.hashCode() ^ value.hashCode(); }

Target:
I think the current state of the art is to do something like: int hc = key.hashCode(); hc *= 31; hc += value.hashCode(); return hc; But actually for an attribute there aren't too many that can can be multi-valued, are there? So just using the key's hashCode as our own hashCode might be sufficient here.
Source:
public PushCommand setRefSpecs(RefSpec... specs) { checkCallable(); this.refSpecs.clear(); for (RefSpec spec : specs) refSpecs.add(spec); return this; }

Target:
could be simplified: Collections.addAll(refsSpecs, specs);
Source:
LStat(int[] rawlstat) { ctimeSec = rawlstat[0]; ctimeNSec = rawlstat[1]; mtimeSec = rawlstat[2]; mtimeNSec = rawlstat[3]; device = rawlstat[4]; inode = rawlstat[5]; mode = FileMode.fromBits(rawlstat[6]); userId = rawlstat[7]; groupId = rawlstat[8]; size = rawlstat[9] + rawlstat[10] << 32; }

Target:
This is going to overflow as its all computed as an int. Also, the precedence of + and << isn't that widely known, so we prefer to wrap with () here to make the order of operations clear to everyone. So instead: size = ((long)rawlstat[9]) + (((long)rawlstat[10]) << 32); FWIW, given that almost everywhere else we use big endian ordering, its weird to see the high 32 bits of the size occur later in the array than the low 32 bits.
Source:
public FSAccessNative() { // empty default constructor }

Target:
Should this be package visible only?
Source:
public int getSize() { return rawlstat[9]; }

Target:
This should be a long.
Source:
protected void run() throws Exception { AddCommand addCmd = new Git(db).add(); addCmd.setUpdate(update); for (String p : filepatterns) { addCmd.addFilepattern(p); } addCmd.call(); }

Target:
Style-nit: We don't put around a single statement.
Source:
public HashSet<String> getAssumeUnchanged() { return assumeUnchanged; }

Target:
None of these methods should export HashSet. They should be exporting Set<String> instead in case we change our internal representation to be something else, e.g a TreeSet, or a custom Set implementation that uses a smaller storage and is easier to construct given the fact that we iterate names in path-order. You can add it as HashSet<String> here if you then immediately follow up with a change that fixes all of these methods to return Set<String>. (Or please do the reverse, insert a new commit that fixes the existing methods to return Set<String> and change this commit to return Set<String>.)
Source:
public static InitCommand init() { return new InitCommand(); }

Target:
Style-nit: Static methods should appear at the start of the class, before instance members.
Source:
private FanoutBucket asFanout(InMemoryNoteBucket bucket) { if (bucket == null) return EMPTY_FANOUT; if (bucket instanceof FanoutBucket) return (FanoutBucket) bucket; FanoutBucket fanoutBucket = ((LeafBucket) bucket).split(); return fanoutBucket; }

Target:
Since we dropped the writeTree call, we probably don't need this local variable anymore and can instead just return the result of split().
Source:
public NotesMergeConflictException(NonNoteEntry base, NonNoteEntry ours, NonNoteEntry theirs) { super(MessageFormat.format( JGitText.get().mergeConflictOnNonNoteEntries, base.name(), ours.name(), theirs.name())); }

Target:
Any of base, ours, theirs could be null if that NonNoteEntry doesn't exist... causing the conflict to NPE. You need something similar to noteOn here: private static String name(NonNoteEntry e) { return e != null ? e.name() : ""; }
Source:
public InMemoryNoteBucket getRoot() { return root; }

Target:
This shouldn't be public, the type it returns isn't public.
Source:
private FanoutBucket asFanout(InMemoryNoteBucket bucket) throws IOException { if (bucket == null) return EMPTY_FANOUT; if (bucket instanceof FanoutBucket) return (FanoutBucket) bucket; FanoutBucket fanoutBucket = ((LeafBucket) bucket).split(); fanoutBucket.writeTree(inserter); return fanoutBucket; }

Target:
I don't know if we need this call anymore. As I understand how the code works, this temporary fanout bucket isn't needed as a tree anywhere, so we shouldn't have to write it.
Source:
public NotesMergeConflictException(NonNoteEntry base, NonNoteEntry ours, NonNoteEntry theirs) { super(MessageFormat.format(JGitText.get().mergeConflictOnNonNoteEntries, base, ours, theirs)); }

Target:
You probably want to use the name field from the NonNoteEntry rather than rely on the toString().
Source:
public void testAddAdd() throws Exception { Note add1 = newNote("add1"); Note add2 = newNote("add2"); Note result = merger.merge(baseNote, add1, add2); assertEquals(result, noteOn); // same note assertEquals(result.getData(), tr.blob("add1add2")); result = merger.merge(baseNote, add2, add1); assertEquals(result, noteOn); // same note assertEquals(result.getData(), tr.blob("add2add1")); }

Target:
what's the difference compared to testEditEdit() ?
Source:
public List<String> getConflictList() { return conflictList; }

Target:
wouldn't it be better to return List<File> here ?
Source:
ObjectId getData() { return data; }

Target:
We also need to make this public. Otherwise the client of the Iterator<Note> cannot see the blob that is attached to the note.
Source:
public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }

Target:
Style-nit: We prefer to import these names and use the short class name instead.
Source:
private void initCommitsMap() { commitsMap = new HashMap<String, PlotCommit>(); for (PlotCommit commit : allCommits) { commitsMap.put(commit.getId().name(), commit); } }

Target:
please remove brackets since we don't use brackets for single line statements
Source:
private String formatHeadRef(Ref ref) { final String name = ref.getName(); if (name.startsWith(Constants.R_HEADS)) { return name.substring(Constants.R_HEADS.length()); } else if (name.startsWith(Constants.R_REMOTES)) { return name.substring(Constants.R_REMOTES.length()); } return name; }

Target:
please remove brackets
Source:
protected void initializeConfiguration( ISynchronizePageConfiguration configuration) { configuration.setProperty(ISynchronizePageConfiguration.P_VIEWER_ID, VIEWER_ID); configuration.setProperty( ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER, GitChangeSetModelProvider.ID); configuration.addActionContribution(new GitActionContributor()); super.initializeConfiguration(configuration); configuration.addActionContribution(new GitActionContributor()); }

Target:
Why are you adding this twice?
Source:
private void resetMerge() throws IOException { try { repo.writeMergeHeads(null); repo.writeMergeCommitMsg(null); } catch (IOException e) { throw e; } }

Target:
unused try catch block
Source:
public final int getRefCount() { return refs == null ? 0 : refs.length; }

Target:
Instead of a null test here, we should have a NO_REFS empty array constant and initialize refs in the constructor to it. Then we don't need to worry about null here, or in getRef().
Source:
private static void loadIdentity(final JSch sch, final File priv) { if (priv.isFile()) { try { sch.addIdentity(priv.getAbsolutePath()); } catch (final JSchException e) { // Instead, pretend the key doesn't exist. } } }

Target:
Style-nit: No reason to add final.
Source:
public void disconnect() { if (sock.isConnected()) { sock.disconnect(); } }

Target:
style nit: we don't use curly braces around single line blocks
Source:
public void destroy() { if (channel.isConnected()) { channel.disconnect(); } }

Target:
Style-nit: No curly braces on single statements.
Source:
private List<Repository> getRepositories() { List<Repository> reposList = new LinkedList<Repository>(); Iterator<RepositoryTreeNode> it = ((IStructuredSelection) repositoryTableViewer.getSelection()).iterator(); while (it.hasNext()) { reposList.add(it.next().getRepository()); } return reposList; }

Target:
style nit: we don't use braces around single line blocks
Source:
public List<Repository> getSelectedRepositories() { if (repos.isEmpty()) { return null; } return repos; }

Target:
style nit: no braces around single line blocks
Source:
public boolean promptPassword(String msg) { CredentialItem.Password p = new CredentialItem.Password(); if (provider.get(uri, p)) { password = new String(p.getValue()); return true; } else { CredentialItem.StringType v = newPrompt(msg); if (provider.get(uri, v)) { password = v.getValue(); return true; } else { password = null; return false; } } }

Target:
This discards the "msg" argument we got from JSch. Maybe this class needs a new constructor that allows us to pass in the msg rather than using the default text.
Source:
public boolean promptPassword(String msg) { CredentialItem.Password p = new CredentialItem.Password(msg); if (provider.get(uri, p)) { password = new String(p.getValue()); return true; } else { CredentialItem.StringType v = newPrompt(msg); if (provider.get(uri, v)) { password = v.getValue(); return true; } else { password = null; return false; } } }

Target:
We shouldn't have this case here. The old code was just plain wrong to be using a StringType for the password. Leave the original else block when that first get returns false.
Source:
private void activateContextService() { IContextService contextService = (IContextService) getSite() .getService(IContextService.class); if (contextService != null) { contextService.activateContext(VIEW_ID); } }

Target:
Style-nit: no brackets around single-line blocks
Source:
public Image getColumnImage(final Object element, final int columnIndex) { if (columnIndex == 0) { final FileDiff c = (FileDiff) element; switch (c.getChange()) { case ADD: return getDecoratedImage(getEditorImage(c), UIIcons.OVR_STAGED_ADD); case COPY: return COPY; case DELETE: return getDecoratedImage(getEditorImage(c), UIIcons.OVR_STAGED_REMOVE); case RENAME: // fall through case MODIFY: return getEditorImage(c); } } return null; }

Target:
I think this case should be in the list of fallback cases (unfortunately, I don't know how to create a COPY diff)...
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { Repository[] repos = getRepositories(event); if (repos.length == 0) return null; Set<Repository> repositories = new HashSet<Repository>(); for (int i = 0; i < repos.length; i++) repositories.add(repos[i]); new PullOperationUI(repositories).start(); return null; }

Target:
how about this: new HashSet<Repository>(Arrays.asList(repos));
Source:
public void tearDown() throws Exception { Activator.getDefault().getRepositoryCache().clear(); for (IProject project : createdProjects) { if (project.exists()) { project.delete(true, true, null); } } for (File pathToClean : pathsToClean) { if (pathToClean.exists()) { FileUtils.delete(pathToClean, FileUtils.RECURSIVE | FileUtils.RETRY); } } }

Target:
style nit: we don't use braces around single line blocks, more occurrences throughout this patch
Source:
public static void closeWelcomePage() { if (welcomePageClosed) return; try { bot.viewByTitle("Welcome").close(); welcomePageClosed = true; } catch (WidgetNotFoundException e) { // somebody else probably closed it, lets not feel bad about it. welcomePageClosed = true; } }

Target:
Shouldn't we put this into a finally block? Saves one line of code...
Source:
public ObjectId readCherryPickHead() throws IOException, NoWorkTreeException { if (isBare() || getDirectory() == null) throw new NoWorkTreeException(); File mergeHeadFile = new File(getDirectory(), Constants.CHERRY_PICK_HEAD); byte[] raw; try { raw = IO.readFully(mergeHeadFile); } catch (FileNotFoundException notFound) { return null; } if (raw.length == 0) return null; ObjectId head = ObjectId.fromString(raw, 0); return head; }

Target:
Style-nit: There is no good reason for this local variable "head".
Source:
protected void makeChangesAndCommit(String projectName) throws Exception { changeFilesInProject(); Thread.sleep(1000); // wait 1 s to get different time stamps // TODO can be removed when commit is based on DirCache commit(projectName); }

Target:
commit is using DirCache since a while
Source:
private byte[] readGitDirectoryFile(String filename) throws IOException { File file = new File(getDirectory(), filename); byte[] raw; try { raw = IO.readFully(file); } catch (FileNotFoundException notFound) { return null; } if (raw.length == 0) return null; return raw; }

Target:
Given how short the method is, maybe this is even shorter: File file = new File(getDirectory(), filename); try { byte[] raw = IO.readFully(file); return 0 < raw.length ? raw : null; } catch (FileNotFoundException notFound) { return null; } On something this tiny, it isn't really worth trying to hoist the if outside of the try/catch.
Source:
public Object getAdapter(Class adapter) { if (adapter == IResource.class) { return resource; } return null; }

Target:
style nit: we don't use curly braces around single line blocks
Source:
public String toString() { if (parent != null && parent.getResource() instanceof IProject) { return resource.getProjectRelativePath().toString(); } return resource.getName(); }

Target:
style nit: no braces here
Source:
public Line(RevCommit startCommit, int lineNumber) { commit = startCommit; number = lineNumber; }

Target:
Why is this constructor public? If its to permit copying a Line (so an application can take a "snapshot"), we should instead support some sort of copy constructor that takes a Line object, or a cloneLine() method that returns a copied Line object. Otherwise, I think this should be package-private. Only the BlameGenerator should need to construct a Line object.
Source:
private List<ResourceTraversal> createTraversalForContainer(GitModelObject child) { GitModelObject[] containerChildren = child.getChildren(); List<ResourceTraversal> result = new ArrayList<ResourceTraversal>(); for (GitModelObject aChild : containerChildren) { if(aChild.isContainer()) { result.addAll(createTraversalForContainer(aChild)); } else { result.add(createTraversalForFile(aChild)); } } return result; }

Target:
Curly brackets are not needed here ;)
Source:
protected void initializeConfiguration( ISynchronizePageConfiguration configuration) { configuration.setProperty(ISynchronizePageConfiguration.P_VIEWER_ID, VIEWER_ID); String modelProvider; if(Activator.getDefault().getPreferenceStore().getBoolean( UIPreferences.SYNC_VIEW_ALWAYS_SHOW_CHANGESET_MODEL)) { modelProvider = GitChangeSetModelProvider.ID; } else { modelProvider = WORKSPACE_MODEL_PROVIDER_ID; } configuration.setProperty( ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER, modelProvider); super.initializeConfiguration(configuration); configuration.addActionContribution(new GitActionContributor()); }

Target:
as usually, please remove curly brackets around single line blocks
Source:
private Collection<String> buildFileList(Collection<IFile> files) throws CoreException { Collection<String> result = new ArrayList<String>(); for (IFile file : files) { RepositoryMapping mapping = RepositoryMapping.getMapping(file); if (mapping == null) throw new CoreException(Activator.error(NLS.bind(CoreText.CommitOperation_couldNotFindRepositoryMapping, file), null)); String repoRelativePath = mapping.getRepoRelativePath(file); result.add(repoRelativePath); } return result; }

Target:
I think HashSet would be faster as in addUntracked() you call contains() which is O(n) for ArrayList but O(1) for HashSet
Source:
private Object getAdapter(Object adaptable, Class c) { if (c.isInstance(adaptable)) { return adaptable; } if (adaptable instanceof IAdaptable) { IAdaptable a = (IAdaptable) adaptable; Object adapter = a.getAdapter(c); if (c.isInstance(adapter)) { return adapter; } } return null; }

Target:
style nit: we use no braces around single line blocks
Source:
public void setCredentials(String user, String password) { if (user != null && password != null) { Credentials credentials = new UsernamePasswordCredentials(user, password); this.client.getCredentialsProvider().setCredentials( new AuthScope(httpHost.getHostName(), httpHost.getPort()), credentials); } }

Target:
Please retain the ability to clear the credentials by calling with null username and password
Source:
public void run() { store.setValue(prefName, isChecked()); if (store.needsSaving()) { try { store.save(); } catch (IOException e) { Activator.handleError(e.getMessage(), e, false); } } }

Target:
These curlies are un-needed
Source:
/*package*/List<IResource> getRelevantResources() { List<IResource> resourcesInScope = new ArrayList<IResource>(); ResourceTraversal[] traversals = getScope().getTraversals(); for (ResourceTraversal resourceTraversal : traversals) { resourcesInScope.addAll(Arrays.asList(resourceTraversal .getResources())); } return resourcesInScope; }

Target:
style nit: no braces around single line block
Source:
public static synchronized GitScopeOperationFactory getFactory() { if(instance == null) { instance = new GitScopeOperationFactory(); } return instance; }

Target:
style nit: no braces around single line blocks
Source:
private static ResourceMapping[] getResourceMappings(IResource[] resources) { List<ResourceMapping> result = new ArrayList<ResourceMapping>(); for (IResource resource : resources) { result.add(getResourceMapping(resource)); } return result.toArray(new ResourceMapping[result.size()]); }

Target:
style nit: no braces for single line block
Source:
public void execute(IProgressMonitor monitor) throws CoreException { Git repoTree; // discover repositories and run clean on them if (paths != null) { for (IResource res : resources) { repoTree = new Git(getRepository(res)); repoTree.clean().setPaths(paths).call(); } } else { for (IResource res : resources) { repoTree = new Git(getRepository(res)); repoTree.clean().call(); } } }

Target:
you will get NPE if getRepository() return null (when given resource isn't in project shared by git).
Source:
private static String stripLeadingZeros(String input) { for (int i = 0; i < input.length(); i++) { if (input.charAt(i) != '0') { return input.substring(i); } } return ""; //$NON-NLS-1$ }

Target:
Code conventions: we don't use curly brackets around single line blocks
Source:
private int findNextEOL(int oldPos, String message) { int pos = message.indexOf("\n", oldPos + 1); //$NON-NLS-1$ if (pos > -1) return pos; return message.indexOf(Text.DELIMITER, oldPos + 1); }

Target:
Is there any reason why not use here Text.DELIMITER instead of "\n"?
Source:
public boolean equals(Object obj) { if (obj == null || !(obj instanceof FilterPath)) { return false; } FilterPath other = (FilterPath) obj; if (path == null) { return other.path == null; } return path.equals(other.path); }

Target:
style-nit; we don't use braces for simple single stament constructs
Source:
public int hashCode() { if (path != null) { return path.hashCode(); } return super.hashCode(); }

Target:
style-nit; we don't use braces for simple single stament constructs
Source:
public void setTreeFilter(TreeFilter filter) { super.setTreeFilter(filter); if (filter instanceof FollowFilter) { FollowFilter followFilter = (FollowFilter) filter; RenameCallback renameCallback = followFilter.getRenameCallback(); if (renameCallback == null) { followFilter.setRenameCallback(callback); } } }

Target:
style nit: we don't use curly braces around single line blocks
Source:
public void addAdditionalRefs(final Repository repo) throws IOException { for (Ref ref : repo.getRefDatabase().getAdditionalRefs()) { Set<Ref> set = reverseRefMap.get(ref.getObjectId()); if (set == null) { set = Collections.singleton(ref); } else { set = new HashSet<Ref>(set); set.add(ref); } reverseRefMap.put(ref.getObjectId(), set); } }

Target:
style nit: no braces around single line blocks
Source:
private void handleException(final URIish uri, Exception e, String userMessage) { if (uri != null) operationResult.addOperationResult(uri, userMessage); String uriString; if (uri == null) uriString = "retrieving URI failed"; //$NON-NLS-1$ else uriString = uri.toString(); String userMessageForUri = NLS.bind( CoreText.PushOperation_ExceptionOccurredDuringPushOnUriMessage, uriString, userMessage); Activator.logError(userMessageForUri, e); }

Target:
This looks convoluted ... instead do String uriString; if (uri != null) { operationResult.addOperationResult(uri, userMessage); uriString = uri.toString(); } else uriString = "retrieving URI failed"; //$NON-NLS-1$
Source:
private LabelProvider getWorkbenchLabelProvider() { if(workbenchLabelProvider == null) { workbenchLabelProvider = new WorkbenchLabelProvider(); } return workbenchLabelProvider; }

Target:
curly brackets can be removed
Source:
public void showReflogFor(Repository repository) { String refName = Constants.R_HEADS + Constants.MASTER; try { Ref ref = repository.getRef(Constants.HEAD); if (ref != null && ref.isSymbolic()) refName = ref.getTarget().getName(); } catch (IOException e) { Activator.logError("Error getting HEAD reference", e); //$NON-NLS-1$ } showReflogFor(repository, refName); }

Target:
no, don't resolve the symbolic link here otherwise you get the reflog for the branch HEAD is pointing at, instead I would like to see the extra reflog maintained for HEAD which follows all updates of HEAD including branch switches with is not the case for git reflog for a branch. Use just refName = Constants.HEAD instead of refName = ref.getTarget().getName() then you'll see the difference, select master to see the difference. Also the branch selection dialog of the reflog view needs to show HEAD otherwise this cannot be selected explicitly.
Source:
private static int findGroupStart(String pattern, int currentIndex, Character invalidWildgetCharacter) { if (invalidWildgetCharacter != null && invalidWildgetCharacter == '\\') { return pattern.indexOf('[', currentIndex); } return findNotEscapedCharacterPosition(pattern, currentIndex, '['); }

Target:
style-nit; no braces for simple single-statement constrcuts
Source:
static File searchPath(final String path, final String... lookFor) { if (path == null) { return null; } for (final String p : path.split(File.pathSeparator)) { for (String command : lookFor) { final File e = new File(p, command); if (e.isFile()) return e.getAbsoluteFile(); } } return null; }

Target:
style nit: we don't use curly braces around single line blocks
Source:
private boolean onlyBranchesAreSelected(TreeSelection selection) { Iterator selIterator = selection.iterator(); for (Object sel = selIterator.next(); selIterator.hasNext(); sel = selIterator .next()) { if (sel instanceof RefNode) { RefNode node = (RefNode) sel; String refName = node.getObject().getName(); if (!refName.startsWith(Constants.R_HEADS)) return false; } else return false; } return true; }

Target:
how about the following ? I find this easier to read : while (selIterator.hasNext()) { Object sel = selIterator.next(); ... }
Source:
private static IDialogSettings getOrCreateSection(IDialogSettings settings, String sectionName) { IDialogSettings section = settings.getSection(sectionName); if (section == null) { section = settings.addNewSection(sectionName); } return section; }

Target:
style nit: we don't use curly braces for single line blocks
Source:
public static void reconfigure(DfsBlockCacheConfig cfg) { DfsBlockCache nc = new DfsBlockCache(cfg); DfsBlockCache oc = cache; cache = nc; if (oc != null) { if (oc.readAheadService != null) oc.readAheadService.shutdown(); for (DfsPackFile pack : oc.getPackFiles()) { pack.key.cachedSize.set(0); } } }

Target:
Style-nit: Curly braces on this loop are not necessary.
Source:
public static void createProjects(final Repository repository, final IProgressMonitor monitor) throws CoreException { List<File> projects = new ArrayList<File>(); if (ProjectUtil.findProjectFiles(projects, repository.getWorkTree() .getParentFile(), null, monitor)) for (File file : projects) ProjectUtil.createProject(repository, file, monitor); }

Target:
this is one level too high, searching the parent of the working tree might also find projects not located in the working tree of the newly cloned repository, also this may run a long time if this parent directory is big also the text displayed by the progress monitor is still "Cloning ..." instead of "Searching projects to auto-import"
Source:
protected IStructuredSelection getSelection(ReflogView view) { ISelection pageSelection = view.getSelectionProvider().getSelection(); if (pageSelection instanceof IStructuredSelection) { return (IStructuredSelection) pageSelection; } else return new StructuredSelection(); }

Target:
style-nit: remove curly brackets around single line block
Source:
private boolean isChanged(List<String> ol, List<String> nl) { if (ol.size() != nl.size()) return true; for (int i = 0; i < ol.size(); i++) { if (!ol.get(i).equals(nl.get(i))) return true; } return false; }

Target:
style nit: no curly braces around single line blocks
Source:
boolean hasChanged() { return configFile.lastModified() != lastModified; }

Target:
either mark lastModified volatile, or make this method synchronized to ensure the caller sees the correct version of the lastModified value from the last read() call.
Source:
public static PreReceiveHook newChain(List<? extends PreReceiveHook> hooks) { PreReceiveHook[] newHooks = new PreReceiveHook[hooks.size()]; int i = 0; for (PreReceiveHook hook : hooks) { if (hook != PreReceiveHook.NULL) newHooks[i++] = hook; } if (i == 0) return PreReceiveHook.NULL; else if (i == 1) return newHooks[0]; else return new PreReceiveHookChain(newHooks); }

Target:
same bug
Source:
public void onPreAdvertiseRefs(UploadPack up) throws UploadPackMayNotContinueException { for (PreUploadHook hook : hooks) { hook.onPreAdvertiseRefs(up); } }

Target:
curly braces
Source:
public void onBeginNegotiateRound(UploadPack up, Collection<? extends ObjectId> wants, int cntOffered) throws UploadPackMayNotContinueException { for (PreUploadHook hook : hooks) { hook.onBeginNegotiateRound(up, wants, cntOffered); } }

Target:
curly braces
Source:
public void onEndNegotiateRound(UploadPack up, Collection<? extends ObjectId> wants, int cntCommon, int cntNotFound, boolean ready) throws UploadPackMayNotContinueException { for (PreUploadHook hook : hooks) { hook.onEndNegotiateRound(up, wants, cntCommon, cntNotFound, ready); } }

Target:
curly braces
Source:
public void onSendPack(UploadPack up, Collection<? extends ObjectId> wants, Collection<? extends ObjectId> haves) throws UploadPackMayNotContinueException { for (PreUploadHook hook : hooks) { hook.onSendPack(up, wants, haves); } }

Target:
curly braces
Source:
public static UploadPackLogger newChain(List<? extends UploadPackLogger> loggers) { UploadPackLogger[] newLoggers = new UploadPackLogger[loggers.size()]; int i = 0; for (UploadPackLogger logger : loggers) { if (logger != UploadPackLogger.NULL) newLoggers[i++] = logger; } if (i == 0) return UploadPackLogger.NULL; else if (i == 1) return newLoggers[0]; else return new UploadPackLoggerChain(newLoggers); }

Target:
same bug
Source:
public void onPackStatistics(PackWriter.Statistics stats) { for (UploadPackLogger logger : loggers) { logger.onPackStatistics(stats); } }

Target:
curly braces
Source:
private TeamException getTeamException(final Throwable throwable) { Throwable current = throwable; while (current.getCause() != null) { current = current.getCause(); } return new TeamException(current.getMessage(), current); }

Target:
style nit: remove curly brackets
Source:
private static boolean containsRemoteForUrl(Config config, URIish url) throws URISyntaxException { Set<String> remotes = config.getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION); for (String remote : remotes) { String remoteUrl = config.getString( ConfigConstants.CONFIG_REMOTE_SECTION, remote, ConfigConstants.CONFIG_KEY_URL); URIish existingUrl = new URIish(remoteUrl); if (existingUrl.equals(url)) { return true; } } return false; }

Target:
style-nit: we don't use curly brackets around single line blocks
Source:
public static List<CloneSourceProvider> getCloneSourceProvider() { List<CloneSourceProvider> cloneSourceProvider = new ArrayList<CloneSourceProvider>(); IExtensionRegistry registry = Platform.getExtensionRegistry(); IConfigurationElement[] config = registry .getConfigurationElementsFor(CLONE_SOURCE_PROVIDER_ID); if (config.length > 0) { addCloneSourceProvider(cloneSourceProvider, config, 0); } return cloneSourceProvider; }

Target:
style nit: no curlies here
Source:
public IRepositoryServerProvider getRepositoryServerProvider() throws CoreException { if (repositoryServerProviderElement == null) return null; Object object = repositoryServerProviderElement .createExecutableExtension("class"); //$NON-NLS-1$ IRepositoryServerProvider provider = null; if (object instanceof IRepositoryServerProvider) { provider = (IRepositoryServerProvider) object; } return provider; }

Target:
style nit: we don't use curly brackets around single line blocks
Source:
public WizardPage getRepositorySearchPage() throws CoreException { if (repositorySearchPageELement == null) return null; Object object = repositorySearchPageELement .createExecutableExtension("class"); //$NON-NLS-1$ WizardPage page = null; if (object instanceof WizardPage && object instanceof IRepositorySearchResult) { page = (WizardPage) object; } return page; }

Target:
style nit: curly brackets