auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void tearDown() throws Exception { Activator.getDefault().getRepositoryCache().clear(); for (IProject project : createdProjects) { START if (project.exists()) { END project.delete(true, true, null); } } for (File pathToClean : pathsToClean) { if (pathToClean.exists()) { FileUtils.delete(pathToClean, FileUtils.RECURSIVE | FileUtils.RETRY); } } } style nit: we don't use braces around single line blocks, more occurrences throughout this patch

Target:
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); }
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. START welcomePageClosed = true; END } } Shouldn't we put this into a finally block? Saves one line of code...

Target:
public static void closeWelcomePage() { if (welcomePageClosed) return; try { bot.viewByTitle("Welcome").close(); } catch (WidgetNotFoundException e) { // somebody else probably closed it, lets not feel bad about it. } finally { welcomePageClosed = true; } }
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; START ObjectId head = ObjectId.fromString(raw, 0); END return head; } Style-nit: There is no good reason for this local variable "head".

Target:
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; return ObjectId.fromString(raw, 0); }
Source:
protected void makeChangesAndCommit(String projectName) throws Exception { changeFilesInProject(); START Thread.sleep(1000); // wait 1 s to get different time stamps END // TODO can be removed when commit is based on DirCache commit(projectName); } commit is using DirCache since a while

Target:
protected void makeChangesAndCommit(String projectName) throws Exception { changeFilesInProject(); commit(projectName); }
Source:
START private byte[] readGitDirectoryFile(String filename) throws IOException { END 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; } 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.

Target:
private byte[] readGitDirectoryFile(String filename) throws IOException { File file = new File(getDirectory(), filename); try { byte[] raw = IO.readFully(file); return raw.length > 0 ? raw : null; } catch (FileNotFoundException notFound) { return null; } }
Source:
public Object getAdapter(Class adapter) { START if (adapter == IResource.class) { END return resource; } return null; } style nit: we don't use curly braces around single line blocks

Target:
public Object getAdapter(Class adapter) { if (adapter == IResource.class) return resource; return null; }
Source:
public String toString() { START if (parent != null && parent.getResource() instanceof IProject) { END return resource.getProjectRelativePath().toString(); } return resource.getName(); } style nit: no braces here

Target:
public String toString() { if (parent != null && parent.getResource() instanceof IProject) return resource.getProjectRelativePath().toString(); return resource.getName(); }
Source:
START public Line(RevCommit startCommit, int lineNumber) { END commit = startCommit; number = lineNumber; } 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.

Target:
Line(RevCommit startCommit, int lineNumber) { commit = startCommit; number = lineNumber; }
Source:
private List<ResourceTraversal> createTraversalForContainer(GitModelObject child) { GitModelObject[] containerChildren = child.getChildren(); List<ResourceTraversal> result = new ArrayList<ResourceTraversal>(); for (GitModelObject aChild : containerChildren) { START if(aChild.isContainer()) { END result.addAll(createTraversalForContainer(aChild)); } else { result.add(createTraversalForFile(aChild)); } } return result; } Curly brackets are not needed here ;)

Target:
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; }
Source:
protected void initializeConfiguration( ISynchronizePageConfiguration configuration) { configuration.setProperty(ISynchronizePageConfiguration.P_VIEWER_ID, VIEWER_ID); String modelProvider; if(Activator.getDefault().getPreferenceStore().getBoolean( START UIPreferences.SYNC_VIEW_ALWAYS_SHOW_CHANGESET_MODEL)) { END modelProvider = GitChangeSetModelProvider.ID; } else { modelProvider = WORKSPACE_MODEL_PROVIDER_ID; } configuration.setProperty( ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER, modelProvider); super.initializeConfiguration(configuration); configuration.addActionContribution(new GitActionContributor()); } as usually, please remove curly brackets around single line blocks

Target:
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()); }
Source:
private Collection<String> buildFileList(Collection<IFile> files) throws CoreException { START Collection<String> result = new ArrayList<String>(); END 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; } I think HashSet would be faster as in addUntracked() you call contains() which is O(n) for ArrayList but O(1) for HashSet

Target:
private Collection<String> buildFileList(Collection<IFile> files) throws CoreException { Collection<String> result = new HashSet<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; }
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); START if (c.isInstance(adapter)) { END return adapter; } } return null; } style nit: we use no braces around single line blocks

Target:
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; }
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); START } END } Please retain the ability to clear the credentials by calling with null username and password

Target:
public void setCredentials(String user, String password) { Credentials credentials = null; if (user != null && password != null) credentials = new UsernamePasswordCredentials(user, password); this.client.getCredentialsProvider().setCredentials( new AuthScope(httpHost.getHostName(), httpHost.getPort()), credentials); }
Source:
public void run() { store.setValue(prefName, isChecked()); START if (store.needsSaving()) { END try { store.save(); } catch (IOException e) { Activator.handleError(e.getMessage(), e, false); } } } These curlies are un-needed

Target:
public void run() { store.setValue(prefName, isChecked()); if (store.needsSaving()) try { store.save(); } catch (IOException e) { Activator.handleError(e.getMessage(), e, false); } }
Source:
/*package*/List<IResource> getRelevantResources() { List<IResource> resourcesInScope = new ArrayList<IResource>(); ResourceTraversal[] traversals = getScope().getTraversals(); START for (ResourceTraversal resourceTraversal : traversals) { END resourcesInScope.addAll(Arrays.asList(resourceTraversal .getResources())); } return resourcesInScope; } style nit: no braces around single line block

Target:
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; }
Source:
public static synchronized GitScopeOperationFactory getFactory() { START if(instance == null) { END instance = new GitScopeOperationFactory(); } return instance; } style nit: no braces around single line blocks

Target:
public static synchronized GitScopeOperationFactory getFactory() { if(instance == null) instance = new GitScopeOperationFactory(); return instance; }
Source:
private static ResourceMapping[] getResourceMappings(IResource[] resources) { List<ResourceMapping> result = new ArrayList<ResourceMapping>(); for (IResource resource : resources) { START result.add(getResourceMapping(resource)); END } return result.toArray(new ResourceMapping[result.size()]); } style nit: no braces for single line block

Target:
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()]); }
Source:
public void execute(IProgressMonitor monitor) throws CoreException { Git repoTree; // discover repositories and run clean on them if (paths != null) { for (IResource res : resources) { START repoTree = new Git(getRepository(res)); END repoTree.clean().setPaths(paths).call(); } } else { for (IResource res : resources) { repoTree = new Git(getRepository(res)); repoTree.clean().call(); } } } you will get NPE if getRepository() return null (when given resource isn't in project shared by git).

Target:
public void execute(IProgressMonitor monitor) throws CoreException { Git repoTree; // discover repositories and run clean on them if (resources.length > 0) { 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(); } } } }
Source:
private static String stripLeadingZeros(String input) { START for (int i = 0; i < input.length(); i++) { END if (input.charAt(i) != '0') { return input.substring(i); } } return ""; //$NON-NLS-1$ } Code conventions: we don't use curly brackets around single line blocks

Target:
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$ }
Source:
private int findNextEOL(int oldPos, String message) { START int pos = message.indexOf("\n", oldPos + 1); //$NON-NLS-1$ END if (pos > -1) return pos; return message.indexOf(Text.DELIMITER, oldPos + 1); } Is there any reason why not use here Text.DELIMITER instead of "\n"?

Target:
private int findNextEOL(int oldPos, String message) { return message.indexOf(Text.DELIMITER, oldPos + 1); }
Source:
public boolean equals(Object obj) { START if (obj == null || !(obj instanceof FilterPath)) { END return false; } FilterPath other = (FilterPath) obj; if (path == null) { return other.path == null; } return path.equals(other.path); } style-nit; we don't use braces for simple single stament constructs

Target:
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); }
Source:
public int hashCode() { START if (path != null) { END return path.hashCode(); } return super.hashCode(); } style-nit; we don't use braces for simple single stament constructs

Target:
public int hashCode() { if (path != null) return path.hashCode(); return super.hashCode(); }
Source:
public void setTreeFilter(TreeFilter filter) { super.setTreeFilter(filter); if (filter instanceof FollowFilter) { FollowFilter followFilter = (FollowFilter) filter; RenameCallback renameCallback = followFilter.getRenameCallback(); START if (renameCallback == null) { END followFilter.setRenameCallback(callback); } } } style nit: we don't use curly braces around single line blocks

Target:
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); } }
Source:
public void addAdditionalRefs(final Repository repo) throws IOException { for (Ref ref : repo.getRefDatabase().getAdditionalRefs()) { Set<Ref> set = reverseRefMap.get(ref.getObjectId()); START if (set == null) { END set = Collections.singleton(ref); } else { set = new HashSet<Ref>(set); set.add(ref); } reverseRefMap.put(ref.getObjectId(), set); } } style nit: no braces around single line blocks

Target:
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); } }
Source:
private void handleException(final URIish uri, Exception e, String userMessage) { START if (uri != null) END 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); } 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$

Target:
private void handleException(final URIish uri, Exception e, String userMessage) { String uriString; if (uri != null) { operationResult.addOperationResult(uri, userMessage); uriString = uri.toString(); } else uriString = "retrieving URI failed"; //$NON-NLS-1$ String userMessageForUri = NLS.bind( CoreText.PushOperation_ExceptionOccurredDuringPushOnUriMessage, uriString, userMessage); Activator.logError(userMessageForUri, e); }
Source:
private LabelProvider getWorkbenchLabelProvider() { START if(workbenchLabelProvider == null) { END workbenchLabelProvider = new WorkbenchLabelProvider(); } return workbenchLabelProvider; } curly brackets can be removed

Target:
private LabelProvider getWorkbenchLabelProvider() { if (workbenchLabelProvider == null) workbenchLabelProvider = new WorkbenchLabelProvider(); return workbenchLabelProvider; }
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()) START refName = ref.getTarget().getName(); END } catch (IOException e) { Activator.logError("Error getting HEAD reference", e); //$NON-NLS-1$ } showReflogFor(repository, refName); } 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.

Target:
public void showReflogFor(Repository repository) { showReflogFor(repository, Constants.HEAD); }
Source:
private static int findGroupStart(String pattern, int currentIndex, Character invalidWildgetCharacter) { START if (invalidWildgetCharacter != null && invalidWildgetCharacter == '\\') { END return pattern.indexOf('[', currentIndex); } return findNotEscapedCharacterPosition(pattern, currentIndex, '['); } style-nit; no braces for simple single-statement constrcuts

Target:
private static int findGroupStart(String pattern, int currentIndex, Character invalidWildgetCharacter) { if (invalidWildgetCharacter != null && invalidWildgetCharacter == '\\') return pattern.indexOf('[', currentIndex); return findNotEscapedCharacterPosition(pattern, currentIndex, '['); }
Source:
static File searchPath(final String path, final String... lookFor) { START if (path == null) { END 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; } style nit: we don't use curly braces around single line blocks

Target:
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; }
Source:
private boolean onlyBranchesAreSelected(TreeSelection selection) { Iterator selIterator = selection.iterator(); START for (Object sel = selIterator.next(); selIterator.hasNext(); sel = selIterator END .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; } how about the following ? I find this easier to read : while (selIterator.hasNext()) { Object sel = selIterator.next(); ... }

Target:
private boolean onlyBranchesAreSelected(TreeSelection selection) { Iterator selIterator = selection.iterator(); while (selIterator.hasNext()) { Object 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; }
Source:
private static IDialogSettings getOrCreateSection(IDialogSettings settings, String sectionName) { IDialogSettings section = settings.getSection(sectionName); START if (section == null) { END section = settings.addNewSection(sectionName); } return section; } style nit: we don't use curly braces for single line blocks

Target:
private static IDialogSettings getOrCreateSection(IDialogSettings settings, String sectionName) { IDialogSettings section = settings.getSection(sectionName); if (section == null) section = settings.addNewSection(sectionName); return section; }
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(); START for (DfsPackFile pack : oc.getPackFiles()) { END pack.key.cachedSize.set(0); } } } Style-nit: Curly braces on this loop are not necessary.

Target:
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); } }
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() START .getParentFile(), null, monitor)) END for (File file : projects) ProjectUtil.createProject(repository, file, monitor); } 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"

Target:
public static void createProjects(final Repository repository, final IProgressMonitor monitor) throws CoreException { List<File> projects = new ArrayList<File>(); if (ProjectUtil.findProjectFiles(projects, repository.getWorkTree(), null, monitor)) for (File file : projects) ProjectUtil.createProject(repository, file, monitor); }
Source:
protected IStructuredSelection getSelection(ReflogView view) { ISelection pageSelection = view.getSelectionProvider().getSelection(); START if (pageSelection instanceof IStructuredSelection) { END return (IStructuredSelection) pageSelection; } else return new StructuredSelection(); } style-nit: remove curly brackets around single line block

Target:
protected IStructuredSelection getSelection(ReflogView view) { ISelection pageSelection = view.getSelectionProvider().getSelection(); if (pageSelection instanceof IStructuredSelection) return (IStructuredSelection) pageSelection; else return new StructuredSelection(); }
Source:
private boolean isChanged(List<String> ol, List<String> nl) { if (ol.size() != nl.size()) return true; START for (int i = 0; i < ol.size(); i++) { END if (!ol.get(i).equals(nl.get(i))) return true; } return false; } style nit: no curly braces around single line blocks

Target:
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; }
Source:
START boolean hasChanged() { END return configFile.lastModified() != lastModified; } 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.

Target:
synchronized boolean hasChanged() { return configFile.lastModified() != lastModified; }
Source:
public static PreReceiveHook newChain(List<? extends PreReceiveHook> hooks) { PreReceiveHook[] newHooks = new PreReceiveHook[hooks.size()]; int i = 0; for (PreReceiveHook hook : hooks) { START if (hook != PreReceiveHook.NULL) END newHooks[i++] = hook; } if (i == 0) return PreReceiveHook.NULL; else if (i == 1) return newHooks[0]; else return new PreReceiveHookChain(newHooks); } same bug

Target:
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, i); }
Source:
public void onPreAdvertiseRefs(UploadPack up) throws UploadPackMayNotContinueException { START for (PreUploadHook hook : hooks) { END hook.onPreAdvertiseRefs(up); } } curly braces

Target:
public void onPreAdvertiseRefs(UploadPack up) throws UploadPackMayNotContinueException { for (int i = 0; i < count; i++) hooks[i].onPreAdvertiseRefs(up); }
Source:
public void onBeginNegotiateRound(UploadPack up, Collection<? extends ObjectId> wants, int cntOffered) throws UploadPackMayNotContinueException { START for (PreUploadHook hook : hooks) { END hook.onBeginNegotiateRound(up, wants, cntOffered); } } curly braces

Target:
public void onBeginNegotiateRound(UploadPack up, Collection<? extends ObjectId> wants, int cntOffered) throws UploadPackMayNotContinueException { for (int i = 0; i < count; i++) hooks[i].onBeginNegotiateRound(up, wants, cntOffered); }
Source:
public void onEndNegotiateRound(UploadPack up, Collection<? extends ObjectId> wants, int cntCommon, int cntNotFound, boolean ready) throws UploadPackMayNotContinueException { START for (PreUploadHook hook : hooks) { END hook.onEndNegotiateRound(up, wants, cntCommon, cntNotFound, ready); } } curly braces

Target:
public void onEndNegotiateRound(UploadPack up, Collection<? extends ObjectId> wants, int cntCommon, int cntNotFound, boolean ready) throws UploadPackMayNotContinueException { for (int i = 0; i < count; i++) hooks[i].onEndNegotiateRound(up, wants, cntCommon, cntNotFound, ready); }
Source:
public void onSendPack(UploadPack up, Collection<? extends ObjectId> wants, Collection<? extends ObjectId> haves) throws UploadPackMayNotContinueException { START for (PreUploadHook hook : hooks) { END hook.onSendPack(up, wants, haves); } } curly braces

Target:
public void onSendPack(UploadPack up, Collection<? extends ObjectId> wants, Collection<? extends ObjectId> haves) throws UploadPackMayNotContinueException { for (int i = 0; i < count; i++) hooks[i].onSendPack(up, wants, haves); }
Source:
public static UploadPackLogger newChain(List<? extends UploadPackLogger> loggers) { UploadPackLogger[] newLoggers = new UploadPackLogger[loggers.size()]; int i = 0; for (UploadPackLogger logger : loggers) { START if (logger != UploadPackLogger.NULL) END newLoggers[i++] = logger; } if (i == 0) return UploadPackLogger.NULL; else if (i == 1) return newLoggers[0]; else return new UploadPackLoggerChain(newLoggers); } same bug

Target:
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, i); }
Source:
public void onPackStatistics(PackWriter.Statistics stats) { START for (UploadPackLogger logger : loggers) { END logger.onPackStatistics(stats); } } curly braces

Target:
public void onPackStatistics(PackWriter.Statistics stats) { for (int i = 0; i < count; i++) loggers[i].onPackStatistics(stats); }
Source:
private TeamException getTeamException(final Throwable throwable) { Throwable current = throwable; START while (current.getCause() != null) { END current = current.getCause(); } return new TeamException(current.getMessage(), current); } style nit: remove curly brackets

Target:
private TeamException getTeamException(final Throwable throwable) { Throwable current = throwable; while (current.getCause() != null) current = current.getCause(); return new TeamException(current.getMessage(), current); }
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); START if (existingUrl.equals(url)) { END return true; } } return false; } style-nit: we don't use curly brackets around single line blocks

Target:
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; }
Source:
public static List<CloneSourceProvider> getCloneSourceProvider() { List<CloneSourceProvider> cloneSourceProvider = new ArrayList<CloneSourceProvider>(); IExtensionRegistry registry = Platform.getExtensionRegistry(); IConfigurationElement[] config = registry .getConfigurationElementsFor(CLONE_SOURCE_PROVIDER_ID); START if (config.length > 0) { END addCloneSourceProvider(cloneSourceProvider, config, 0); } return cloneSourceProvider; } style nit: no curlies here

Target:
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; }
Source:
public IRepositoryServerProvider getRepositoryServerProvider() throws CoreException { if (repositoryServerProviderElement == null) return null; Object object = repositoryServerProviderElement .createExecutableExtension("class"); //$NON-NLS-1$ IRepositoryServerProvider provider = null; START if (object instanceof IRepositoryServerProvider) { END provider = (IRepositoryServerProvider) object; } return provider; } style nit: we don't use curly brackets around single line blocks

Target:
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; }
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 START && object instanceof IRepositorySearchResult) { END page = (WizardPage) object; } return page; } style nit: curly brackets

Target:
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; }
Source:
private void cacheParents(CloneSourceProvider repositoryImport, Collection<RepositoryServerInfo> repositoryServerInfos) { START for (RepositoryServerInfo info : repositoryServerInfos) { END parents.put(info, repositoryImport); } } nit: no braces around single line block

Target:
private void cacheParents(CloneSourceProvider repositoryImport, Collection<RepositoryServerInfo> repositoryServerInfos) { for (RepositoryServerInfo info : repositoryServerInfos) parents.put(info, repositoryImport); }
Source:
private void configureFetchSpec(CloneOperation op, GitRepositoryInfo gitRepositoryInfo, String remoteName) { START for (String fetchRefSpec : gitRepositoryInfo.getFetchRefSpecs()) { END op.addPostCloneTask(new ConfigureFetchAfterCloneTask(remoteName, fetchRefSpec)); } } style nit: no curly braces around single line blocks

Target:
private void configureFetchSpec(CloneOperation op, GitRepositoryInfo gitRepositoryInfo, String remoteName) { for (String fetchRefSpec : gitRepositoryInfo.getFetchRefSpecs()) op.addPostCloneTask(new ConfigureFetchAfterCloneTask(remoteName, fetchRefSpec)); }
Source:
public void dispose() { repoImage.dispose(); START for (Image image : images) { END image.dispose(); } } style nit: no braces around single line blocks

Target:
public void dispose() { repoImage.dispose(); for (Image image : images) image.dispose(); }
Source:
private SkipRevFilter(int skip) { START this.count = 0; END this.skip = skip; } Count doesn't need to be explicitly initialized since it is 0 by default

Target:
private SkipRevFilter(int skip) { this.skip = skip; }
Source:
protected void run() throws Exception { START if (list) { END list(); } else { throw new NotSupportedException( "only --list option is currently supported"); } } style nit: no braces around single line blocks

Target:
protected void run() throws Exception { if (list) list(); else throw new NotSupportedException( "only --list option is currently supported"); }
Source:
private boolean equalIdAndMode(ObjectId id1, FileMode mode1, ObjectId id2, FileMode mode2) { if (mode1.equals(mode2)) { if (id1 == null) return id2 == null; START return (id1.equals(id2)); END } return false; } right, looks much nicer. done!

Target:
private boolean equalIdAndMode(ObjectId id1, FileMode mode1, ObjectId id2, FileMode mode2) { if (!mode1.equals(mode2)) return false; return id1 != null ? id1.equals(id2) : id2 == null; }
Source:
public CleanCommand setCleanDirectories(boolean dirs) { START this.directories = dirs; END return this; } this keyword not needed

Target:
public CleanCommand setCleanDirectories(boolean dirs) { directories = dirs; return this; }
Source:
public static List<ReceiveCommand> filter(List<ReceiveCommand> commands, final Result want) { START final List<ReceiveCommand> r = new ArrayList<ReceiveCommand>(commands END .size()); for (final ReceiveCommand cmd : commands) { if (cmd.getResult() == want) r.add(cmd); } return r; } If you drop the final qualifier on "r" will this all fit on one line?

Target:
public static List<ReceiveCommand> filter(List<ReceiveCommand> commands, final Result want) { List<ReceiveCommand> r = new ArrayList<ReceiveCommand>(commands.size()); for (final ReceiveCommand cmd : commands) { if (cmd.getResult() == want) r.add(cmd); } return r; }
Source:
public void addTags(String remotePath, CVSTag[] tags) { if (tags.length == 0) { START return; END } addDateTags(tags); addVersionAndBranchTags(remotePath, tags); } Yes, even if we add empty set of tags the entry is treated as accessed. I don't think it's correct.

Target:
public void addTags(String remotePath, CVSTag[] tags) { addDateTags(tags); addVersionAndBranchTags(remotePath, tags); }
Source:
private void removeTagsFromChildrenCacheEntries(TagCacheEntry entry, CVSTag[] tags) { for (int i = 0; i < tags.length; i++) { removeTagFromChildrenCacheEntries(entry, tags[i]); } entry.getTags().removeAll(Arrays.asList(tags)); START if (entry.getTags().size() == 0 && entry.children.size() == 0) { END // remove this entry when the last tags where removed // keep the entry if there are any children that have tags removeTagCacheEntry(entry); } } Use #isEmpty.

Target:
private void removeTagsFromChildrenCacheEntries(TagCacheEntry entry, CVSTag[] tags) { for (int i = 0; i < tags.length; i++) { removeTagFromChildrenCacheEntries(entry, tags[i]); } entry.getTags().removeAll(Arrays.asList(tags)); if (entry.isEmpty()) { // remove this entry when the last tags where removed // keep the entry if there are any children that have tags removeTagCacheEntry(entry); } }
Source:
private void removeTagCacheEntry(TagCacheEntry entry) { if (entry.parent == null) { // We cannot remove root tag cache entry return; } Map newParentChildren = new HashMap(); newParentChildren.putAll(entry.parent.children); newParentChildren.remove(entry.path.lastSegment()); entry.parent.children = newParentChildren; START if (entry.parent.getTags().isEmpty() && entry.children.isEmpty()) { END // remove parents if they no longer carry any value removeTagCacheEntry(entry.parent); } } Shouldn't the second condition be "entry.parent.children.isEmpty()"?

Target:
private void removeTagCacheEntry(TagCacheEntry entry) { if (entry.parent == null) { // We cannot remove root tag cache entry return; } Map newParentChildren = new HashMap(); newParentChildren.putAll(entry.parent.children); newParentChildren.remove(entry.path.lastSegment()); entry.parent.children = newParentChildren; if (entry.parent.isEmpty()) { // remove parents if they no longer carry any value removeTagCacheEntry(entry.parent); } }
Source:
private void removeTagFromChildrenCacheEntries(TagCacheEntry entry, CVSTag tag) { Iterator childrenIterator = entry.getChildrenIterator(); while (childrenIterator.hasNext()) { TagCacheEntry child = (TagCacheEntry) childrenIterator.next(); removeTagFromChildrenCacheEntries(child, tag); child.getTags().remove(tag); START if (child.getTags().size() == 0 && child.children.size() == 0) { END // remove this entry when the last tag was removed // keep the entry if there are any children that have tags removeTagCacheEntry(child); } } } Use #isEmpty()

Target:
private void removeTagFromChildrenCacheEntries(TagCacheEntry entry, CVSTag tag) { Iterator childrenIterator = entry.getChildrenIterator(); while (childrenIterator.hasNext()) { TagCacheEntry child = (TagCacheEntry) childrenIterator.next(); removeTagFromChildrenCacheEntries(child, tag); child.getTags().remove(tag); if (child.isEmpty()) { // remove this entry when the last tag was removed // keep the entry if there are any children that have tags removeTagCacheEntry(child); } } }
Source:
public void execute(IProgressMonitor monitor) throws CVSException, InterruptedException { super.execute(monitor); if (tempFile.length() == 0) { tempFile.delete(); reportEmptyDiff(); return; } if (this.isMultiPatch && (!patchHasContents && !patchHasNewFiles && !emptyDiffReported)){ START tempFile.delete(); END reportEmptyDiff(); return; } copyFile(); } Shouldn't the temp file be deleted anyway?

Target:
public void execute(IProgressMonitor monitor) throws CVSException, InterruptedException { super.execute(monitor); if (tempFile.length() == 0) { tempFile.delete(); reportEmptyDiff(); return; } if (this.isMultiPatch && (!patchHasContents && !patchHasNewFiles)){ tempFile.delete(); reportEmptyDiff(); return; } copyFile(); }
Source:
public BatchRefUpdate addCommand(ReceiveCommand... cmd) { START commands.addAll(Arrays.asList(cmd)); END classifiedUpdates = false; return this; } addCommand(Arrays.asList(cmd))?

Target:
public BatchRefUpdate addCommand(ReceiveCommand... cmd) { return addCommand(Arrays.asList(cmd)); }
Source:
byte[] getCachedBytes(RevObject obj, ObjectLoader ldr) throws LargeObjectException, MissingObjectException, IOException { try { START return ldr.getCachedBytes(streamFileThreshold); END } catch (LargeObjectException tooBig) { tooBig.setObjectId(obj); throw tooBig; } } I think you can just drop this parameter, and the MiB constant and that is the entire commit.

Target:
byte[] getCachedBytes(RevObject obj, ObjectLoader ldr) throws LargeObjectException, MissingObjectException, IOException { try { return ldr.getCachedBytes(); } catch (LargeObjectException tooBig) { tooBig.setObjectId(obj); throw tooBig; } }
Source:
private String[] addFilePathToArgs(String actualFilePath, String[] configuredArgs) { int argCount = configuredArgs.length; String[] allArgs = new String[argCount + 1]; // Arrays.copyOf leaves empty cells at the end. We need an empty cell at the beginning of // the array. System.arraycopy(configuredArgs, 0, allArgs, 1, argCount); // We add the path of the file to process as the first argument to pass. START allArgs[0] = actualFilePath; END return allArgs; } Move after line 51.

Target:
private String[] addFilePathToArgs(String actualFilePath, String[] configuredArgs) { int argCount = configuredArgs.length; String[] allArgs = new String[argCount + 1]; allArgs[0] = actualFilePath; // Copy arguments System.arraycopy(configuredArgs, 0, allArgs, 1, argCount); return allArgs; }
Source:
private void readCheckerEnablementVerifier() { IExtensionPoint ep = getExtensionPoint(CHECKER_ENABLEMENT_EXTENSION_POINT_NAME); for (IConfigurationElement ce : ep.getConfigurationElements()) { try { Object o = ce.createExecutableExtension(CLASS_ATTR); START checkerEnablementVerifier = (ICheckerEnablementVerifier) o; END } catch (CoreException e) { CodanCorePlugin.log(e); } } } inline o

Target:
private void readCheckerEnablementVerifier() { IExtensionPoint ep = getExtensionPoint(CHECKER_ENABLEMENT_EXTENSION_POINT_NAME); for (IConfigurationElement ce : ep.getConfigurationElements()) { try { checkerEnablementVerifier = (ICheckerEnablementVerifier) ce.createExecutableExtension(CLASS_ATTR); } catch (CoreException e) { CodanCorePlugin.log(e); } } }
Source:
public static int getValue(String text) { START if (text == null || text.isEmpty() || text.equals("build")) { //$NON-NLS-1$ END return BUILD; } if (text.equals("codan")) { //$NON-NLS-1$ return CODAN; } throw new IllegalArgumentException("Unknown context value: " + text); //$NON-NLS-1$ } Please remove isEmpty() check. Null check should be removed too, but the comparisons should be made null-proof.

Target:
public static int getValue(String text) { if ("build".equals(text)) { //$NON-NLS-1$ return BUILD; } if ("codan".equals(text)) { //$NON-NLS-1$ return CODAN; } throw new IllegalArgumentException("Unknown context value: " + text); //$NON-NLS-1$ }
Source:
public void removeChildrenFromLRU() { if (children != null) { for (ExpressionInfo child : children) { removeChildFromLRU(child); } children = null; numChildrenHint = 0; } if (fakeChildren != null) { for (ExpressionInfo fakeChild : fakeChildren) { if (fakeChild == null) { break; } removeChildFromLRU(fakeChild); } clearFakeChildren(); START } END } fakeChildren removal can be cleaned up when using a Vector

Target:
public void removeChildrenFromLRU() { if (children != null) { for (ExpressionInfo child : children) { removeChildFromLRU(child); } children = null; numChildrenHint = 0; } for (ExpressionInfo fakeChild : fakeChildren) { removeChildFromLRU(fakeChild); } fakeChildren.clear(); }
Source:
public static Test suite() { TestSuite suite = new TestSuite(RegressionTests.class.getName()); // Test that common builder does the correct amount of work. suite.addTestSuite(Bug_303953.class); suite.addTestSuite(Bug_377295.class); START END return suite; } I don't think it is useful for us to organize the tests using "regression" category. I'd rather see them in the regular test suite.

Target:
public static Test suite() { TestSuite suite = new TestSuite(RegressionTests.class.getName()); // Test that common builder does the correct amount of work. suite.addTestSuite(Bug_303953.class); return suite; }
Source:
public URI getWorkingDirectoryURI() { START if (!fDirectoryStack.isEmpty()) END return fDirectoryStack.lastElement(); // Fall back to the Project Location / Build directory return fBaseDirectoryURI; } Please bring the braces back.

Target:
public URI getWorkingDirectoryURI() { if (!fDirectoryStack.isEmpty()) { return fDirectoryStack.lastElement(); } // Fall back to the Project Location / Build directory return fBaseDirectoryURI; }
Source:
public void pushDirectory(IPath dir) { if (dir != null) { URI uri; URI workingDirectoryURI = getWorkingDirectoryURI(); START if (!dir.isAbsolute()) END uri = URIUtil.append(workingDirectoryURI, dir.toString()); else { uri = toURI(dir); if (uri == null) // Shouldn't happen; error logged return; } pushDirectoryURI(uri); } } Please bring the braces back.

Target:
public void pushDirectory(IPath dir) { if (dir != null) { URI uri; URI workingDirectoryURI = getWorkingDirectoryURI(); if (!dir.isAbsolute()) { uri = URIUtil.append(workingDirectoryURI, dir.toString()); } else { uri = toURI(dir); if (uri == null) { return; } } pushDirectoryURI(uri); } }
Source:
public void pushDirectoryURI(URI dir) { if (dir != null) { START if (dir.isAbsolute()) END fDirectoryStack.addElement(dir); else fDirectoryStack.addElement(URIUtil.makeAbsolute(dir, getWorkingDirectoryURI())); } } Please bring the braces back.

Target:
public void pushDirectoryURI(URI dir) { if (dir != null) { if (dir.isAbsolute()) { fDirectoryStack.addElement(dir); } else { fDirectoryStack.addElement(URIUtil.makeAbsolute(dir, getWorkingDirectoryURI())); } } }
Source:
protected IFile findFileInWorkspace(IPath path) { URI uri; if (!path.isAbsolute()) { URI workingDirectoryURI = getWorkingDirectoryURI(); uri = EFSExtensionManager.getDefault().append(workingDirectoryURI, path.toString()); } else { uri = toURI(path); START if (uri == null) // Shouldn't happen; error logged END return null; } return findFileInWorkspace(uri); } Please bring the braces back.

Target:
protected IFile findFileInWorkspace(IPath path) { URI uri; if (!path.isAbsolute()) { URI workingDirectoryURI = getWorkingDirectoryURI(); uri = EFSExtensionManager.getDefault().append(workingDirectoryURI, path.toString()); } else { uri = toURI(path); if (uri == null) { return null; } } return findFileInWorkspace(uri); }
Source:
protected IFile findFileInWorkspace(URI uri) { START if (!uri.isAbsolute()) END uri = URIUtil.makeAbsolute(uri, getWorkingDirectoryURI()); IFile f = ResourceLookup.selectFileForLocationURI(uri, fProject); if (f != null && f.isAccessible()) return f; return null; } Please bring the braces back.

Target:
protected IFile findFileInWorkspace(URI uri) { if (!uri.isAbsolute()) { uri = URIUtil.makeAbsolute(uri, getWorkingDirectoryURI()); } IFile f = ResourceLookup.selectFileForLocationURI(uri, fProject); if (f != null && f.isAccessible()) { return f; } return null; }
Source:
public void addProblemMarker(ProblemMarkerInfo problemMarkerInfo){ fErrors.add(problemMarkerInfo); fMarkerGenerator.addMarker(problemMarkerInfo); START if (problemMarkerInfo.severity == IMarkerGenerator.SEVERITY_ERROR_RESOURCE) END hasErrors = true; } Please bring the braces back.

Target:
public void addProblemMarker(ProblemMarkerInfo problemMarkerInfo){ fErrors.add(problemMarkerInfo); fMarkerGenerator.addMarker(problemMarkerInfo); if (problemMarkerInfo.severity == IMarkerGenerator.SEVERITY_ERROR_RESOURCE) { hasErrors = true; } }
Source:
public void flush() throws IOException { START if (outputStream != null) END outputStream.flush(); } Please bring the braces back.

Target:
public void flush() throws IOException { if (outputStream != null) { outputStream.flush(); } }
Source:
private URI toURI(IPath path) { // try { URI baseURI = getWorkingDirectoryURI(); String uriString = path.toString(); // On Windows "C:/folder/" -> "/C:/folder/" START if (path.isAbsolute() && uriString.charAt(0) != IPath.SEPARATOR) END uriString = IPath.SEPARATOR + uriString; return EFSExtensionManager.getDefault().createNewURIFromPath(baseURI, uriString); } Please bring the braces back.

Target:
private URI toURI(IPath path) { // try { URI baseURI = getWorkingDirectoryURI(); String uriString = path.toString(); // On Windows "C:/folder/" -> "/C:/folder/" if (path.isAbsolute() && uriString.charAt(0) != IPath.SEPARATOR) { uriString = IPath.SEPARATOR + uriString; } return EFSExtensionManager.getDefault().createNewURIFromPath(baseURI, uriString); }