com.intellij.openapi.vcs.FilePath Java Examples

The following examples show how to use com.intellij.openapi.vcs.FilePath. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: P4LocalFileImpl.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
private P4LocalFileImpl(@Nullable P4RemoteFile depot, @Nullable P4RemoteFile clientDepot, @NotNull FilePath local,
        @NotNull P4Revision haveRev, @Nullable P4FileRevision headRev, @Nullable P4ChangelistId changelistId,
        @NotNull P4FileAction action, @NotNull P4ResolveType resolveType, @Nullable P4FileType fileType,
        @Nullable P4RemoteFile integrateFrom, @Nullable Charset charset) {
    this.depot = depot;
    this.clientDepot = clientDepot;
    this.local = local;
    this.haveRev = haveRev;
    this.headRev = headRev;
    this.changelistId = changelistId;
    this.action = action;
    this.resolveType = resolveType;
    this.fileType = fileType == null ? P4FileType.convert("unknown") : fileType;
    this.integrateFrom = integrateFrom;
    this.charset = charset;
}
 
Example #2
Source File: ApplyBinaryShelvedFilePatch.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected Result applyChange(Project project, final VirtualFile fileToPatch, FilePath pathBeforeRename, Getter<CharSequence> baseContents)
        throws IOException {
  try {
    ContentRevision contentRevision = myPatch.getShelvedBinaryFile().createChange(project).getAfterRevision();
    if (contentRevision != null) {
      assert (contentRevision instanceof ShelvedBinaryContentRevision);
      byte[] binaryContent = ((ShelvedBinaryContentRevision)contentRevision).getBinaryContent();
      //it may be new empty binary file
      fileToPatch.setBinaryContent(binaryContent != null ? binaryContent : ArrayUtil.EMPTY_BYTE_ARRAY);
    }
  }
  catch (VcsException e) {
    LOG.error("Couldn't apply shelved binary patch", e);
    return new Result(ApplyPatchStatus.FAILURE) {

      @Override
      public ApplyPatchForBaseRevisionTexts getMergeData() {
        return null;
      }
    };
  }
  return SUCCESS;
}
 
Example #3
Source File: ContentRevisionCache.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static VcsRevisionNumber putIntoCurrentCache(final ContentRevisionCache cache,
                                                     FilePath path,
                                                     @Nonnull VcsKey vcsKey,
                                                     final CurrentRevisionProvider loader) throws VcsException, IOException {
  VcsRevisionNumber loadedRevisionNumber;
  Pair<VcsRevisionNumber, Long> currentRevision;

  while (true) {
    loadedRevisionNumber = loader.getCurrentRevision();
    currentRevision = cache.getCurrent(path, vcsKey);
    if (loadedRevisionNumber.equals(currentRevision.getFirst())) return loadedRevisionNumber;

    if (cache.putCurrent(path, loadedRevisionNumber, vcsKey, currentRevision.getSecond())) {
      return loadedRevisionNumber;
    }
  }
}
 
Example #4
Source File: P4RollbackEnvironment.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
/**
 * Force a sync from server operation to overwrite local changes.
 * @param files files to sync
 * @param exceptions exceptions encountered
 * @param listener listener on progress
 */
private void forceSync(List<FilePath> files, List<VcsException> exceptions, RollbackProgressListener listener) {
    if (files.isEmpty() || project.isDisposed()) {
        return;
    }
    ProjectConfigRegistry registry = ProjectConfigRegistry.getInstance(project);
    if (registry == null || registry.isDisposed()) {
        return;
    }

    groupFilesByClient(registry, files)
        .stream()
        .map(e -> P4ServerComponent
                .perform(project, e.getKey().getClientConfig(), new FetchFilesAction(e.getValue(), "", true))
                .whenCompleted((c) -> listener.accept(e.getValue()))
                .whenServerError((ex) -> listener.accept(e.getValue()))
                .whenOffline(() -> listener.accept(e.getValue())))
        .collect(ErrorCollectors.collectActionErrors(exceptions))
        .whenCompleted((c) -> LOG.info("Completed sync of files"))
        .whenFailed((c) -> LOG.info("Failed to sync files"));
}
 
Example #5
Source File: ChangeGoToChangePopupAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("AbstractMethodCallInConstructor")
public Fake(@Nonnull Chain chain, int selection, @Nonnull Consumer<Integer> onSelected) {
  super(chain, onSelected);

  mySelection = selection;

  // we want to show ChangeBrowser-based popup, so have to create some fake changes
  List<? extends DiffRequestProducer> requests = chain.getRequests();

  myChanges = new ArrayList<Change>(requests.size());
  for (int i = 0; i < requests.size(); i++) {
    FilePath path = getFilePath(i);
    FileStatus status = getFileStatus(i);
    FakeContentRevision revision = new FakeContentRevision(path);
    myChanges.add(new Change(revision, revision, status));
  }
}
 
Example #6
Source File: FileTreeUtil.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
/**
 * Break apart the path into parent directories, up to and including the {@literal parent}.
 * If the {@literal parent} is never reached, then this returns null.
 *
 * @param path   child path
 * @param parent parent path
 * @return the paths in the tree, or null if the path is not in the parent.  The returned
 *      paths will always contain at least the path itself, if it is under the parent.
 */
@Nullable
public static List<FilePath> getTreeTo(@NotNull FilePath path, @Nullable FilePath parent) {
    if (parent == null) {
        return null;
    }
    List<FilePath> ret = new ArrayList<>();
    FilePath prev;
    FilePath next = path;
    do {
        ret.add(next);
        prev = next;
        next = next.getParentPath();
    } while (next != null && !next.equals(prev) && !parent.equals(prev));
    if (parent.equals(prev) || parent.equals(next)) {
        return ret;
    }
    return null;
}
 
Example #7
Source File: DiffShelvedChangesAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void processBinaryFiles(@Nonnull final Project project,
                                       @Nonnull List<ShelvedBinaryFile> files,
                                       @Nonnull List<MyDiffRequestProducer> diffRequestProducers) {
  final String base = project.getBaseDir().getPath();
  for (final ShelvedBinaryFile shelvedChange : files) {
    final File file = new File(base, shelvedChange.AFTER_PATH == null ? shelvedChange.BEFORE_PATH : shelvedChange.AFTER_PATH);
    final FilePath filePath = VcsUtil.getFilePath(file);
    diffRequestProducers.add(new MyDiffRequestProducer(shelvedChange, filePath) {
      @Nonnull
      @Override
      public DiffRequest process(@Nonnull UserDataHolder context, @Nonnull ProgressIndicator indicator)
              throws DiffRequestProducerException, ProcessCanceledException {
        Change change = shelvedChange.createChange(project);
        return PatchDiffRequestFactory.createDiffRequest(project, change, getName(), context, indicator);
      }
    });
  }
}
 
Example #8
Source File: ConnectionTreeRootNode.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
private void loadClientConfigRoot(@NotNull Project project, @NotNull ClientConfigRoot root) {
    RootNode fileRoot = createRootNode(root);

    try {
        List<ActionChoice> pendingActions =
                CacheComponent.getInstance(project).getCachePending().copyActions(root.getClientConfig())
                        .collect(Collectors.toList());
        fileRoot.pending.setPendingCount(pendingActions.size());
        pendingActions.forEach((ac) -> {
            DefaultMutableTreeNode actionNode = new DefaultMutableTreeNode(ac);
            fileRoot.pendingNode.add(actionNode);
            // File information on an action is static.
            for (FilePath affectedFile : ac.getAffectedFiles()) {
                actionNode.add(new DefaultMutableTreeNode(affectedFile));
            }
            for (P4CommandRunner.ResultError previousExecutionProblem : ac.getPreviousExecutionProblems()) {
                actionNode.add(new DefaultMutableTreeNode(previousExecutionProblem));
            }
        });
    } catch (InterruptedException e) {
        InternalErrorMessage.send(project).cacheLockTimeoutError(new ErrorEvent<>(new VcsInterruptedException(e)));
    }
}
 
Example #9
Source File: VirtualFileListCellRenderer.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void putParentPath(Object value, FilePath path, FilePath self) {
  final File parentFile = path.getIOFile().getParentFile();
  if (parentFile != null) {
    final String parentPath = parentFile.getPath();
    append(" (", SimpleTextAttributes.GRAYED_ATTRIBUTES);
    putParentPathImpl(value, parentPath, self);
    append(")", SimpleTextAttributes.GRAYED_ATTRIBUTES);
  }
}
 
Example #10
Source File: GetCommittedChangelistAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static Collection<FilePath> getFilePaths(final VcsContext context) {
  final Set<FilePath> files = new HashSet<>();
  final ChangeList[] selectedChangeLists = context.getSelectedChangeLists();
  if (selectedChangeLists != null) {
    for(ChangeList changelist: selectedChangeLists) {
      for(Change change: changelist.getChanges()) {
        files.add(ChangesUtil.getFilePath(change));
      }
    }
  }
  return files;
}
 
Example #11
Source File: ChangesBrowserChangeNode.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void render(@Nonnull ChangesBrowserNodeRenderer renderer, boolean selected, boolean expanded, boolean hasFocus) {
  Change change = getUserObject();
  FilePath filePath = ChangesUtil.getFilePath(change);
  VirtualFile file = filePath.getVirtualFile();

  if (myDecorator != null) {
    myDecorator.preDecorate(change, renderer, renderer.isShowFlatten());
  }

  renderer.appendFileName(file, filePath.getName(), change.getFileStatus().getColor());

  String originText = change.getOriginText(myProject);
  if (originText != null) {
    renderer.append(spaceAndThinSpace() + originText, SimpleTextAttributes.REGULAR_ATTRIBUTES);
  }

  if (renderer.isShowFlatten()) {
    FilePath parentPath = filePath.getParentPath();
    if (parentPath != null) {
      renderer.append(spaceAndThinSpace() + FileUtil.getLocationRelativeToUserHome(parentPath.getPath()),
                      SimpleTextAttributes.GRAYED_ATTRIBUTES);
    }
    appendSwitched(renderer, file);
  }
  else if (getFileCount() != 1 || getDirectoryCount() != 0) {
    appendSwitched(renderer, file);
    appendCount(renderer);
  }
  else {
    appendSwitched(renderer, file);
  }

  renderer.setIcon(getIcon(change, filePath));

  if (myDecorator != null) {
    myDecorator.decorate(change, renderer, renderer.isShowFlatten());
  }
}
 
Example #12
Source File: ContentRevisionCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
@javax.annotation.Nullable
public byte[] getBytes(FilePath path, VcsRevisionNumber number, @Nonnull VcsKey vcsKey, @Nonnull UniqueType type) {
  synchronized (myLock) {
    final SoftReference<byte[]> reference = myCache.get(new Key(path, number, vcsKey, type));
    return SoftReference.dereference(reference);
  }
}
 
Example #13
Source File: MockFilePath.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public FilePath getParentPath() {
    File parent = f.getParentFile();
    if (parent == null) {
        return null;
    }
    return new MockFilePath(parent);
}
 
Example #14
Source File: VcsContextFactoryImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public FilePath createFilePathOn(@Nonnull File file) {
  String path = file.getPath();
  VirtualFile vf = LocalFileSystem.getInstance().findFileByPath(path);
  return createFilePath(path, vf != null ? vf.isDirectory() : file.isDirectory());
}
 
Example #15
Source File: MoveFileAction.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
public MoveFileAction(@NotNull String actionId, @NotNull FilePath source, @NotNull FilePath target,
        P4ChangelistId changelistId) {
    this.actionId = actionId;
    this.source = source;
    this.target = target;
    this.changelistId = changelistId;
}
 
Example #16
Source File: P4RollbackEnvironment.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
@Override
public void rollbackModifiedWithoutCheckout(List<VirtualFile> files, List<VcsException> exceptions, RollbackProgressListener listener) {
    List<FilePath> paths = new ArrayList<>(files.size());
    for (VirtualFile vf: files) {
        paths.add(VcsUtil.getFilePath(vf));
    }
    forceSync(paths, exceptions, listener);
}
 
Example #17
Source File: ApplyPatchForBaseRevisionTexts.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static ApplyPatchForBaseRevisionTexts create(final Project project, final VirtualFile file, final FilePath pathBeforeRename,
                                                     final TextFilePatch patch, final Getter<CharSequence> baseContents) {
  assert ! patch.isNewFile();
  final String beforeVersionId = patch.getBeforeVersionId();
  DefaultPatchBaseVersionProvider provider = null;
  if (beforeVersionId != null) {
    provider = new DefaultPatchBaseVersionProvider(project, file, beforeVersionId);
  }
  if (provider != null && provider.canProvideContent()) {
    return new ApplyPatchForBaseRevisionTexts(provider, pathBeforeRename, patch, file, baseContents);
  } else {
    return new ApplyPatchForBaseRevisionTexts(null, pathBeforeRename, patch, file, baseContents);
  }
}
 
Example #18
Source File: P4HistoryProvider.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canShowHistoryFor(@NotNull VirtualFile file) {
    if (file.isDirectory() || !file.isValid()) {
        return false;
    }
    FilePath fp = VcsUtil.getFilePath(file);
    return fp != null && getRootFor(fp) != null;
}
 
Example #19
Source File: VcsDirtyScopeImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean belongsTo(final FilePath path, final Consumer<AbstractVcs> vcsConsumer) {
  if (myProject.isDisposed()) return false;
  final VcsRoot rootObject = myVcsManager.getVcsRootObjectFor(path);
  if (vcsConsumer != null && rootObject != null) {
    vcsConsumer.consume(rootObject.getVcs());
  }
  if (rootObject == null || rootObject.getVcs() != myVcs) {
    return false;
  }

  final VirtualFile vcsRoot = rootObject.getPath();
  if (vcsRoot != null) {
    for (VirtualFile contentRoot : myAffectedContentRoots) {
      // since we don't know exact dirty mechanics, maybe we have 3 nested mappings like:
      // /root -> vcs1, /root/child -> vcs2, /root/child/inner -> vcs1, and we have file /root/child/inner/file,
      // mapping is detected as vcs1 with root /root/child/inner, but we could possibly have in scope
      // "affected root" -> /root with scope = /root recursively
      if (VfsUtilCore.isAncestor(contentRoot, vcsRoot, false)) {
        THashSet<FilePath> dirsByRoot = myDirtyDirectoriesRecursively.get(contentRoot);
        if (dirsByRoot != null) {
          for (FilePath filePath : dirsByRoot) {
            if (path.isUnder(filePath, false)) return true;
          }
        }
      }
    }
  }

  if (!myDirtyFiles.isEmpty()) {
    FilePath parent = path.getParentPath();
    return isInDirtyFiles(path) || isInDirtyFiles(parent);
  }

  return false;
}
 
Example #20
Source File: PlatformVcsPathPresenter.java    From consulo with Apache License 2.0 5 votes vote down vote up
public String getPresentableRelativePath(final ContentRevision fromRevision, final ContentRevision toRevision) {
  FilePath fromPath = fromRevision.getFile();
  FilePath toPath = toRevision.getFile();

  final RelativePathCalculator calculator =
    new RelativePathCalculator(toPath.getIOFile().getAbsolutePath(), fromPath.getIOFile().getAbsolutePath());
  calculator.execute();
  final String result = calculator.getResult();
  return (result == null) ? null : result.replace("/", File.separator);
}
 
Example #21
Source File: P4ChangelistListener.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
private boolean isUnderVcs(final FilePath path) {
    // Only files can be under VCS control.
    if (path.isDirectory()) {
        return false;
    }
    final AbstractVcs vcs = ProjectLevelVcsManager.getInstance(myProject).getVcsFor(path);
    return ((vcs != null) && (P4Vcs.VCS_NAME.equals(vcs.getName())));
}
 
Example #22
Source File: VcsDirtyScopeManagerProxy.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void filePathsDirty(@javax.annotation.Nullable final Collection<FilePath> filesDirty, @Nullable final Collection<FilePath> dirsRecursivelyDirty) {
  if (filesDirty != null) {
    myFiles.addAll(filesDirty);
  }
  if (dirsRecursivelyDirty != null) {
    myDirs.addAll(dirsRecursivelyDirty);
  }
  return;
}
 
Example #23
Source File: ShelveFilesAction.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
@NotNull
public File getCommonDir() {
    for (FilePath file : files) {
        FilePath parent = file.getParentPath();
        if (parent != null) {
            return parent.getIOFile();
        }
    }
    throw new RuntimeException("Unable to find a parent directory for " + files);
}
 
Example #24
Source File: VcsInvalidated.java    From consulo with Apache License 2.0 5 votes vote down vote up
public boolean isFileDirty(final FilePath fp) {
  if (myEverythingDirty) return true;

  for (VcsDirtyScope scope : myScopes) {
    if (scope.belongsTo(fp)) return true;
  }
  return false;
}
 
Example #25
Source File: FileActionMessage.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
public Event(@NotNull ClientServerRef ref, @NotNull FilePath file, @NotNull P4FileAction action,
        @Nullable P4FileType type, @NotNull P4CommandRunner.ClientAction<?> clientAction) {
    super(ref);
    this.file = file;
    this.action = action;
    this.type = type;
    this.clientAction = clientAction;
    this.state = ActionState.PENDING;
    this.result = null;
    this.problem = null;
    this.error = null;
}
 
Example #26
Source File: P4AnnotatedFileImpl.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
public P4AnnotatedFileImpl(@NotNull Project project,
        @NotNull FilePath file,
        @Nullable HistoryMessageFormatter formatter,
        @Nullable HistoryContentLoader loader,
        @NotNull AnnotateFileResult annotatedFileResult) {
    super(project);
    this.file = file;
    this.config = annotatedFileResult.getClientConfig();
    this.annotatedFile = annotatedFileResult.getAnnotatedFile();
    this.head = annotatedFileResult.getHeadRevision();
    this.content = annotatedFileResult.getContent();
    this.formatter = formatter;
    this.loader = loader;
}
 
Example #27
Source File: ContentRevisionCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
@javax.annotation.Nullable
@Contract("!null, _, _ -> !null")
public static String getAsString(@javax.annotation.Nullable byte[] bytes, @Nonnull FilePath file, @Nullable Charset charset) {
  if (bytes == null) return null;
  if (charset == null) {
    return bytesToString(file, bytes);
  }
  else {
    return CharsetToolkit.bytesToString(bytes, charset);
  }
}
 
Example #28
Source File: CacheStoreUpdateListener.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
private void sendCachedFiles(@NotNull ClientServerRef config)
        throws InterruptedException {
    FileCacheUpdatedMessage.send(project).onFilesCacheUpdated(new FileCacheUpdatedMessage.FileCacheUpdateEvent(
            pendingCache.readActions(config, (Function<Stream<ActionChoice>, FilePath[]>) actions -> {
                List<FilePath> files = new ArrayList<>();
                actions.forEach((a) -> files.addAll(a.getAffectedFiles()));
                return files.toArray(new FilePath[0]);
            })
    ));
}
 
Example #29
Source File: IgnoreFiles.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
public boolean isFileIgnored(@Nullable final FilePath file) {
    if (file == null || file.getVirtualFile() == null) {
        return true;
    }
    final VirtualFile ignoreFile = getIgnoreFileForPath(file.getVirtualFile());
    return isMatch(file, ignoreFile);
}
 
Example #30
Source File: ShowUpdatedDiffAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static byte[] loadContent(@Nonnull FilePath filePointer, @Nonnull Label label) throws DiffRequestProducerException {
  String path = filePointer.getPresentableUrl();
  ByteContent byteContent = label.getByteContent(FileUtil.toSystemIndependentName(path));

  if (byteContent == null || byteContent.isDirectory() || byteContent.getBytes() == null) {
    throw new DiffRequestProducerException("Can't load content");
  }

  return byteContent.getBytes();
}