@Override
 public synchronized void setText2(String text) {
   super.setText2(text);
   if (myOriginal.isRunning()) {
     myOriginal.setText2(text);
   }
 }
 private void doIndexing(
     @NotNull final VirtualFile virtualFile, @NotNull final ProgressIndicator indicator) {
   final int fileId = FileBasedIndex.getFileId(virtualFile);
   indicator.setText("IntelliJence Advisor plugin indexing...");
   indicator.setText2(virtualFile.getCanonicalPath());
   final Long timestamp = getTimestamp(fileId);
   ProgressManager.checkCanceled();
   final long currentTimeStamp = virtualFile.getModificationStamp();
   if (timestamp == null || timestamp != currentTimeStamp) {
     putTimestamp(fileId, currentTimeStamp);
     final ClassReader reader;
     try {
       reader = new ClassReader(virtualFile.contentsToByteArray());
     } catch (IOException e) {
       removeTimestamp(fileId);
       return;
     }
     try {
       for (final AdvisorBaseIndex index : indexes) {
         index.update(fileId, reader);
       }
     } catch (RuntimeException e) {
       log.error(String.format("can't index file: %s", virtualFile.getCanonicalPath()));
       // TODO delete it
       e.printStackTrace();
       throw e;
     }
   }
 }
예제 #3
0
  @Nullable
  public static PsiClass[] getAllTestClasses(final TestClassFilter filter, boolean sync) {
    final PsiClass[][] holder = new PsiClass[1][];
    final Runnable process =
        () -> {
          final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();

          final Collection<PsiClass> set = new LinkedHashSet<>();
          final PsiManager manager = PsiManager.getInstance(filter.getProject());
          final GlobalSearchScope projectScope =
              GlobalSearchScope.projectScope(manager.getProject());
          final GlobalSearchScope scope = projectScope.intersectWith(filter.getScope());
          for (final PsiClass psiClass : AllClassesSearch.search(scope, manager.getProject())) {
            if (filter.isAccepted(psiClass)) {
              if (indicator != null) {
                indicator.setText2(
                    "Found test class " + ReadAction.compute(psiClass::getQualifiedName));
              }
              set.add(psiClass);
            }
          }
          holder[0] = set.toArray(new PsiClass[set.size()]);
        };
    if (sync) {
      ProgressManager.getInstance()
          .runProcessWithProgressSynchronously(
              process, "Searching For Tests...", true, filter.getProject());
    } else {
      process.run();
    }
    return holder[0];
  }
 private void updateProgress(final ProgressIndicator indicator, final String text) {
   LOG.info("PAX output: " + text.replace("\n", ""));
   Matcher matcher = errorMessagePattern.matcher(text.trim());
   // save error message for later..
   if (matcher.matches()) {
     String message = matcher.group(1).trim();
     if (!StringUtil.isEmpty(message)
         && !message.contains("--log=debug")
         && !message.contains("Oops")) {
       myErrorMessage = (myErrorMessage != null ? myErrorMessage : "") + message + "\n";
     }
   }
   if (indicator != null) {
     if (indicator.isCanceled()) {
       if (!myIsCancelled) {
         ApplicationManager.getApplication()
             .invokeLater(
                 new Runnable() {
                   public void run() {
                     cancel();
                   }
                 });
       }
     }
     indicator.setText2(text);
   }
 }
 private void updateIndicatorText(@NotNull String upperLabel, @NotNull String downLabel) {
   ProgressIndicator indicator = myCompositeTask.getIndicator();
   if (indicator != null) {
     indicator.setText(upperLabel);
     indicator.setText2(downLabel);
   }
 }
 private HgCommandResult doMerge(ProgressIndicator indicator) throws VcsException {
   indicator.setText2(HgVcsMessages.message("hg4idea.update.progress.merging"));
   HgMergeCommand mergeCommand = new HgMergeCommand(project, repoRoot);
   // do not explicitly set the revision, that way mercurial itself checks that there are exactly
   // two heads in this branch
   //    mergeCommand.setRevision(headToMerge.getRevision());
   return new HgHeadMerger(project, mergeCommand).merge(repoRoot);
 }
예제 #7
0
 void displayProgress() {
   final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
   if (indicator != null) {
     indicator.setText(
         MessageFormat.format(
             "{0} {1}",
             myAction != null ? myAction : RunnerBundle.message("maven.running"),
             myParameters.getWorkingDirPath()));
     indicator.setText2(myParameters.getGoals().toString());
   }
 }
예제 #8
0
  public void run(@NotNull ProgressIndicator indicator) {
    indicator.setIndeterminate(true);
    indicator.setText2(VcsBundle.message("commit.wait.util.synched.text"));

    if (!myStarted.compareAndSet(false, true)) {
      LOG.error("Waiter running under progress being started again.");
    } else {
      while (!mySemaphore.waitFor(500)) {
        indicator.checkCanceled();
      }
    }
  }
  private void collectLogEntries(
      final ProgressIndicator indicator,
      FilePath file,
      VcsException[] exception,
      final Consumer<VcsFileRevision> result,
      final Ref<Boolean> supports15Ref)
      throws SVNException, VcsException {
    SVNWCClient wcClient = myVcs.createWCClient();
    SVNInfo info =
        wcClient.doInfo(new File(file.getIOFile().getAbsolutePath()), SVNRevision.UNDEFINED);
    wcClient.setEventHandler(
        new ISVNEventHandler() {
          public void handleEvent(SVNEvent event, double progress) throws SVNException {}

          public void checkCancelled() throws SVNCancelException {
            indicator.checkCanceled();
          }
        });
    if (info == null || info.getRepositoryRootURL() == null) {
      exception[0] =
          new VcsException("File ''{0}'' is not under version control" + file.getIOFile());
      return;
    }
    final String url = info.getURL() == null ? null : info.getURL().toString();
    String relativeUrl = url;
    final SVNURL repoRootURL = info.getRepositoryRootURL();

    final String root = repoRootURL.toString();
    if (url != null && url.startsWith(root)) {
      relativeUrl = url.substring(root.length());
    }
    if (indicator != null) {
      indicator.setText2(SvnBundle.message("progress.text2.changes.establishing.connection", url));
    }
    final SVNRevision pegRevision = info.getRevision();
    SVNLogClient client = myVcs.createLogClient();

    final boolean supports15 = SvnUtil.checkRepositoryVersion15(myVcs, url);
    supports15Ref.set(supports15);
    client.doLog(
        new File[] {new File(file.getIOFile().getAbsolutePath())},
        SVNRevision.HEAD,
        SVNRevision.create(1),
        SVNRevision.UNDEFINED,
        false,
        true,
        supports15,
        0,
        null,
        new MyLogEntryHandler(
            myVcs, url, pegRevision, relativeUrl, result, repoRootURL, file.getCharset()));
  }
 private HgCommandExitCode pull(VirtualFile repo, ProgressIndicator indicator, boolean isRebase)
     throws VcsException {
   indicator.setText2(HgVcsMessages.message("hg4idea.progress.pull.with.update"));
   HgPullCommand hgPullCommand = new HgPullCommand(project, repo);
   final String defaultPath = HgUtil.getRepositoryDefaultPath(project, repo);
   hgPullCommand.setSource(defaultPath);
   if (isRebase) {
     hgPullCommand.setRebase(true);
   } else {
     hgPullCommand.setUpdate(true);
   }
   return hgPullCommand.execute();
 }
예제 #11
0
 private void deleteAddedFilesLocally(final List<Change> changes) {
   if (myIndicator != null) {
     myIndicator.setText("Deleting added files locally...");
     myIndicator.setFraction(0);
   }
   final int changesSize = changes.size();
   for (int i = 0; i < changesSize; i++) {
     final Change c = changes.get(i);
     if (c.getType() == Change.Type.NEW) {
       ContentRevision rev = c.getAfterRevision();
       assert rev != null;
       final File ioFile = rev.getFile().getIOFile();
       if (myIndicator != null) {
         myIndicator.setText2(ioFile.getAbsolutePath());
         myIndicator.setFraction(((double) i) / changesSize);
       }
       FileUtil.delete(ioFile);
     }
   }
   if (myIndicator != null) {
     myIndicator.setText2("");
   }
 }
예제 #12
0
        public void run() {
          synchronized (SmoothProgressAdapter.this) {
            if (!isRunning()) {
              return;
            }

            myOriginal.start();
            myOriginalStarted = true;

            myOriginal.setText(getText());
            myOriginal.setFraction(getFraction());
            myOriginal.setText2(getText2());
          }
        }
  public void loadCommittedChanges(
      ChangeBrowserSettings settings,
      RepositoryLocation location,
      int maxCount,
      final AsynchConsumer<CommittedChangeList> consumer)
      throws VcsException {
    try {
      final SvnRepositoryLocation svnLocation = (SvnRepositoryLocation) location;
      final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
      if (progress != null) {
        progress.setText(SvnBundle.message("progress.text.changes.collecting.changes"));
        progress.setText2(
            SvnBundle.message("progress.text2.changes.establishing.connection", location));
      }

      final String repositoryRoot;
      SVNRepository repository = null;
      try {
        repository = myVcs.createRepository(svnLocation.getURL());
        repositoryRoot = repository.getRepositoryRoot(true).toString();
      } catch (SVNException e) {
        throw new VcsException(e);
      } finally {
        if (repository != null) {
          repository.closeSession();
        }
      }

      final ChangeBrowserSettings.Filter filter = settings.createFilter();

      getCommittedChangesImpl(
          settings,
          svnLocation.getURL(),
          new String[] {""},
          maxCount,
          new Consumer<SVNLogEntry>() {
            public void consume(final SVNLogEntry svnLogEntry) {
              final SvnChangeList cl =
                  new SvnChangeList(myVcs, svnLocation, svnLogEntry, repositoryRoot);
              if (filter.accepts(cl)) {
                consumer.consume(cl);
              }
            }
          },
          false,
          true);
    } finally {
      consumer.finished();
    }
  }
예제 #14
0
    private void doRun() {
      myIndicator = ProgressManager.getInstance().getProgressIndicator();

      final List<Change> changesToRefresh = new ArrayList<Change>();
      try {
        ChangesUtil.processChangesByVcs(
            myProject,
            myChanges,
            new ChangesUtil.PerVcsProcessor<Change>() {
              public void process(AbstractVcs vcs, List<Change> changes) {
                final RollbackEnvironment environment = vcs.getRollbackEnvironment();
                if (environment != null) {
                  changesToRefresh.addAll(changes);

                  if (myIndicator != null) {
                    myIndicator.setText(vcs.getDisplayName() + ": performing rollback...");
                    myIndicator.setIndeterminate(false);
                    myIndicator.checkCanceled();
                  }
                  environment.rollbackChanges(
                      changes,
                      myExceptions,
                      new RollbackProgressModifier(changes.size(), myIndicator));
                  if (myIndicator != null) {
                    myIndicator.setText2("");
                    myIndicator.checkCanceled();
                  }

                  if (myExceptions.isEmpty() && myDeleteLocallyAddedFiles) {
                    deleteAddedFilesLocally(changes);
                  }
                }
              }
            });
      } catch (ProcessCanceledException e) {
        // still do refresh
      }

      if (myIndicator != null) {
        myIndicator.startNonCancelableSection();
        myIndicator.setIndeterminate(true);
        myIndicator.setText2("");
        myIndicator.setText(VcsBundle.message("progress.text.synchronizing.files"));
      }

      doRefresh(myProject, changesToRefresh);

      AbstractVcsHelper.getInstance(myProject)
          .showErrors(myExceptions, VcsBundle.message("changes.action.rollback.text"));
    }
    public void run() {
      ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
      if (progress != null) {
        progress.setText(SvnBundle.message("progress.text.loading.contents", myURL));
        progress.setText2(SvnBundle.message("progress.text2.revision.information", myRevision));
      }

      try {
        myContents =
            SvnUtil.getFileContents(
                myVCS, SvnTarget.fromURL(SvnUtil.parseUrl(myURL)), myRevision, myPegRevision);
      } catch (VcsException e) {
        myException = e;
      }
    }
  public static void updateRepository(AsposeJavaComponent component, ProgressIndicator p) {
    p.setText2("Downloading " + component.get_name() + " examples ...");
    checkAndCreateFolder(getLocalRepositoryPath(component));

    try {

      updateRepository(getLocalRepositoryPath(component), component.get_remoteExamplesRepository());
      p.setFraction(0.3);
      // Added by [email protected] - Integration of Apache POI Examples / Other FrameWork
      // Examples
      OtherExamplesManager.updateOtherExamplesRepositories(component, p);
      // [email protected]
      p.setFraction(0.5);
    } catch (Exception e) {
    }
  }
  private void updateToPulledHead(
      VirtualFile repo,
      UpdatedFiles updatedFiles,
      HgRevisionNumber newHead,
      ProgressIndicator indicator) {
    indicator.setText2(HgVcsMessages.message("hg4idea.update.progress.updating.to.pulled.head"));
    HgRevisionNumber parentBeforeUpdate =
        new HgWorkingCopyRevisionsCommand(project).firstParent(repo);
    HgUpdateCommand updateCommand = new HgUpdateCommand(project, repoRoot);
    updateCommand.setRevision(newHead.getChangeset());
    updateCommand.setClean(true);
    updateCommand.execute();

    HgRevisionNumber commonParent = findCommonParent(newHead, parentBeforeUpdate);
    addUpdatedFiles(repo, updatedFiles, commonParent, newHead);
  }
  public static void executeExternalProcess(
      @Nullable final Project myProject,
      @NotNull final ProcessHandler processHandler,
      @NotNull final ExecutionMode mode,
      @NotNull final String presentableCmdline) {
    final String title = mode.getTitle() != null ? mode.getTitle() : "Please wait...";
    assert title != null;

    final Runnable process;
    if (mode.cancelable()) {
      process = createCancelableExecutionProcess(processHandler, mode.shouldCancelFun());
    } else {
      if (mode.getTimeout() <= 0) {
        process =
            new Runnable() {
              public void run() {
                processHandler.waitFor();
              }
            };
      } else {
        process =
            createTimelimitedExecutionProcess(
                processHandler, mode.getTimeout(), presentableCmdline);
      }
    }
    if (mode.withModalProgress()) {
      ProgressManager.getInstance()
          .runProcessWithProgressSynchronously(
              process, title, mode.cancelable(), myProject, mode.getProgressParentComponent());
    } else if (mode.inBackGround()) {
      final Task task =
          new Task.Backgroundable(myProject, title, mode.cancelable()) {
            public void run(@NotNull final ProgressIndicator indicator) {
              process.run();
            }
          };
      ProgressManager.getInstance().run(task);
    } else {
      final String title2 = mode.getTitle2();
      final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
      if (indicator != null && title2 != null) {
        indicator.setText2(title2);
      }
      process.run();
    }
  }
  private void update(
      @NotNull VirtualFile repo,
      ProgressIndicator indicator,
      UpdatedFiles updatedFiles,
      List<VcsException> warnings)
      throws VcsException {
    indicator.setText2(HgVcsMessages.message("hg4idea.progress.updatingworkingdir"));

    HgRevisionNumber parentBeforeUpdate =
        new HgWorkingCopyRevisionsCommand(project).firstParent(repo);
    HgUpdateCommand hgUpdateCommand = new HgUpdateCommand(project, repo);
    String warningMessages = ensureSuccess(hgUpdateCommand.execute()).getWarnings();
    handlePossibleWarning(warnings, warningMessages);

    HgRevisionNumber parentAfterUpdate =
        new HgWorkingCopyRevisionsCommand(project).firstParent(repo);

    addUpdatedFiles(repo, updatedFiles, parentBeforeUpdate, parentAfterUpdate);
  }
  public List<SvnChangeList> getCommittedChanges(
      ChangeBrowserSettings settings, final RepositoryLocation location, final int maxCount)
      throws VcsException {
    final SvnRepositoryLocation svnLocation = (SvnRepositoryLocation) location;
    final ArrayList<SvnChangeList> result = new ArrayList<SvnChangeList>();
    final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
    if (progress != null) {
      progress.setText(SvnBundle.message("progress.text.changes.collecting.changes"));
      progress.setText2(
          SvnBundle.message("progress.text2.changes.establishing.connection", location));
    }

    final String repositoryRoot;
    SVNRepository repository = null;
    try {
      repository = myVcs.createRepository(svnLocation.getURL());
      repositoryRoot = repository.getRepositoryRoot(true).toString();
      repository.closeSession();
    } catch (SVNException e) {
      throw new VcsException(e);
    } finally {
      if (repository != null) {
        repository.closeSession();
      }
    }

    getCommittedChangesImpl(
        settings,
        svnLocation.getURL(),
        new String[] {""},
        maxCount,
        new Consumer<SVNLogEntry>() {
          public void consume(final SVNLogEntry svnLogEntry) {
            result.add(new SvnChangeList(myVcs, svnLocation, svnLogEntry, repositoryRoot));
          }
        },
        false,
        true);
    settings.filterChanges(result);
    return result;
  }
 private boolean generateSkeletonsForList(
     @NotNull final PySkeletonRefresher refresher,
     ProgressIndicator indicator,
     @Nullable final String currentBinaryFilesPath)
     throws InvalidSdkException {
   final PySkeletonGenerator generator =
       new PySkeletonGenerator(refresher.getSkeletonsPath(), mySdk, currentBinaryFilesPath);
   indicator.setIndeterminate(false);
   final String homePath = mySdk.getHomePath();
   if (homePath == null) return false;
   final ProcessOutput runResult =
       PySdkUtil.getProcessOutput(
           new File(homePath).getParent(),
           new String[] {
             homePath, PythonHelpersLocator.getHelperPath("extra_syspath.py"), myQualifiedName
           },
           PythonSdkType.getVirtualEnvExtraEnv(homePath),
           5000);
   if (runResult.getExitCode() == 0 && !runResult.isTimeout()) {
     final String extraPath = runResult.getStdout();
     final PySkeletonGenerator.ListBinariesResult binaries =
         generator.listBinaries(mySdk, extraPath);
     final List<String> names = Lists.newArrayList(binaries.modules.keySet());
     Collections.sort(names);
     final int size = names.size();
     for (int i = 0; i != size; ++i) {
       final String name = names.get(i);
       indicator.setFraction((double) i / size);
       if (needBinaryList(name)) {
         indicator.setText2(name);
         final PySkeletonRefresher.PyBinaryItem item = binaries.modules.get(name);
         final String modulePath = item != null ? item.getPath() : "";
         //noinspection unchecked
         refresher.generateSkeleton(
             name, modulePath, new ArrayList<String>(), Consumer.EMPTY_CONSUMER);
       }
     }
   }
   return true;
 }
 private void collectLogEntriesForRepository(
     final ProgressIndicator indicator,
     FilePath file,
     final Consumer<VcsFileRevision> result,
     final Ref<Boolean> supports15Ref)
     throws SVNException, VcsException {
   final String url = file.getPath().replace('\\', '/');
   if (indicator != null) {
     indicator.setText2(SvnBundle.message("progress.text2.changes.establishing.connection", url));
   }
   SVNWCClient wcClient = myVcs.createWCClient();
   final SVNURL svnurl = SVNURL.parseURIEncoded(url);
   SVNInfo info = wcClient.doInfo(svnurl, SVNRevision.UNDEFINED, SVNRevision.HEAD);
   final String root = info.getRepositoryRootURL().toString();
   String relativeUrl = url;
   if (url.startsWith(root)) {
     relativeUrl = url.substring(root.length());
   }
   SVNLogClient client = myVcs.createLogClient();
   final boolean supports15 = SvnUtil.checkRepositoryVersion15(myVcs, root);
   supports15Ref.set(supports15);
   // todo log in history provider
   client.doLog(
       svnurl,
       new String[] {},
       SVNRevision.UNDEFINED,
       SVNRevision.HEAD,
       SVNRevision.create(1),
       false,
       true,
       supports15,
       0,
       null,
       new RepositoryLogEntryHandler(
           myVcs, url, SVNRevision.UNDEFINED, relativeUrl, result, info.getRepositoryRootURL()));
 }
  public boolean update(
      final UpdatedFiles updatedFiles, ProgressIndicator indicator, List<VcsException> warnings)
      throws VcsException {
    indicator.setText(HgVcsMessages.message("hg4idea.progress.updating", repoRoot.getPath()));

    String defaultPath = HgUtil.getRepositoryDefaultPath(project, repoRoot);

    if (StringUtil.isEmptyOrSpaces(defaultPath)) {
      throw new VcsException(
          HgVcsMessages.message("hg4idea.warning.no-default-update-path", repoRoot.getPath()));
    }

    List<HgRevisionNumber> branchHeadsBeforePull = new HgHeadsCommand(project, repoRoot).execute();

    if (branchHeadsBeforePull.size() > 1) {
      reportWarning(
          warnings,
          HgVcsMessages.message(
              "hg4idea.update.warning.multipleHeadsBeforeUpdate", repoRoot.getPath()));
    }

    // TODO perhaps report a warning in this case ?
    //    //if the parent of the working dir is not the tip of the current branch, the user has
    //    //manually brought his working copy to some specific revision. In that case we won't touch
    //    //his setup
    //    if (!parentRevision.equals(currentBranchHead)) {
    //      throw new VcsException("working dir not at branch tip (use \"Update to...\" to check out
    // branch tip)");
    //    }

    HgRevisionNumber parentBeforeUpdate =
        new HgWorkingCopyRevisionsCommand(project).firstParent(repoRoot);
    HgCommandExitCode pullResult = pull(repoRoot, indicator, shouldRebase());
    if (pullResult == HgCommandExitCode.ERROR) {
      return false;
    }

    if (pullResult == HgCommandExitCode.SUCCESS) {
      HgRevisionNumber parentAfterUpdate =
          new HgWorkingCopyRevisionsCommand(project).firstParent(repoRoot);
      addUpdatedFiles(repoRoot, updatedFiles, parentBeforeUpdate, parentAfterUpdate);
      return true;
    }

    if (shouldMerge()) {

      indicator.setText2(HgVcsMessages.message("hg4idea.progress.countingHeads"));

      List<HgRevisionNumber> branchHeadsAfterPull = new HgHeadsCommand(project, repoRoot).execute();
      List<HgRevisionNumber> pulledBranchHeads =
          determinePulledBranchHeads(branchHeadsBeforePull, branchHeadsAfterPull);
      List<HgRevisionNumber> remainingOriginalBranchHeads =
          determingRemainingOriginalBranchHeads(branchHeadsBeforePull, branchHeadsAfterPull);

      if (branchHeadsAfterPull.size() > 1) {
        abortOnLocalChanges();
        abortOnMultiplePulledHeads(pulledBranchHeads);
        abortOnMultipleLocalHeads(remainingOriginalBranchHeads);

        HgCommandResult mergeResult = doMerge(indicator);

        if (shouldCommitAfterMerge()) {
          commitOrWarnAboutConflicts(warnings, mergeResult);
        }
      }
      // any kind of update could have resulted in merges and merge conflicts, so run the resolver
      resolvePossibleConflicts(updatedFiles);
    } else {
      processRebase(updatedFiles);
    }

    return true;
  }
 @Override
 public void setText2(final String text) {
   myIndicator.setText2(text);
 }
  protected void runOverFiles(
      @NotNull final Project project, @NotNull final List<VirtualFile> dartFiles) {
    if (dartFiles.isEmpty()) {
      Messages.showInfoMessage(
          project,
          DartBundle.message("dart.style.files.no.dart.files"),
          DartBundle.message("dart.style.action.name"));
      return;
    }

    if (Messages.showOkCancelDialog(
            project,
            DartBundle.message("dart.style.files.dialog.question", dartFiles.size()),
            DartBundle.message("dart.style.action.name"),
            null)
        != Messages.OK) {
      return;
    }

    final Map<VirtualFile, String> fileToNewContentMap = new THashMap<VirtualFile, String>();
    final int lineLength = getRightMargin(project);

    final Runnable runnable =
        () -> {
          double fraction = 0.0;
          for (final VirtualFile virtualFile : dartFiles) {
            fraction += 1.0;
            final ProgressIndicator indicator =
                ProgressManager.getInstance().getProgressIndicator();
            if (indicator != null) {
              indicator.checkCanceled();
              indicator.setFraction(fraction / dartFiles.size());
              indicator.setText2(FileUtil.toSystemDependentName(virtualFile.getPath()));
            }

            final DartAnalysisServerService.FormatResult formatResult =
                DartAnalysisServerService.getInstance().edit_format(virtualFile, 0, 0, lineLength);
            if (formatResult != null
                && formatResult.getEdits() != null
                && formatResult.getEdits().size() == 1) {
              final String replacement =
                  StringUtil.convertLineSeparators(formatResult.getEdits().get(0).getReplacement());
              fileToNewContentMap.put(virtualFile, replacement);
            }
          }
        };

    DartAnalysisServerService.getInstance().updateFilesContent();

    final boolean ok =
        ApplicationManagerEx.getApplicationEx()
            .runProcessWithProgressSynchronously(
                runnable, DartBundle.message("dart.style.action.name"), true, project);

    if (ok) {
      final Runnable onSuccessRunnable =
          () -> {
            CommandProcessor.getInstance().markCurrentCommandAsGlobal(project);

            for (Map.Entry<VirtualFile, String> entry : fileToNewContentMap.entrySet()) {
              final VirtualFile file = entry.getKey();
              final Document document = FileDocumentManager.getInstance().getDocument(file);
              final String newContent = entry.getValue();

              if (document != null && newContent != null) {
                document.setText(newContent);
              }
            }
          };

      ApplicationManager.getApplication()
          .runWriteAction(
              () ->
                  CommandProcessor.getInstance()
                      .executeCommand(
                          project,
                          onSuccessRunnable,
                          DartBundle.message("dart.style.action.name"),
                          null));
    }
  }
  private void searchInFiles(
      @NotNull Collection<PsiFile> psiFiles,
      @NotNull FindUsagesProcessPresentation processPresentation,
      @NotNull final Processor<UsageInfo> consumer) {
    int i = 0;
    long totalFilesSize = 0;
    int count = 0;

    for (final PsiFile psiFile : psiFiles) {
      final VirtualFile virtualFile = psiFile.getVirtualFile();
      final int index = i++;
      if (virtualFile == null) continue;

      long fileLength = UsageViewManagerImpl.getFileLength(virtualFile);
      if (fileLength == -1) continue; // Binary or invalid

      final boolean skipProjectFile =
          ProjectCoreUtil.isProjectOrWorkspaceFile(virtualFile)
              && !myFindModel.isSearchInProjectFiles();
      if (skipProjectFile && !Registry.is("find.search.in.project.files")) continue;

      if (fileLength > SINGLE_FILE_SIZE_LIMIT) {
        myLargeFiles.add(psiFile);
        continue;
      }

      myProgress.checkCanceled();
      myProgress.setFraction((double) index / psiFiles.size());
      String text =
          FindBundle.message(
              "find.searching.for.string.in.file.progress",
              myFindModel.getStringToFind(),
              virtualFile.getPresentableUrl());
      myProgress.setText(text);
      myProgress.setText2(
          FindBundle.message("find.searching.for.string.in.file.occurrences.progress", count));

      int countInFile =
          FindInProjectUtil.processUsagesInFile(
              psiFile,
              myFindModel,
              new Processor<UsageInfo>() {
                @Override
                public boolean process(UsageInfo info) {
                  return skipProjectFile || consumer.process(info);
                }
              });

      if (countInFile > 0 && skipProjectFile) {
        processPresentation.projectFileUsagesFound(
            new Runnable() {
              @Override
              public void run() {
                FindModel model = myFindModel.clone();
                model.setSearchInProjectFiles(true);
                FindInProjectManager.getInstance(myProject).startFindInProject(model);
              }
            });
        continue;
      }

      count += countInFile;
      if (countInFile > 0) {
        totalFilesSize += fileLength;
        if (totalFilesSize > FILES_SIZE_LIMIT && !myWarningShown) {
          myWarningShown = true;
          String message =
              FindBundle.message(
                  "find.excessive.total.size.prompt",
                  UsageViewManagerImpl.presentableSize(totalFilesSize),
                  ApplicationNamesInfo.getInstance().getProductName());
          UsageLimitUtil.showAndCancelIfAborted(
              myProject, message, processPresentation.getUsageViewPresentation());
        }
      }
    }
  }
예제 #27
0
    // "Calculating not merged revisions"
    @Override
    public void run(ContinuationContext context) {
      if (myCopyData == null) {
        finishWithError(context, "Merge start wasn't found", true);
        return;
      }

      final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
      myIsReintegrate = myCopyData.isInvertedSense();
      if (!myWcInfo.getFormat().supportsMergeInfo()) return;
      final SvnBranchPointsCalculator.BranchCopyData data = myCopyData.getTrue();
      final long sourceLatest = data.getTargetRevision();

      final SvnCommittedChangesProvider committedChangesProvider =
          (SvnCommittedChangesProvider) myVcs.getCommittedChangesProvider();
      final ChangeBrowserSettings settings = new ChangeBrowserSettings();
      settings.CHANGE_AFTER = Long.toString(sourceLatest);
      settings.USE_CHANGE_AFTER_FILTER = true;

      String local =
          SVNPathUtil.getRelativePath(myWcInfo.getRepositoryRoot(), myWcInfo.getRootUrl());
      final String relativeLocal = (local.startsWith("/") ? local : "/" + local);

      final LinkedList<Pair<SvnChangeList, TreeStructureNode<SVNLogEntry>>> list =
          new LinkedList<Pair<SvnChangeList, TreeStructureNode<SVNLogEntry>>>();
      try {
        committedChangesProvider.getCommittedChangesWithMergedRevisons(
            settings,
            new SvnRepositoryLocation(mySourceUrl),
            0,
            new PairConsumer<SvnChangeList, TreeStructureNode<SVNLogEntry>>() {
              public void consume(SvnChangeList svnList, TreeStructureNode<SVNLogEntry> tree) {
                indicator.checkCanceled();
                if (sourceLatest >= svnList.getNumber()) return;
                list.add(new Pair<SvnChangeList, TreeStructureNode<SVNLogEntry>>(svnList, tree));
              }
            });
      } catch (VcsException e) {
        finishWithError(
            context, "Checking revisions for merge fault", Collections.singletonList(e));
      }

      indicator.setText("Checking merge information...");
      // to do not go into file system while asking something on the net
      for (Pair<SvnChangeList, TreeStructureNode<SVNLogEntry>> pair : list) {
        final SvnChangeList svnList = pair.getFirst();
        final SvnMergeInfoCache.MergeCheckResult checkResult = myMergeChecker.checkList(svnList);
        indicator.setText2("Processing revision " + svnList.getNumber());

        if (SvnMergeInfoCache.MergeCheckResult.NOT_MERGED.equals(checkResult)) {
          // additionally check for being 'local'
          final List<TreeStructureNode<SVNLogEntry>> children = pair.getSecond().getChildren();
          boolean localChange = false;
          for (TreeStructureNode<SVNLogEntry> child : children) {
            if (isLocalRevisionMergeIteration(child, relativeLocal, indicator)) {
              localChange = true;
              break;
            }
          }

          if (!localChange) {
            myNotMerged.add(svnList);
          }
        }
      }

      if (myNotMerged.isEmpty()) {
        finishWithError(context, "Everything is up-to-date", false);
        return;
      }
      context.next(new ShowRevisionSelector(myCopyData));
    }
  public void getCommittedChangesWithMergedRevisons(
      final ChangeBrowserSettings settings,
      final RepositoryLocation location,
      final int maxCount,
      final PairConsumer<SvnChangeList, TreeStructureNode<SVNLogEntry>> finalConsumer)
      throws VcsException {
    final SvnRepositoryLocation svnLocation = (SvnRepositoryLocation) location;
    final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
    if (progress != null) {
      progress.setText(SvnBundle.message("progress.text.changes.collecting.changes"));
      progress.setText2(
          SvnBundle.message("progress.text2.changes.establishing.connection", location));
    }

    final String repositoryRoot;
    SVNRepository repository = null;
    try {
      repository = myVcs.createRepository(svnLocation.getURL());
      repositoryRoot = repository.getRepositoryRoot(true).toString();
    } catch (SVNException e) {
      throw new VcsException(e);
    } finally {
      if (repository != null) {
        repository.closeSession();
      }
    }

    final MergeTrackerProxy proxy =
        new MergeTrackerProxy(
            new Consumer<TreeStructureNode<SVNLogEntry>>() {
              public void consume(TreeStructureNode<SVNLogEntry> node) {
                finalConsumer.consume(
                    new SvnChangeList(myVcs, svnLocation, node.getMe(), repositoryRoot), node);
              }
            });
    final SvnMergeSourceTracker mergeSourceTracker =
        new SvnMergeSourceTracker(
            new ThrowableConsumer<Pair<SVNLogEntry, Integer>, SVNException>() {
              public void consume(Pair<SVNLogEntry, Integer> svnLogEntryIntegerPair)
                  throws SVNException {
                proxy.consume(svnLogEntryIntegerPair);
              }
            });

    getCommittedChangesImpl(
        settings,
        svnLocation.getURL(),
        new String[] {""},
        maxCount,
        new Consumer<SVNLogEntry>() {
          public void consume(final SVNLogEntry svnLogEntry) {
            try {
              mergeSourceTracker.consume(svnLogEntry);
            } catch (SVNException e) {
              throw new RuntimeException(e);
              // will not occur actually but anyway never eat them
            }
          }
        },
        true,
        false);

    proxy.finish();
  }
  private void getCommittedChangesImpl(
      ChangeBrowserSettings settings,
      final String url,
      final String[] filterUrls,
      final int maxCount,
      final Consumer<SVNLogEntry> resultConsumer,
      final boolean includeMergedRevisions,
      final boolean filterOutByDate)
      throws VcsException {
    final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
    if (progress != null) {
      progress.setText(SvnBundle.message("progress.text.changes.collecting.changes"));
      progress.setText2(SvnBundle.message("progress.text2.changes.establishing.connection", url));
    }
    try {
      SVNLogClient logger = myVcs.createLogClient();

      final String author = settings.getUserFilter();
      final Date dateFrom = settings.getDateAfterFilter();
      final Long changeFrom = settings.getChangeAfterFilter();
      final Date dateTo = settings.getDateBeforeFilter();
      final Long changeTo = settings.getChangeBeforeFilter();

      final SVNRevision revisionBefore;
      if (dateTo != null) {
        revisionBefore = SVNRevision.create(dateTo);
      } else if (changeTo != null) {
        revisionBefore = SVNRevision.create(changeTo.longValue());
      } else {
        SVNRepository repository = null;
        final long revision;
        try {
          repository = myVcs.createRepository(url);
          revision = repository.getLatestRevision();
        } finally {
          if (repository != null) {
            repository.closeSession();
          }
        }
        revisionBefore = SVNRevision.create(revision);
      }
      final SVNRevision revisionAfter;
      if (dateFrom != null) {
        revisionAfter = SVNRevision.create(dateFrom);
      } else if (changeFrom != null) {
        revisionAfter = SVNRevision.create(changeFrom.longValue());
      } else {
        revisionAfter = SVNRevision.create(1);
      }

      logger.doLog(
          SVNURL.parseURIEncoded(url),
          filterUrls,
          revisionBefore,
          revisionBefore,
          revisionAfter,
          settings.STOP_ON_COPY,
          true,
          includeMergedRevisions,
          maxCount,
          null,
          new ISVNLogEntryHandler() {
            public void handleLogEntry(SVNLogEntry logEntry) {
              if (myProject.isDisposed()) throw new ProcessCanceledException();
              if (progress != null) {
                progress.setText2(
                    SvnBundle.message(
                        "progress.text2.processing.revision", logEntry.getRevision()));
                progress.checkCanceled();
              }
              if (filterOutByDate && logEntry.getDate() == null) {
                // do not add lists without info - this situation is possible for lists where there
                // are paths that user has no rights to observe
                return;
              }
              if (author == null || author.equalsIgnoreCase(logEntry.getAuthor())) {
                resultConsumer.consume(logEntry);
              }
            }
          });
    } catch (SVNException e) {
      throw new VcsException(e);
    }
  }