auphong2707/dl4se-code-review-dataset huggingface dataset:
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( START String.format("Cannot load SecureStore implementation: %s"), e); END } } Bug: Format string "%s" needs argument 1 but only 0 are provided

Target:
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", className), e); } }
Source:
private PatchSet getBasePatchSet(Change change, Ref ref) throws IOException, InvalidChangeOperationException { try { int pos = ref.getName().lastIndexOf("/"); String psId = START ref.getName().substring(++pos); END return db.get().patchSets().get(new PatchSet.Id( change.getId(), Integer.valueOf(psId))); } catch (OrmException e) { throw new IOException(e); } } pos + 1, since you're not depending on the side effect.

Target:
private PatchSet getBasePatchSet(Change change, Ref ref) throws IOException, InvalidChangeOperationException { try { int pos = ref.getName().lastIndexOf("/"); String psId = ref.getName().substring(pos + 1); return db.get().patchSets().get(new PatchSet.Id( change.getId(), Integer.valueOf(psId))); } catch (OrmException e) { throw new IOException(e); } }
Source:
public START Response<TreeSet<String>> apply(ChangeResource END 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)); } Make it Response<? extends Set<String>>

Target:
public Response<? extends Set<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)); }
Source:
public Set<AccountGroup.UUID> getAllOwners() { Set<AccountGroup.UUID> result = new START HashSet<AccountGroup.UUID>(); END for (ProjectState p : tree()) { result.addAll(p.localOwners); } return result; } In any event, since we're on Java7, just: new HashSet<>();

Target:
public Set<AccountGroup.UUID> getAllOwners() { Set<AccountGroup.UUID> result = new HashSet<>(); for (ProjectState p : tree()) { result.addAll(p.localOwners); } return result; }
Source:
void onAdd(ClickEvent e) { String hashtag = hashtagTextBox.getText(); START while (hashtag.startsWith("#")) { END hashtag = hashtag.substring(1); } if (!hashtag.isEmpty()) { addHashtag(hashtag); } } 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?

Target:
void onAdd(ClickEvent e) { String hashtag = hashtagTextBox.getText(); if (!hashtag.isEmpty()) { addHashtag(hashtag); } }
Source:
START static public void setLevel(int END value) { level.set(value); } 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.

Target:
static void setLevel(int value) { level.set(value); }
Source:
START static public void resetLevel() END { level.remove(); } Done

Target:
static void resetLevel() { level.remove(); }
Source:
public int weigh(EntryKey k, Boolean v) { // Size of EntryKey, 64-bit JVM. return 16 + 2 * (16 + 20) + 8 + 8 + START 2 * k.mergeStrategy.length() END + 1; // Size of Boolean. } 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.

Target:
public int weigh(EntryKey k, Boolean v) { return 16 + 2 * (16 + 20) + 4 * 8 // Size of EntryKey, 64-bit JVM. + 1; // Size of Boolean. }
Source:
START public static END 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; } Unneeded change. This only used in RegexPathPredicateTest, that is in the same package.

Target:
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; }
Source:
private List<SubmitRecord> ruleError(String err, Exception e) { if (logErrors) { if START (err == null) { END log.error(err); } else { log.error(err, e); } return defaultRuleError(); } else { return createRuleError(err); } } e == null

Target:
private List<SubmitRecord> ruleError(String err, Exception e) { if (logErrors) { if (e == null) { log.error(err); } else { log.error(err, e); } return defaultRuleError(); } else { return createRuleError(err); } }
Source:
START public void readGroupList() throws IOException { groupList = GroupList.parse(readUTF8(GroupList.FILE_NAME), this); } END Inline this method or at least make it private.

Target:
private void readGroupList() throws IOException { groupList = GroupList.parse(readUTF8(GroupList.FILE_NAME), this); }
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; } } } START return isMatch; END } Done

Target:
public boolean matches(NameKey name) { if (projectPatterns.isEmpty()) { return true; } else { String projectName = name.get(); for (String pattern : projectPatterns) { if (matchesPattern(projectName, pattern)) { return true; } } } return false; }
Source:
public BinaryResult apply(ChangeResource rsrc) throws AuthException, IOException, START InvalidChangeOperationException, OrmException, END 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(); } never thrown?

Target:
public BinaryResult apply(ChangeResource rsrc) throws AuthException, IOException, 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(); }
Source:
public CommentLinkInfo(Pattern pattern, String link) { START this.pattern = pattern; END this.link = checkNotNull(link); } checkNotNull(pattern), too?

Target:
public CommentLinkInfo(Pattern pattern, String link) { this.pattern = checkNotNull(pattern); this.link = checkNotNull(link); }
Source:
public static Change.Id changeIdFromDraftComments(String refName) { int d = refName.lastIndexOf('-'); return new Change.Id(Integer.parseInt(refName.substring(d + START 1), 10)); END } This is optional, it's the default, and Java doesn't do anything dumb like treat leading 0s as octal.

Target:
public static Change.Id changeIdFromDraftComments(String refName) { int d = refName.lastIndexOf('-'); return new Change.Id(Integer.parseInt(refName.substring(d + 1))); }
Source:
public START CheckResult check(Change END 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(); } } } This return value in unexpected. This method doesn't render ChangeInfo. So no reason to instantiate CheckResult. Just return messages.

Target:
public List<String> check(Change c) { reset(); change = c; try { checkImpl(); return messages; } finally { if (rw != null) { rw.release(); } if (repo != null) { repo.close(); } } }
Source:
static boolean needsQuotedPrintableWithinPhrase(final int cp) { switch (cp) { case '!': case '*': case '+': case '-': case '/': case '=': case '_': return false; default: if START ((cp >= 'a' && cp <= 'z') END || (cp >= 'A' && cp <= 'Z') || (cp >= '0' && cp <= '9')) { return false; } else { return true; } } } 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

Target:
static boolean needsQuotedPrintableWithinPhrase(final int cp) { switch (cp) { case '!': case '*': case '+': case '-': case '/': case '=': case '_': return false; default: if (('a' <= cp && cp <= 'z') || ('A' <= cp && cp <= 'Z') || ('0' <= cp && cp <= '9')) { return false; } else { return true; } } }
Source:
private static void validateRequestMethod(HttpServletRequest req) throws MethodNotAllowedException { START if (!"GET".equals(req.getMethod()) && !"HEAD".equals(req.getMethod())) { END throw new MethodNotAllowedException(); } } Or: if (!(req.getMethod().equals("GET") || req.getMethod().equals("HEAD")))

Target:
private static void validateRequestMethod(HttpServletRequest req) throws MethodNotAllowedException { if (!("GET".equals(req.getMethod()) || "HEAD".equals(req.getMethod()))) { throw new MethodNotAllowedException(); } }
Source:
public void onLoad(Screen screen) { String projectName = URL.decode(screen.getToken(1)); String START fileName = END URL.decode(screen.getToken(2)); screen.show(new XDocScreen(projectName, "HEAD", fileName)); screen.setWindowTitle(getFileName(fileName)); } Rename this to `path` to make it consistent with the parameter name on getFileName?

Target:
public void onLoad(Screen screen) { String projectName = URL.decode(screen.getToken(1)); String path = URL.decode(screen.getToken(2)); screen.show(new XDocScreen(projectName, "HEAD", path)); screen.setWindowTitle(getFileName(path)); }
Source:
private int getPermittedLimit() { START if (!enforceVisibility) { return Integer.MAX_VALUE; } return userProvider.get().getCapabilities() .getRange(GlobalCapability.QUERY_LIMIT) .getMax(); END } I would wrap the user code: if (enforceVisibility) { return userProvider.get()... } return Integer.MAX_VALUE;

Target:
private int getPermittedLimit() { if (enforceVisibility) { return userProvider.get().getCapabilities() .getRange(GlobalCapability.QUERY_LIMIT) .getMax(); } return Integer.MAX_VALUE; }
Source:
void onEditMode(@SuppressWarnings("unused") ClickEvent e) { fileTableMode = FileTable.Mode.EDIT; refreshFileTable(); editMode.setVisible(false); START reply.setVisible(false); END addFile.setVisible(true); reviewMode.setVisible(true); } Toggling edit mode in file table, doesn't imply that we have a change edit yet: it is still possible to post reviews?

Target:
void onEditMode(@SuppressWarnings("unused") ClickEvent e) { fileTableMode = FileTable.Mode.EDIT; refreshFileTable(); editMode.setVisible(false); addFile.setVisible(true); reviewMode.setVisible(true); }
Source:
public Object apply(RevisionResource rsrc) throws START AuthException, BadRequestException, ResourceConflictException, Exception { END return Response.withMustRevalidate(delegate.get().format(rsrc)); } All these exceptions are unsed. "Exception" is never used in real code, only in unit tests.

Target:
public Object apply(RevisionResource rsrc) { return Response.withMustRevalidate(delegate.format(rsrc)); }
Source:
public Object apply(RevisionResource rsrc) throws AuthException, BadRequestException, ResourceConflictException, Exception { START return Response.withMustRevalidate(delegate.format(rsrc)); END } This is GetRevisionActions, why is it returning a ChangeInfo? "Actions for this revision" sounds like a Map<String, ActionInfo>, no?

Target:
public Object apply(RevisionResource rsrc) throws AuthException, BadRequestException, ResourceConflictException, Exception { return Response.withMustRevalidate(delegate.get().format(rsrc)); }
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)) { START found = true; break; END } } return found; } Local variable is not necessary. Instead, here we can just do: return true;

Target:
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)) { return true; } } return false; }
Source:
public Rule[] blockPluginRules() { return new Rule[]{ toc(), note(), START cols(), END }; } Alphabetize these?

Target:
public Rule[] blockPluginRules() { return new Rule[] { cols(), note(), toc(), }; }
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, START batchRefUpdate); END 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); } } batchRefUpdate can be null now and we would get an NPE inside the fire method.

Target:
public void execute() throws UpdateException, RestApiException { try { executeRefUpdates(); executeChangeOps(); reindexChanges(); if (batchRefUpdate != null) { // 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); } }
Source:
START private int getPluginsLoadTimeout(final Config cfg) { END long cfgValue = ConfigUtil.getTimeUnit(cfg, "plugins", null, "jsLoadTimeout", DEFAULT_JS_LOAD_TIMEOUT, TimeUnit.MILLISECONDS); if (cfgValue < 0) { return 0; } return (int) cfgValue; } method should be static

Target:
private static 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; }
Source:
public synchronized void unregister(URI key) { START if (locks.containsKey(key)) { END LockProvider provider = locks.get(key); if (provider != null) { provider.decreateCount(); if (provider.getRegisterCount() < 1) { locks.remove(key); } } } } Unnecessary given the next two lines which perform a get and test for null on the result.

Target:
public synchronized void unregister(URI key) { LockProvider provider = locks.get(key); if (provider != null) { provider.decreateCount(); if (provider.getRegisterCount() < 1) { locks.remove(key); } } }
Source:
private RemoteConfig selectDefaultRemoteConfig() { for (final RemoteConfig rc : configuredRemotes) START if (getTextForRemoteConfig(rc) == Constants.DEFAULT_REMOTE_NAME) END return rc; return configuredRemotes.get(0); } Use .equals()

Target:
private RemoteConfig selectDefaultRemoteConfig() { for (final RemoteConfig rc : configuredRemotes) if (Constants.DEFAULT_REMOTE_NAME.equals(getTextForRemoteConfig(rc))) return rc; return configuredRemotes.get(0); }
Source:
protected MergeChunk(int sequenceIndex, int begin, int end, ConflictState conflictState) { START super(); END this.sequenceIndex = sequenceIndex; this.begin = begin; this.end = end; this.conflictState = conflictState; } Style-nit: We don't call super if there are no arguments to it.

Target:
protected MergeChunk(int sequenceIndex, int begin, int end, ConflictState conflictState) { this.sequenceIndex = sequenceIndex; this.begin = begin; this.end = end; this.conflictState = conflictState; }
Source:
public TagOperation(Repository repo, Tag tag, boolean shouldMoveTag) { this.tag = tag; this.repo = repo; START tagName = tag.getTag(); END this.shouldMoveTag = shouldMoveTag; refName = Constants.R_TAGS + tagName; } tagName is redundant. Use local variablesl later on if necessary

Target:
public TagOperation(Repository repo, Tag tag, boolean shouldMoveTag) { this.tag = tag; this.repo = repo; this.shouldMoveTag = shouldMoveTag; }
Source:
public void setSelectedElement(ObjectId objectId) { START if (null == objectId) { END return; } for (int i = 0; i < commits.size(); i++) if (objectId.equals(commits.get(i).objectId)) { combo.select(i); break; } } Why not the more straightforward objectId == null? (this isn't C)

Target:
public void setSelectedElement(ObjectId objectId) { if (objectId == null) { return; } for (int i = 0; i < commits.size(); i++) if (objectId.equals(commits.get(i).objectId)) { combo.select(i); break; } }
Source:
public CommitCommand setCommitter(String name, String email) { START this.committer = new PersonIdent(name, email); END return this; } 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)); }

Target:
public CommitCommand setCommitter(String name, String email) { return setCommitter(new PersonIdent(name, email)); }
Source:
public CommitCommand commit() { START return (new CommitCommand(this)); END } Style-nit: We don't put parens around return. Thus: return new CommitCommand(this);

Target:
public CommitCommand commit() { return new CommitCommand(this); }
Source:
public LogCommand log() { START return (new LogCommand(this)); END } style: extra parentheses

Target:
public LogCommand log() { return new LogCommand(this); }
Source:
public Repository getRepository() { START return(repo); END } style: extra parentheses

Target:
public Repository getRepository() { return repo; }
Source:
public void execute(IAction action) { START IHistoryView view = TeamUI.showHistoryFor(TeamUIPlugin.getActivePage(), getSelectedResources()[0], null); END IHistoryPage page = view.getHistoryPage(); if (page instanceof GitHistoryPage){ GitHistoryPage gitHistoryPage = (GitHistoryPage) page; gitHistoryPage.setCompareMode(true); } } The API says null can be returned, we should check for this.

Target:
public void execute(IAction action) { IHistoryView view = TeamUI.showHistoryFor(TeamUIPlugin.getActivePage(), getSelectedResources()[0], null); if (view == null) return; IHistoryPage page = view.getHistoryPage(); if (page instanceof GitHistoryPage){ GitHistoryPage gitHistoryPage = (GitHistoryPage) page; gitHistoryPage.setCompareMode(true); } }
Source:
private void removeEmptyParents(File f) { File parentFile = f.getParentFile(); while (!parentFile.equals(repo.getWorkDir())) { START if (parentFile.list().length == 0) END parentFile.delete(); else break; parentFile = parentFile.getParentFile(); } } 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.

Target:
private void removeEmptyParents(File f) { File parentFile = f.getParentFile(); while (!parentFile.equals(repo.getWorkDir())) { if (!parentFile.delete()) break; parentFile = parentFile.getParentFile(); } }
Source:
public GitIndex getIndex() throws IOException { if (isBare()) START throw new IOException( END JGitText.get().bareRepositoryNoWorkdirAndIndex); if (index == null) { index = new GitIndex(this); index.read(); } else { index.rereadIfNecessary(); } return index; } Why do we throw IOException here and IllegalStateException in getIndexFile()? Can we at least throw the same type consistently?

Target:
public GitIndex getIndex() throws IOException, IllegalStateException { if (isBare()) throw new IOException( JGitText.get().bareRepositoryNoWorkdirAndIndex); if (index == null) { index = new GitIndex(this); index.read(); } else { index.rereadIfNecessary(); } return index; }
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; START return true; END } With all of the logic in the constructor, I wonder if we can simplify this method down to: public boolean isBare() { return workDir == null; }

Target:
public boolean isBare() { return workDir == null; }
Source:
public void resourceChanged(IResourceChangeEvent event) { START if (event.getType() == IResourceChangeEvent.POST_CHANGE) { END state = true; } } style nit: no braces around single line

Target:
public void resourceChanged(IResourceChangeEvent event) { if (event.getType() == IResourceChangeEvent.POST_CHANGE) state = true; }
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(); START if (rowName.contains(projectName)) { END return true; } } return false; } style nit: no braces around single line

Target:
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; }
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$ START if (memberRelPath.startsWith("/")) { //$NON-NLS-1$ END memberRelPath = memberRelPath.substring(1); } return memberRelPath; } style nit: no braces around single line

Target:
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; }
Source:
public void flushVariants(IResource resource, int depth) throws TeamException { START if (!gsdData.getData(resource.getProject()).shouldIncludeLocal()) { END store.flushBytes(resource, depth); } } style nit: no braces around single line

Target:
public void flushVariants(IResource resource, int depth) throws TeamException { if (!gsdData.getData(resource.getProject()).shouldIncludeLocal()) store.flushBytes(resource, depth); }
Source:
protected int hashLine(final byte[] raw, int ptr, final int end) { int hash = 5381; for (; ptr < end; ptr++) { START if (!RawCharUtil.isWhitespace(raw[ptr])) { END hash = (hash << 5) ^ (raw[ptr] & 0xff); } } return hash; } Performance-nit: Same nit as above, pull raw[ptr] into a local variable so its not evaluated twice.

Target:
protected int hashLine(final byte[] raw, int ptr, final int end) { int hash = 5381; for (; ptr < end; ptr++) { byte c = raw[ptr]; if (!isWhitespace(c)) hash = (hash << 5) ^ (c & 0xff); } return hash; }
Source:
FileHeader(final byte[] b, final int offset) { START changeType = ChangeType.MODIFY; // unless otherwise designated END buf = b; startOffset = offset; patchType = PatchType.UNIFIED; } Please don't move this line around in the constructor, its not essential to the patch.

Target:
FileHeader(final byte[] b, final int offset) { buf = b; startOffset = offset; changeType = ChangeType.MODIFY; // unless otherwise designated patchType = PatchType.UNIFIED; }
Source:
public void setUp() throws Exception { super.setUp(); iProject = project.project; if (!gitDir.exists()) new FileRepository(gitDir).create(); START new ConnectProviderOperation(iProject, gitDir).execute(null); END testRepo = new TestRepository(gitDir); testRepo.connect(iProject); repo = RepositoryMapping.getMapping(iProject).getRepository(); } 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.

Target:
public void setUp() throws Exception { super.setUp(); iProject = project.project; testRepo = new TestRepository(gitDir); testRepo.connect(iProject); repo = RepositoryMapping.getMapping(iProject).getRepository(); }
Source:
START private DiffEntry bestPathMatch(DiffEntry src, List<DiffEntry> list) { END 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; } Style-nit: This can be a static method.

Target:
private static 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; }
Source:
public void close() throws IOException { try { START super.close(); END } finally { is.close(); } } There is no need to call super.close() on InputStream. It is a no-op method. Instead you just need to do is.close();

Target:
public void close() throws IOException { is.close(); }
Source:
protected void createButtonsForButtonBar(Composite parent) { // OK button only createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); START setTitle(myTitle); END } 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.

Target:
protected void createButtonsForButtonBar(Composite parent) { // OK button only createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); }
Source:
public String getMessage() { START return name; END } that's wrong, should be: return message;

Target:
public String getMessage() { return message; }
Source:
private static int lastIndexOfTrim(byte[] raw, char ch, int pos) { START while (pos >= 0 && raw[pos] == ' ') { END pos--; } while (pos >= 0 && raw[pos] != ch) { pos--; } return pos; } Style-nit: We don't use curly braces around simple loops.

Target:
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; }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + remoteCommit.hashCode(); START result = prime * result + baseCommit.hashCode(); END result = prime * result + getLocation().hashCode(); return result; } 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'.

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getLocation().hashCode(); result = prime * result + remoteCommit.hashCode(); if (baseCommit != null) result = prime * result + baseCommit.hashCode(); return result; }
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; START if (isneg) { END value = -value; } while (value != 0) { b[--o] = base10byte[value % 10]; value /= 10; } if (isneg) b[--o] = '-'; return o; } 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.

Target:
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; }
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); START if (rule.isMatch(entryPath, isDirectory)) { END return rule.getAttributes(); } } return Collections.emptyList(); } Done

Target:
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 >= 0; i--) { AttributesRule rule = rules.get(i); if (rule.isMatch(entryPath, isDirectory)) return rule.getAttributes(); } return Collections.emptyList(); }
Source:
public boolean equals(Object obj) { START if (obj == null || obj.getClass() != getClass()) { END return false; } final Attribute attribute = (Attribute) obj; return CompareUtils.areEqual(key, attribute.getKey()) && CompareUtils.areEqual(value, attribute.getValue()); } 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.

Target:
public boolean equals(Object obj) { if (obj instanceof Attribute) { final Attribute attribute = (Attribute) obj; return CompareUtils.areEqual(key, attribute.getKey()) && CompareUtils.areEqual(value, attribute.getValue()); } return false; }
Source:
public int hashCode() { START return key.hashCode() ^ value.hashCode(); END } 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.

Target:
public int hashCode() { return key.hashCode(); }
Source:
public PushCommand setRefSpecs(RefSpec... specs) { checkCallable(); this.refSpecs.clear(); START for (RefSpec spec : specs) END refSpecs.add(spec); return this; } could be simplified: Collections.addAll(refsSpecs, specs);

Target:
public PushCommand setRefSpecs(RefSpec... specs) { checkCallable(); this.refSpecs.clear(); Collections.addAll(refSpecs, specs); return this; }
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]; START size = rawlstat[9] + rawlstat[10] << 32; END } 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.

Target:
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 = (((long) rawlstat[9]) << 32) + rawlstat[10]; }
Source:
START public FSAccessNative() { END // empty default constructor } Should this be package visible only?

Target:
FSAccessNative() { // empty }
Source:
public int getSize() { START return rawlstat[9]; END } This should be a long.

Target:
public long getSize() { return size; }
Source:
protected void run() throws Exception { AddCommand addCmd = new Git(db).add(); addCmd.setUpdate(update); START for (String p : filepatterns) { END addCmd.addFilepattern(p); } addCmd.call(); } Style-nit: We don't put around a single statement.

Target:
protected void run() throws Exception { AddCommand addCmd = new Git(db).add(); addCmd.setUpdate(update); for (String p : filepatterns) addCmd.addFilepattern(p); addCmd.call(); }
Source:
START public HashSet<String> getAssumeUnchanged() { END return assumeUnchanged; } 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>.)

Target:
public Set<String> getAssumeUnchanged() { return assumeUnchanged; }
Source:
START public static InitCommand init() { END return new InitCommand(); } Style-nit: Static methods should appear at the start of the class, before instance members.

Target:
static public InitCommand init() { return new InitCommand(); }
Source:
private FanoutBucket asFanout(InMemoryNoteBucket bucket) { if (bucket == null) return EMPTY_FANOUT; if (bucket instanceof FanoutBucket) return (FanoutBucket) bucket; START FanoutBucket fanoutBucket = ((LeafBucket) bucket).split(); END return fanoutBucket; } Since we dropped the writeTree call, we probably don't need this local variable anymore and can instead just return the result of split().

Target:
private FanoutBucket asFanout(InMemoryNoteBucket bucket) { if (bucket == null) return EMPTY_FANOUT; if (bucket instanceof FanoutBucket) return (FanoutBucket) bucket; return ((LeafBucket) bucket).split(); }
Source:
public NotesMergeConflictException(NonNoteEntry base, NonNoteEntry ours, NonNoteEntry theirs) { super(MessageFormat.format( START JGitText.get().mergeConflictOnNonNoteEntries, base.name(), END ours.name(), theirs.name())); } 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() : ""; }

Target:
public NotesMergeConflictException(NonNoteEntry base, NonNoteEntry ours, NonNoteEntry theirs) { super(MessageFormat.format( JGitText.get().mergeConflictOnNonNoteEntries, name(base), name(ours), name(theirs))); }
Source:
START public InMemoryNoteBucket getRoot() { END return root; } This shouldn't be public, the type it returns isn't public.

Target:
InMemoryNoteBucket getRoot() { return root; }
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(); START fanoutBucket.writeTree(inserter); END return fanoutBucket; } 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.

Target:
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; }
Source:
public NotesMergeConflictException(NonNoteEntry base, NonNoteEntry ours, NonNoteEntry theirs) { super(MessageFormat.format(JGitText.get().mergeConflictOnNonNoteEntries, START base, ours, theirs)); END } You probably want to use the name field from the NonNoteEntry rather than rely on the toString().

Target:
public NotesMergeConflictException(NonNoteEntry base, NonNoteEntry ours, NonNoteEntry theirs) { super(MessageFormat.format( JGitText.get().mergeConflictOnNonNoteEntries, base.name(), ours.name(), theirs.name())); }
Source:
START public void testAddAdd() throws Exception { END 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")); } what's the difference compared to testEditEdit() ?

Target:
public void testAddAdd() throws Exception { Note add1 = newNote("add1"); Note add2 = newNote("add2"); Note result = merger.merge(null, add1, add2); assertEquals(result, noteOn); // same note assertEquals(result.getData(), tr.blob("add1add2")); result = merger.merge(null, add2, add1); assertEquals(result, noteOn); // same note assertEquals(result.getData(), tr.blob("add2add1")); }
Source:
START public List<String> getConflictList() { END return conflictList; } wouldn't it be better to return List<File> here ?

Target:
public List<File> getConflictList() { return conflictList; }
Source:
START ObjectId getData() { END return data; } We also need to make this public. Otherwise the client of the Iterator<Note> cannot see the blob that is attached to the note.

Target:
public ObjectId getData() { return data; }
Source:
START public java.security.cert.X509Certificate[] getAcceptedIssuers() { END return null; } Style-nit: We prefer to import these names and use the short class name instead.

Target:
public X509Certificate[] getAcceptedIssuers() { return null; }
Source:
private void initCommitsMap() { commitsMap = new HashMap<String, PlotCommit>(); START for (PlotCommit commit : allCommits) { END commitsMap.put(commit.getId().name(), commit); } } please remove brackets since we don't use brackets for single line statements

Target:
private void initCommitsMap() { commitsMap = new HashMap<String, PlotCommit>(); for (PlotCommit commit : allCommits) commitsMap.put(commit.getId().name(), commit); }
Source:
private String formatHeadRef(Ref ref) { final String name = ref.getName(); START if (name.startsWith(Constants.R_HEADS)) { END return name.substring(Constants.R_HEADS.length()); } else if (name.startsWith(Constants.R_REMOTES)) { return name.substring(Constants.R_REMOTES.length()); } return name; } please remove brackets

Target:
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; }
Source:
protected void initializeConfiguration( ISynchronizePageConfiguration configuration) { configuration.setProperty(ISynchronizePageConfiguration.P_VIEWER_ID, VIEWER_ID); configuration.setProperty( ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER, GitChangeSetModelProvider.ID); START configuration.addActionContribution(new GitActionContributor()); END super.initializeConfiguration(configuration); configuration.addActionContribution(new GitActionContributor()); } Why are you adding this twice?

Target:
protected void initializeConfiguration( ISynchronizePageConfiguration configuration) { configuration.setProperty(ISynchronizePageConfiguration.P_VIEWER_ID, VIEWER_ID); configuration.setProperty( ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER, GitChangeSetModelProvider.ID); super.initializeConfiguration(configuration); configuration.addActionContribution(new GitActionContributor()); }
Source:
private void resetMerge() throws IOException { try { repo.writeMergeHeads(null); repo.writeMergeCommitMsg(null); START } catch (IOException e) { END throw e; } } unused try catch block

Target:
private void resetMerge() throws IOException { repo.writeMergeHeads(null); repo.writeMergeCommitMsg(null); }
Source:
public final int getRefCount() { START return refs == null ? 0 : refs.length; END } 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().

Target:
public final int getRefCount() { return refs.length; }
Source:
private static void loadIdentity(final JSch sch, final File priv) { if (priv.isFile()) { try { sch.addIdentity(priv.getAbsolutePath()); START } catch (final JSchException e) { END // Instead, pretend the key doesn't exist. } } } Style-nit: No reason to add final.

Target:
private static void loadIdentity(final JSch sch, final File priv) { if (priv.isFile()) { try { sch.addIdentity(priv.getAbsolutePath()); } catch (JSchException e) { // Instead, pretend the key doesn't exist. } } }
Source:
public void disconnect() { START if (sock.isConnected()) { END sock.disconnect(); } } style nit: we don't use curly braces around single line blocks

Target:
public void disconnect() { if (sock.isConnected()) sock.disconnect(); }
Source:
public void destroy() { START if (channel.isConnected()) { END channel.disconnect(); } } Style-nit: No curly braces on single statements.

Target:
public void destroy() { if (channel.isConnected()) channel.disconnect(); }
Source:
private List<Repository> getRepositories() { List<Repository> reposList = new LinkedList<Repository>(); Iterator<RepositoryTreeNode> it = ((IStructuredSelection) repositoryTableViewer.getSelection()).iterator(); START while (it.hasNext()) { END reposList.add(it.next().getRepository()); } return reposList; } style nit: we don't use braces around single line blocks

Target:
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; }
Source:
public List<Repository> getSelectedRepositories() { START if (repos.isEmpty()) { END return null; } return repos; } style nit: no braces around single line blocks

Target:
public List<Repository> getSelectedRepositories() { if (repos.isEmpty()) return null; return repos; }
Source:
public boolean promptPassword(String msg) { START CredentialItem.Password p = new CredentialItem.Password(); END 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; } } } 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.

Target:
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; } } }
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 { START CredentialItem.StringType v = newPrompt(msg); END if (provider.get(uri, v)) { password = v.getValue(); return true; } else { password = null; return false; } } } 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.

Target:
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 { password = null; return false; } }
Source:
private void activateContextService() { IContextService contextService = (IContextService) getSite() .getService(IContextService.class); START if (contextService != null) { END contextService.activateContext(VIEW_ID); } } Style-nit: no brackets around single-line blocks

Target:
private void activateContextService() { IContextService contextService = (IContextService) getSite() .getService(IContextService.class); if (contextService != null) contextService.activateContext(VIEW_ID); }
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: START return COPY; END case DELETE: return getDecoratedImage(getEditorImage(c), UIIcons.OVR_STAGED_REMOVE); case RENAME: // fall through case MODIFY: return getEditorImage(c); } } return null; } I think this case should be in the list of fallback cases (unfortunately, I don't know how to create a COPY diff)...

Target:
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 DELETE: return getDecoratedImage(getEditorImage(c), UIIcons.OVR_STAGED_REMOVE); case COPY: // fall through case RENAME: // fall through case MODIFY: return getEditorImage(c); } } return null; }
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++) START repositories.add(repos[i]); END new PullOperationUI(repositories).start(); return null; } how about this: new HashSet<Repository>(Arrays.asList(repos));

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { Repository[] repos = getRepositories(event); if (repos.length == 0) return null; Set<Repository> repositories = new HashSet<Repository>( Arrays.asList(repos)); new PullOperationUI(repositories).start(); return null; }