/** {@inheritDoc} */
  public boolean accept(Object element) {
    boolean passes = true;

    if (element instanceof IFile) {

      IFile file = (IFile) element;
      IProject project = file.getProject();

      if (RepositoryProvider.isShared(project)) {

        RepositoryProvider provider = RepositoryProvider.getProvider(project);

        if (provider != null) {

          Subscriber subscriber = provider.getSubscriber();

          if (subscriber != null) {

            try {
              SyncInfo synchInfo = subscriber.getSyncInfo(file);

              if (synchInfo != null) {
                int kind = synchInfo.getKind();
                passes = (SyncInfo.getDirection(kind) & SyncInfo.OUTGOING) == SyncInfo.OUTGOING;
              }
            } catch (TeamException e) {
              CheckstyleLog.log(e);
            }
          }
        }
      }
    }
    return passes;
  }
 public IFileHistory getFileHistoryFor(IResource resource, int flags, IProgressMonitor monitor) {
   RepositoryProvider provider = RepositoryProvider.getProvider(((IFile) resource).getProject());
   if (provider instanceof MercurialTeamProvider) {
     MercurialHistory history = new MercurialHistory(resource);
     try {
       history.load(monitor, Integer.MAX_VALUE);
     } catch (CoreException e) {
       MercurialEclipsePlugin.logError(e);
     }
     return history;
   }
   return null;
 }
 /** Split the resources into sets associated with their project/provider */
 protected Map getRepositoryProviderMapping() {
   HashMap result = new HashMap();
   IResource[] resources = getSelectedResources();
   for (IResource element : resources) {
     RepositoryProvider provider = RepositoryProvider.getProvider(element.getProject());
     List list = (List) result.get(provider);
     if (list == null) {
       list = new ArrayList();
       result.put(provider, list);
     }
     list.add(new SimpleResourceMapping(element));
   }
   return result;
 }
 public boolean isEnabled() {
   return resource != null
       && RepositoryProvider.getProvider(resource.getProject(), GitProvider.ID) != null;
 }
Exemple #5
0
 private void compare(CommitItem commitItem) {
   IFile file = findFile(commitItem.path);
   if (file == null || RepositoryProvider.getProvider(file.getProject()) == null)
     CompareUtils.compareHeadWithWorkingTree(repository, commitItem.path);
   else CompareUtils.compareHeadWithWorkspace(repository, file);
 }
  private void prepareChangeLog(IProgressMonitor monitor) {

    Object element = selected.getFirstElement();

    IResource resource = null;
    Vector<PatchFile> newList = new Vector<PatchFile>();
    Vector<PatchFile> removeList = new Vector<PatchFile>();
    Vector<PatchFile> changeList = new Vector<PatchFile>();
    int totalChanges = 0;

    if (element instanceof IResource) {
      resource = (IResource) element;
    } else if (element instanceof ISynchronizeModelElement) {
      ISynchronizeModelElement sme = (ISynchronizeModelElement) element;
      resource = sme.getResource();
    } else if (element instanceof IAdaptable) {
      resource = (IResource) ((IAdaptable) element).getAdapter(IResource.class);
    }

    if (resource == null) return;

    IProject project = resource.getProject();
    // Get the repository provider so we can support multiple types of
    // code repositories without knowing exactly which (e.g. CVS, SVN, etc..).
    RepositoryProvider r = RepositoryProvider.getProvider(project);
    if (r == null) return;
    SyncInfoSet set = new SyncInfoSet();
    Subscriber s = r.getSubscriber();
    if (s == null) return;
    if (element instanceof ISynchronizeModelElement) {
      // We can extract the ChangeLog list from the synchronize view which
      // allows us to skip items removed from the view
      ISynchronizeModelElement d = (ISynchronizeModelElement) element;
      while (d.getParent() != null) d = (ISynchronizeModelElement) d.getParent();
      extractSynchronizeModelInfo(d, new Path(""), newList, removeList, changeList);
      totalChanges = newList.size() + removeList.size() + changeList.size();
    } else {
      // We can then get a list of all out-of-sync resources.
      s.collectOutOfSync(new IResource[] {project}, IResource.DEPTH_INFINITE, set, monitor);
      SyncInfo[] infos = set.getSyncInfos();
      totalChanges = infos.length;
      // Iterate through the list of changed resources and categorize them into
      // New, Removed, and Changed lists.
      for (SyncInfo info : infos) {
        int kind = SyncInfo.getChange(info.getKind());
        PatchFile p = new PatchFile(info.getLocal());

        // Check the type of entry and sort into lists.  Do not add an entry
        // for ChangeLog files.
        if (!(p.getPath().lastSegment().equals("ChangeLog"))) { // $NON-NLS-1$
          if (kind == SyncInfo.ADDITION) {
            p.setNewfile(true);
            newList.add(p);
          } else if (kind == SyncInfo.DELETION) {
            p.setRemovedFile(true);
            removeList.add(p);
          } else if (kind == SyncInfo.CHANGE) {
            if (info.getLocal().getType() == IResource.FILE) {
              changeList.add(p);
            }
          }
        } else {
          this.changeLogModified = true;
        }
      }
    }

    if (totalChanges == 0) return; // nothing to parse

    PatchFile[] patchFileInfoList = new PatchFile[totalChanges];

    // Group like changes together and sort them by path name.
    // We want removed files, then new files, then changed files.
    // To get this, we put them in the array in reverse order.
    int index = 0;
    if (changeList.size() > 0) {
      // Get the repository provider so we can support multiple types of
      // code repositories without knowing exactly which (e.g. CVS, SVN, etc..).
      Collections.sort(changeList, new PatchFileComparator());
      int size = changeList.size();
      for (int i = 0; i < size; ++i) {
        PatchFile p = changeList.get(i);
        getChangedLines(s, p, monitor);
        patchFileInfoList[index + (size - i - 1)] = p;
      }
      index += size;
    }

    if (newList.size() > 0) {
      Collections.sort(newList, new PatchFileComparator());
      int size = newList.size();
      for (int i = 0; i < size; ++i) patchFileInfoList[index + (size - i - 1)] = newList.get(i);
      index += size;
    }

    if (removeList.size() > 0) {
      Collections.sort(removeList, new PatchFileComparator());
      int size = removeList.size();
      for (int i = 0; i < size; ++i) patchFileInfoList[index + (size - i - 1)] = removeList.get(i);
    }

    // now, find out modified functions/classes.
    // try to use the the extension point. so it can be extended easily
    // for all files in patch file info list, get function guesses of each
    // file.
    monitor.subTask(Messages.getString("ChangeLog.WritingMessage")); // $NON-NLS-1$
    int unitwork = 250 / patchFileInfoList.length;
    for (PatchFile pf : patchFileInfoList) {
      // for each file
      if (pf != null) { // any ChangeLog changes will have null entries for them
        String[] funcGuessList = guessFunctionNames(pf);
        outputMultipleEntryChangeLog(pf, funcGuessList);
      }
      monitor.worked(unitwork);
    }
  }
  /**
   * Process the EGit history associated with a given project.
   *
   * @param selectedProject selected project, presumably an object contribution selection
   * @throws CoreException
   * @throws IOException
   */
  public void processHistory(IProject selectedProject, IProgressMonitor monitor)
      throws CoreException, IOException {

    // find the repository mapping for the project
    // if none found, return
    RepositoryMapping repositoryMapping = RepositoryMapping.getMapping((IResource) selectedProject);
    if (repositoryMapping == null) {
      CertWareLog.logWarning(
          String.format("%s %s", "Missing repository for project", selectedProject.getName()));
      return;
    }

    // build the commit history model, load it from the tree walk
    final CommitHistory commitHistory = ScoFactory.eINSTANCE.createCommitHistory();
    Repository repo = repositoryMapping.getRepository();
    RevWalk revWalk = new RevWalk(repo);
    ObjectId headObject = repo.resolve("HEAD");
    revWalk.markStart(revWalk.parseCommit(headObject));

    final Set<String> repositoryPaths =
        Collections.singleton(repositoryMapping.getRepoRelativePath(selectedProject));
    revWalk.setTreeFilter(PathFilterGroup.createFromStrings(repositoryPaths));

    for (RevCommit commit : revWalk) {
      String commitName = commit.getName();
      ArtifactCommit artifactCommit = ScoFactory.eINSTANCE.createArtifactCommit();
      artifactCommit.setCommitIdentifier(commitName);
      commitHistory.getCommitRecord().add(artifactCommit);
    }

    revWalk.dispose();

    // use the Git provider to find the file history, then converge into the model
    GitProvider provider = (GitProvider) RepositoryProvider.getProvider(selectedProject);
    IFileHistoryProvider fileHistoryProvider = provider.getFileHistoryProvider();
    IResource[] projectMembers = selectedProject.members();

    monitor.beginTask("Processing project resources", projectMembers.length);
    for (IResource resource : projectMembers) {
      processResource(resource, fileHistoryProvider, commitHistory, monitor);
      monitor.worked(1);
      if (monitor.isCanceled()) {
        return;
      }
    }

    // model complete with commit history and associated file sizes
    // write the resulting model to an SCO file
    // expecting preference to have no extension, so add it if necessary
    IPreferenceStore store = Activator.getDefault().getPreferenceStore();
    String fileName = store.getString(PreferenceConstants.P_FILENAME_SCO);
    if (fileName.endsWith(ICertWareConstants.SCO_EXTENSION) == false) {
      fileName = fileName + '.' + ICertWareConstants.SCO_EXTENSION;
    }

    // fully specify the path to the new file given the container project
    final String modelFile =
        selectedProject.getFullPath().toPortableString() + IPath.SEPARATOR + fileName;

    // create the resource in a workspace modify operation
    WorkspaceModifyOperation operation =
        new WorkspaceModifyOperation() {
          @Override
          protected void execute(IProgressMonitor progressMonitor) {
            try {
              // create a resource set and resource for a new file
              ResourceSet resourceSet = new ResourceSetImpl();
              URI fileURI = URI.createPlatformResourceURI(modelFile, true);
              Resource resource = resourceSet.createResource(fileURI);
              resource.getContents().add(commitHistory);

              // save the contents of the resource to the file system
              Map<Object, Object> options = new HashMap<Object, Object>();
              options.put(XMLResource.OPTION_ENCODING, FILE_ENCODING);
              resource.save(options);
            } catch (Exception e) {
              CertWareLog.logError(String.format("%s %s", "Saving SCO file", modelFile), e);
            }
          }
        };

    // modify the workspace
    try {
      operation.run(monitor);
    } catch (Exception e) {
      CertWareLog.logError(
          String.format("%s %s", "Modifying workspace for", selectedProject.getName()), e);
    }

    monitor.done();
  }
 /**
  * Returns <code>true</code> if the given project is associated to the egit team provider. Returns
  * <code>false</code> otherwise.
  *
  * @param project the project to check
  * @return <code>true</code> if the project is associated with the git team provider.
  */
 public static boolean isSharedWithGit(IProject project) {
   RepositoryProvider provider = RepositoryProvider.getProvider(project);
   return provider != null && EGIT_TEAM_PROVIDER_ID.equals(provider.getID());
 }
 /**
  * Returns <code>true</code> if the given project is associated to any team provider (git, svn,
  * cvs, etc.). Returns <code>false</code> otherwise.
  *
  * @param project the project to check
  * @return <code>true</code> if the project is associated with any team provider.
  */
 public static boolean isShared(IProject project) {
   return RepositoryProvider.getProvider(project) != null;
 }
  /**
   * Returns a team project set for <code>projects</code>.
   *
   * @param projects the projects to include
   * @return an XML document
   * @throws CoreException indicates that the team project set could not be created
   */
  public static ByteArrayOutputStream exportProjectSet(List<IProject> projects)
      throws CoreException {
    Map<String, Set<IProject>> map = new HashMap<String, Set<IProject>>();
    for (IProject project : projects) {
      RepositoryProvider provider = RepositoryProvider.getProvider(project);
      if (provider != null) {
        String id = provider.getID();
        Set<IProject> list = map.get(id);
        if (list == null) {
          list =
              new TreeSet<IProject>(
                  new Comparator<IProject>() {
                    public int compare(IProject o1, IProject o2) {
                      return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase());
                    }
                  });
          map.put(id, list);
        }
        list.add(project);
      }
    }

    BufferedWriter writer = null;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    try {
      writer = new BufferedWriter(new OutputStreamWriter(output, "UTF-8")); // $NON-NLS-1$

      XmlMemento xmlMemento = getXMLMementoRoot();
      Iterator<String> it = map.keySet().iterator();
      while (it.hasNext()) {
        String id = it.next();
        XmlMemento memento = xmlMemento.createChild("provider"); // $NON-NLS-1$
        memento.putString("id", id); // $NON-NLS-1$
        Set<IProject> list = map.get(id);
        IProject[] projectArray = list.toArray(new IProject[list.size()]);
        RepositoryProviderType providerType = RepositoryProviderType.getProviderType(id);
        ProjectSetCapability serializer = providerType.getProjectSetCapability();
        ProjectSetCapability.ensureBackwardsCompatible(providerType, serializer);
        if (serializer != null) {
          String[] references = serializer.asReference(projectArray, null, null);
          for (String reference : references) {
            XmlMemento proj = memento.createChild("project"); // $NON-NLS-1$
            proj.putString("reference", reference); // $NON-NLS-1$
          }
        }
      }

      xmlMemento.save(writer);
      return output;
    } catch (Exception e) {
      throw new CoreException(
          new Status(
              IStatus.ERROR,
              ScmInternal.ID_PLUGIN,
              "Unexpected error exporting project sets.",
              e)); //$NON-NLS-1$
    } finally {
      if (writer != null) {
        try {
          writer.close();
        } catch (IOException e) {
          // ignore
        }
      }
    }
  }
  /**
   * The action is enabled for the appropriate resources. This method checks that:
   *
   * <ol>
   *   <li>there is no overlap between a selected file and folder (overlapping folders is allowed
   *       because of logical vs. physical mapping problem in views)
   *   <li>the state of the resources match the conditions provided by:
   *       <ul>
   *         <li>isEnabledForIgnoredResources()
   *         <li>isEnabledForManagedResources()
   *         <li>isEnabledForUnManagedResources() (i.e. not ignored and not managed)
   *       </ul>
   * </ol>
   *
   * @see TeamAction#isEnabled()
   */
  public boolean isEnabled() {

    // allow the super to decide enablement. if the super doesn't know it will return false.
    boolean enabled = super.isEnabled();
    if (enabled) return true;

    // invoke the inherited method so that overlaps are maintained
    IResource[] resources = getSelectedResourcesWithOverlap();

    // disable if no resources are selected
    if (resources.length == 0) return false;

    // disable properly for single resource enablement
    if (!isEnabledForMultipleResources() && resources.length != 1) return false;

    // validate enabled for each resource in the selection
    List folderPaths = new ArrayList();
    List filePaths = new ArrayList();
    for (int i = 0; i < resources.length; i++) {
      IResource resource = resources[i];

      // only enable for accessible resources
      if (resource.getType() == IResource.PROJECT) {
        if (!resource.isAccessible()) return false;
      }

      // no CVS actions are enabled if the selection contains a linked resource
      if (CVSWorkspaceRoot.isLinkedResource(resource)) return false;

      // only enable for resources in a project shared with CVS
      if (RepositoryProvider.getProvider(resource.getProject(), CVSProviderPlugin.getTypeId())
          == null) {
        return false;
      }

      // collect files and folders separately to check for overlap later
      IPath resourceFullPath = resource.getFullPath();
      if (resource.getType() == IResource.FILE) {
        filePaths.add(resourceFullPath);
      } else {
        folderPaths.add(resourceFullPath);
      }

      // ensure that resource management state matches what the action requires
      ICVSResource cvsResource = getCVSResourceFor(resource);
      try {
        if (!isEnabledForCVSResource(cvsResource)) {
          return false;
        }
      } catch (CVSException e) {
        if (!isEnabledForException(e)) return false;
      }
    }
    // Ensure that there is no overlap between files and folders
    // NOTE: folder overlap must be allowed because of logical vs. physical
    if (!folderPaths.isEmpty()) {
      for (Iterator fileIter = filePaths.iterator(); fileIter.hasNext(); ) {
        IPath resourcePath = (IPath) fileIter.next();
        for (Iterator it = folderPaths.iterator(); it.hasNext(); ) {
          IPath folderPath = (IPath) it.next();
          if (folderPath.isPrefixOf(resourcePath)) {
            return false;
          }
        }
      }
    }
    return true;
  }