/** {@inheritDoc} */
 @Override
 public void commit(IProgressMonitor monitor) throws CoreException {
   if (isDirty()) {
     if (isConnected()) {
       super.commit(monitor);
     } else {
       FileOutputStream out = null;
       File file = path.toFile();
       try {
         if (!file.exists()) FileUtils.createNewFile(file);
         out = new FileOutputStream(file);
         out.write(getContent());
         fDirty = false;
       } catch (IOException e) {
         throw new CoreException(
             new Status(
                 IStatus.ERROR,
                 Activator.getPluginId(),
                 UIText.LocalNonWorkspaceTypedElement_errorWritingContents,
                 e));
       } finally {
         fireContentChanged();
         RepositoryMapping mapping = RepositoryMapping.getMapping(path);
         if (mapping != null) mapping.getRepository().fireEvent(new IndexChangedEvent());
         if (out != null)
           try {
             out.close();
           } catch (IOException ex) {
             // ignore
           }
       }
     }
   }
 }
Ejemplo n.º 2
0
 private void assertProjectIsShared(String projectName, boolean shouldBeShared) {
   IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
   RepositoryMapping mapping = RepositoryMapping.getMapping(project);
   if (shouldBeShared) {
     assertNotNull(mapping);
     assertNotNull(mapping.getRepository());
   } else assertNull(mapping);
 }
Ejemplo n.º 3
0
  /**
   * Gets the repository that is configured to the given project.
   *
   * @param project the project
   * @return the repository
   */
  public static Repository getRepository(IProject project) {
    Assert.isLegal(project != null, "Could not get repository. No project provided");

    RepositoryMapping repositoryMapping = RepositoryMapping.getMapping(project);
    if (repositoryMapping == null) {
      return null;
    }
    return repositoryMapping.getRepository();
  }
Ejemplo n.º 4
0
 private IProject[] getProjectsOfRepositories() {
   Set<IProject> ret = new HashSet<IProject>();
   final IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
   for (IProject project : projects) {
     RepositoryMapping mapping = RepositoryMapping.getMapping(project);
     if (mapping != null && mapping.getRepository() == repo) ret.add(project);
   }
   return ret.toArray(new IProject[ret.size()]);
 }
 private List<IPath> getProjectPaths() {
   if (projectPaths == null) {
     projectPaths = new ArrayList<IPath>();
     for (IProject project : ResourcesPlugin.getWorkspace().getRoot().getProjects()) {
       RepositoryMapping mapping = RepositoryMapping.getMapping(project);
       if (mapping != null && mapping.getRepository().equals(repository)) {
         projectPaths.add(project.getLocation());
       }
     }
   }
   return projectPaths;
 }
Ejemplo n.º 6
0
    @Override
    public IStatus runInWorkspace(IProgressMonitor monitor) {
      Set<Repository> repos;
      synchronized (repositoriesChanged) {
        if (repositoriesChanged.isEmpty()) {
          return Status.OK_STATUS;
        }
        repos = new LinkedHashSet<>(repositoriesChanged);
        repositoriesChanged.clear();
      }
      IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
      Set<IProject> toRefresh = new LinkedHashSet<>();
      for (IProject p : projects) {
        if (!p.isAccessible()) {
          continue;
        }
        RepositoryMapping mapping = RepositoryMapping.getMapping(p);
        if (mapping != null && repos.contains(mapping.getRepository())) {
          toRefresh.add(p);
        }
      }
      monitor.beginTask(UIText.Activator_refreshingProjects, toRefresh.size());

      for (IProject p : toRefresh) {
        if (monitor.isCanceled()) {
          return Status.CANCEL_STATUS;
        }
        ISchedulingRule rule = p.getWorkspace().getRuleFactory().refreshRule(p);
        try {
          getJobManager().beginRule(rule, monitor);
          // handle missing projects after branch switch
          if (p.isAccessible()) {
            p.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 1));
          }
        } catch (CoreException e) {
          handleError(UIText.Activator_refreshFailed, e, false);
          return new Status(IStatus.ERROR, getPluginId(), e.getMessage());
        } finally {
          getJobManager().endRule(rule);
        }
      }
      if (!monitor.isCanceled()) {
        // re-schedule if we got some changes in the meantime
        synchronized (repositoriesChanged) {
          if (!repositoriesChanged.isEmpty()) {
            schedule(100);
          }
        }
      }
      monitor.done();
      return Status.OK_STATUS;
    }
Ejemplo n.º 7
0
  private KidWalk buildWalk() {
    final RepositoryMapping rm = RepositoryMapping.getMapping(resource);
    if (rm == null) {
      Activator.logError(
          NLS.bind(CoreText.GitFileHistory_gitNotAttached, resource.getProject().getName()), null);
      return null;
    }

    final KidWalk w = new KidWalk(rm.getRepository());
    gitPath = rm.getRepoRelativePath(resource);
    w.setTreeFilter(
        AndTreeFilter.create(
            PathFilterGroup.createFromStrings(Collections.singleton(gitPath)),
            TreeFilter.ANY_DIFF));
    return w;
  }
Ejemplo n.º 8
0
 public Object execute(ExecutionEvent event) throws ExecutionException {
   boolean compareMode =
       Boolean.TRUE.toString().equals(event.getParameter(HistoryViewCommands.COMPARE_MODE_PARAM));
   IStructuredSelection selection = getSelection(getPage());
   if (selection.size() < 1) return null;
   Object input = getPage().getInputInternal().getSingleFile();
   if (input == null) return null;
   IWorkbenchPage workBenchPage =
       HandlerUtil.getActiveWorkbenchWindowChecked(event).getActivePage();
   boolean errorOccurred = false;
   List<ObjectId> ids = new ArrayList<ObjectId>();
   String gitPath = null;
   if (input instanceof IFile) {
     IFile resource = (IFile) input;
     final RepositoryMapping map = RepositoryMapping.getMapping(resource);
     gitPath = map.getRepoRelativePath(resource);
     Iterator<?> it = selection.iterator();
     while (it.hasNext()) {
       RevCommit commit = (RevCommit) it.next();
       String commitPath = getRenamedPath(gitPath, commit);
       IFileRevision rev = null;
       try {
         rev = CompareUtils.getFileRevision(commitPath, commit, map.getRepository(), null);
       } catch (IOException e) {
         Activator.logError(
             NLS.bind(UIText.GitHistoryPage_errorLookingUpPath, gitPath, commit.getId()), e);
         errorOccurred = true;
       }
       if (rev != null) {
         if (compareMode) {
           ITypedElement right =
               CompareUtils.getFileRevisionTypedElement(commitPath, commit, map.getRepository());
           final GitCompareFileRevisionEditorInput in =
               new GitCompareFileRevisionEditorInput(
                   SaveableCompareEditorInput.createFileElement(resource), right, null);
           try {
             CompareUtils.openInCompare(workBenchPage, in);
           } catch (Exception e) {
             errorOccurred = true;
           }
         } else
           try {
             EgitUiEditorUtils.openEditor(
                 getPart(event).getSite().getPage(), rev, new NullProgressMonitor());
           } catch (CoreException e) {
             Activator.logError(UIText.GitHistoryPage_openFailed, e);
             errorOccurred = true;
           }
       } else ids.add(commit.getId());
     }
   }
   if (input instanceof File) {
     File fileInput = (File) input;
     Repository repo = getRepository(event);
     gitPath = getRepoRelativePath(repo, fileInput);
     Iterator<?> it = selection.iterator();
     while (it.hasNext()) {
       RevCommit commit = (RevCommit) it.next();
       String commitPath = getRenamedPath(gitPath, commit);
       IFileRevision rev = null;
       try {
         rev = CompareUtils.getFileRevision(commitPath, commit, repo, null);
       } catch (IOException e) {
         Activator.logError(
             NLS.bind(UIText.GitHistoryPage_errorLookingUpPath, commitPath, commit.getId()), e);
         errorOccurred = true;
       }
       if (rev != null) {
         if (compareMode)
           try {
             ITypedElement left =
                 CompareUtils.getFileRevisionTypedElement(
                     gitPath, new RevWalk(repo).parseCommit(repo.resolve(Constants.HEAD)), repo);
             ITypedElement right =
                 CompareUtils.getFileRevisionTypedElement(commitPath, commit, repo);
             final GitCompareFileRevisionEditorInput in =
                 new GitCompareFileRevisionEditorInput(left, right, null);
             CompareUtils.openInCompare(workBenchPage, in);
           } catch (IOException e) {
             errorOccurred = true;
           }
         else
           try {
             EgitUiEditorUtils.openEditor(
                 getPart(event).getSite().getPage(), rev, new NullProgressMonitor());
           } catch (CoreException e) {
             Activator.logError(UIText.GitHistoryPage_openFailed, e);
             errorOccurred = true;
           }
       } else ids.add(commit.getId());
     }
   }
   if (errorOccurred) Activator.showError(UIText.GitHistoryPage_openFailed, null);
   if (ids.size() > 0) {
     StringBuilder idList = new StringBuilder(""); // $NON-NLS-1$
     for (ObjectId objectId : ids) idList.append(objectId.getName()).append(' ');
     MessageDialog.openError(
         getPart(event).getSite().getShell(),
         UIText.GitHistoryPage_fileNotFound,
         NLS.bind(UIText.GitHistoryPage_notContainedInCommits, gitPath, idList.toString()));
   }
   return null;
 }
Ejemplo n.º 9
0
  /**
   * 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();
  }
Ejemplo n.º 10
0
  private void buildTrees(final boolean buildMaps) {
    final Object[] wsExpaneded = tree.getExpandedElements();
    final ISelection wsSel = tree.getSelection();

    tree.setInput(null);

    if (baseVersion == null) {
      tree.setContentProvider(new WorkbenchTreeContentProvider());
      tree.setComparator(new WorkbenchTreeComparator());
      tree.setLabelProvider(new WorkbenchTreeLabelProvider());
    } else {
      tree.setContentProvider(new PathNodeContentProvider());
      tree.setComparator(new PathNodeTreeComparator());
      tree.setLabelProvider(new PathNodeLabelProvider());
    }
    for (IWorkbenchAction action : actionsToDispose) action.setEnabled(false);

    showEquals =
        Activator.getDefault()
            .getPreferenceStore()
            .getBoolean(UIPreferences.TREE_COMPARE_SHOW_EQUALS);
    final Repository repo;
    if (input instanceof IResource[]) {
      repositoryMapping = RepositoryMapping.getMapping(((IResource[]) input)[0]);
      if (repositoryMapping == null || repositoryMapping.getRepository() == null) return;
      repo = repositoryMapping.getRepository();
    } else if (input instanceof Repository) {
      repo = (Repository) input;
    } else return;
    final RevCommit baseCommit;
    final RevCommit compareCommit;
    RevWalk rw = new RevWalk(repo);
    try {
      ObjectId commitId = repo.resolve(compareVersion);
      compareCommit = commitId != null ? rw.parseCommit(commitId) : null;
      if (baseVersion == null) baseCommit = null;
      else {
        commitId = repo.resolve(baseVersion);
        baseCommit = rw.parseCommit(commitId);
      }
    } catch (IOException e) {
      Activator.handleError(e.getMessage(), e, true);
      return;
    } finally {
      rw.release();
    }
    showBusy(true);
    try {
      // this does the hard work...
      new ProgressMonitorDialog(getViewSite().getShell())
          .run(
              true,
              true,
              new IRunnableWithProgress() {
                public void run(IProgressMonitor monitor)
                    throws InvocationTargetException, InterruptedException {
                  try {
                    if (buildMaps) buildMaps(repo, baseCommit, compareCommit, monitor);
                    PlatformUI.getWorkbench()
                        .getDisplay()
                        .asyncExec(
                            new Runnable() {
                              public void run() {
                                tree.setInput(input);
                                tree.setExpandedElements(wsExpaneded);
                                tree.setSelection(wsSel);
                                updateControls();
                              }
                            });
                  } catch (IOException e) {
                    throw new InvocationTargetException(e);
                  }
                }
              });
    } catch (InvocationTargetException e) {
      Activator.handleError(e.getTargetException().getMessage(), e.getTargetException(), true);
    } catch (InterruptedException e) {
      input = null;
    } finally {
      showBusy(false);
    }
  }
Ejemplo n.º 11
0
  @Override
  protected Object prepareInput(IProgressMonitor monitor)
      throws InvocationTargetException, InterruptedException {
    // make sure all resources belong to the same repository
    try (RevWalk rw = new RevWalk(repository)) {
      monitor.beginTask(
          UIText.GitCompareEditorInput_CompareResourcesTaskName, IProgressMonitor.UNKNOWN);

      for (IResource resource : resources) {
        RepositoryMapping map = RepositoryMapping.getMapping(resource.getProject());
        if (map == null) {
          throw new InvocationTargetException(
              new IllegalStateException(
                  UIText.GitCompareEditorInput_ResourcesInDifferentReposMessagge));
        }
        if (repository != null && repository != map.getRepository())
          throw new InvocationTargetException(
              new IllegalStateException(
                  UIText.GitCompareEditorInput_ResourcesInDifferentReposMessagge));
        String repoRelativePath = map.getRepoRelativePath(resource);
        filterPathStrings.add(repoRelativePath);
        DiffNode node =
            new DiffNode(Differencer.NO_CHANGE) {
              @Override
              public Image getImage() {
                return FOLDER_IMAGE;
              }
            };
        diffRoots.put(new Path(map.getRepoRelativePath(resource)), node);
        repository = map.getRepository();
      }

      if (repository == null)
        throw new InvocationTargetException(
            new IllegalStateException(
                UIText.GitCompareEditorInput_ResourcesInDifferentReposMessagge));

      if (monitor.isCanceled()) throw new InterruptedException();

      final RevCommit baseCommit;
      try {
        try {
          baseCommit = rw.parseCommit(repository.resolve(baseVersion));
        } catch (IOException e) {
          throw new InvocationTargetException(e);
        }

        final RevCommit compareCommit;
        if (compareVersion == null) {
          compareCommit = null;
        } else {
          try {
            compareCommit = rw.parseCommit(repository.resolve(compareVersion));
          } catch (IOException e) {
            throw new InvocationTargetException(e);
          }
        }
        if (monitor.isCanceled()) throw new InterruptedException();

        // set the labels
        CompareConfiguration config = getCompareConfiguration();
        config.setLeftLabel(compareVersion);
        config.setRightLabel(baseVersion);
        // set title and icon
        if (resources.length == 0) {
          Object[] titleParameters =
              new Object[] {
                Activator.getDefault().getRepositoryUtil().getRepositoryName(repository),
                CompareUtils.truncatedRevision(compareVersion),
                CompareUtils.truncatedRevision(baseVersion)
              };
          setTitle(NLS.bind(UIText.GitCompareEditorInput_EditorTitle, titleParameters));
        } else if (resources.length == 1) {
          Object[] titleParameters =
              new Object[] {
                resources[0].getFullPath().makeRelative().toString(),
                CompareUtils.truncatedRevision(compareVersion),
                CompareUtils.truncatedRevision(baseVersion)
              };
          setTitle(
              NLS.bind(UIText.GitCompareEditorInput_EditorTitleSingleResource, titleParameters));
        } else {
          setTitle(
              NLS.bind(
                  UIText.GitCompareEditorInput_EditorTitleMultipleResources,
                  CompareUtils.truncatedRevision(compareVersion),
                  CompareUtils.truncatedRevision(baseVersion)));
        }

        // build the nodes
        try {
          return buildDiffContainer(baseCommit, compareCommit, monitor);
        } catch (IOException e) {
          throw new InvocationTargetException(e);
        }
      } finally {
        monitor.done();
      }
    }
  }