Java Code Examples for com.intellij.vcsUtil.VcsUtil#getFilePath()

The following examples show how to use com.intellij.vcsUtil.VcsUtil#getFilePath() . 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: PluginSetup.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
public ClientConfigRoot addClientConfigRoot(TemporaryFolder tmp, String clientRootDir) {
    File base = tmp.newFile(clientRootDir);
    if (!base.mkdirs()) {
        throw new RuntimeException("Could not create directory " + base);
    }

    MockConfigPart cp1 = new MockConfigPart()
            .withClientname("cn")
            .withUsername("u")
            .withServerName("s:123");
    ClientConfig cc = ClientConfig.createFrom(ServerConfig.createFrom(cp1), cp1);
    FilePath fp = VcsUtil.getFilePath(base);
    VirtualFile rootDir = Objects.requireNonNull(fp.getVirtualFile());
    registry.addClientConfig(cc, rootDir);
    roots.add(rootDir);
    return Objects.requireNonNull(registry.getClientFor(rootDir));
}
 
Example 2
Source File: TreeModelBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static FilePath getPathForObject(@Nonnull Object o) {
  if (o instanceof Change) {
    return ChangesUtil.getFilePath((Change)o);
  }
  else if (o instanceof VirtualFile) {
    return VcsUtil.getFilePath((VirtualFile)o);
  }
  else if (o instanceof FilePath) {
    return (FilePath)o;
  }
  else if (o instanceof ChangesBrowserLogicallyLockedFile) {
    return VcsUtil.getFilePath(((ChangesBrowserLogicallyLockedFile)o).getUserObject());
  }
  else if (o instanceof LocallyDeletedChange) {
    return ((LocallyDeletedChange)o).getPath();
  }

  throw new IllegalArgumentException("Unknown type - " + o.getClass());
}
 
Example 3
Source File: VcsSelectionHistoryDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void actionPerformed(AnActionEvent e) {
  VcsFileRevision revision = myList.getSelectedObject();
  if (revision == null) return;

  FilePath filePath = VcsUtil.getFilePath(myFile);

  getDiffHandler().showDiffForTwo(myProject, filePath, revision, myLocalRevision);
}
 
Example 4
Source File: P4LocalFileImpl.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
private static FilePath getLocalFile(IFileSpec spec) {
    String path;
    if (spec.getLocalPath() != null) {
        path = spec.getLocalPath().getPathString();
    } else if (spec.getClientPath() != null) {
        path = spec.getClientPath().getPathString();
    } else {
        throw new IllegalArgumentException("FileSpec does not have a local component: " + spec);
    }
    return VcsUtil.getFilePath(path, false);
}
 
Example 5
Source File: FileTreeUtil.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param path   child path
 * @param parent parent path
 * @return < 0 if the path is not under the parent, 0 if the path is the parent, or the
 *      number of directories under the parent the path is.
 */
public static int getPathDepth(@NotNull FilePath path, @Nullable VirtualFile parent) {
    if (parent == null) {
        return -1;
    }
    FilePath parentFile = VcsUtil.getFilePath(parent);
    return getPathDepth(path, parentFile);
}
 
Example 6
Source File: VcsSelectionHistoryDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void actionPerformed(AnActionEvent e) {
  IntPair range = getSelectedRevisionsRange();

  VcsFileRevision beforeRevision = range.val2 < myRevisions.size() ? myRevisions.get(range.val2) : VcsFileRevision.NULL;
  VcsFileRevision afterRevision = myRevisions.get(range.val1);

  FilePath filePath = VcsUtil.getFilePath(myFile);

  if (range.val2 - range.val1 > 1) {
    getDiffHandler().showDiffForTwo(myProject, filePath, beforeRevision, afterRevision);
  }
  else {
    getDiffHandler().showDiffForOne(e, myProject, filePath, beforeRevision, afterRevision);
  }
}
 
Example 7
Source File: BinaryFilePatchInProgress.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public ContentRevision getNewContentRevision() {
  if (FilePatchStatus.DELETED.equals(myStatus)) return null;

  if (myNewContentRevision != null) return myNewContentRevision;
  if (myPatch.getAfterFileName() != null) {
    final FilePath newFilePath = FilePatchStatus.ADDED.equals(myStatus) ? VcsUtil.getFilePath(myIoCurrentBase, false)
                                                                        : detectNewFilePathForMovedOrModified();
    myNewContentRevision = new ShelvedBinaryContentRevision(newFilePath, myPatch.getShelvedBinaryFile().SHELVED_PATH);
  }
  return myNewContentRevision;
}
 
Example 8
Source File: VersionControlPath.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
public static FilePath getCombinedLocalPath(final FilePath localPathBase,
                                            final String serverPathBase,
                                            final String serverPath,
                                            final boolean isDirectory) {
    String serverPathBaseString = FileUtil.toSystemDependentName(serverPathBase);
    String serverPathString = FileUtil.toSystemDependentName(serverPath);
    File localFile = new File(localPathBase.getIOFile(), serverPathString.substring(serverPathBaseString.length()));
    return VcsUtil.getFilePath(localFile, isDirectory);
}
 
Example 9
Source File: TreeModelBuilder.java    From consulo with Apache License 2.0 4 votes vote down vote up
@javax.annotation.Nullable
private ChangesBrowserNode createPathNode(@Nonnull StaticFilePath path) {
  FilePath filePath = path.getVf() == null ? VcsUtil.getFilePath(path.getPath(), true) : VcsUtil.getFilePath(path.getVf());
  return ChangesBrowserNode.create(myProject, filePath);
}
 
Example 10
Source File: P4AnnotationProvider.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
@NotNull
@Override
public FileAnnotation annotate(@NotNull VirtualFile file, VcsFileRevision revision) throws VcsException {
    if (ApplicationManager.getApplication().isDispatchThread()) {
        LOG.info("Fetching annotation from the EDT");
        // TODO bundle for error messages
        throw new VcsException("Does not support fetching annotations from the EDT.");
    }
    // TODO use a better location for this constant.
    int rev = IFileSpec.HEAD_REVISION;
    if (revision != null) {
        VcsRevisionNumber revNumber = revision.getRevisionNumber();
        if (revNumber instanceof VcsRevisionNumber.Int) {
            rev = ((VcsRevisionNumber.Int) revNumber).getValue();
        } else {
            LOG.warn("Unknown file revision " + revision + " for " + file + "; using head revision");
        }
    }
    FilePath fp = VcsUtil.getFilePath(file);
    if (fp == null) {
        // TODO bundle for error messages
        throw new VcsException("No known Perforce server for " + file);
    }
    ProjectConfigRegistry registry = ProjectConfigRegistry.getInstance(project);
    if (registry == null) {
        // TODO bundle for error messages
        throw new VcsException("Project not configured for showing annotations");
    }
    ClientConfigRoot client = registry.getClientFor(file);
    if (client == null) {
        // TODO bundle for error messages
        throw new VcsException("No known Perforce server for " + file);
    }
    String clientname = client.getClientConfig().getClientname();
    if (clientname == null) {
        // TODO bundle for error messages
        throw new VcsException("No workspace name set for Perforce connection for " + file);
    }
    try {
        return new P4AnnotatedFileImpl(project, fp,
                messageFormatter, contentLoader,
                P4ServerComponent
                    .query(project, client.getClientConfig(), new AnnotateFileQuery(fp, rev))
                    .blockingGet(UserProjectPreferences.getLockWaitTimeoutMillis(project), TimeUnit.MILLISECONDS));
    } catch (InterruptedException e) {
        throw new VcsInterruptedException(e);
    }
}
 
Example 11
Source File: P4CommittedChangesProvider.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
private P4RemoteFileContentRevision readContentRevision(DataInput dataInput)
        throws IOException {
    // 1. Is "revision" set - int
    int isSet = dataInput.readInt();
    if (isSet == 1) {
        // 2. depot file
        // 2.a. path - utf
        String depotPath = dataInput.readUTF();
        // 2.b. display name - utf
        String depotDisplayName = dataInput.readUTF();
        // 2.c. is local path non-null - int
        String localPath;
        int hasLocalPath = dataInput.readInt();
        if (hasLocalPath == 0) {
            localPath = null;
        } else {
            // 2.c.i. local path - utf
            localPath = dataInput.readUTF();
        }
        P4RemoteFile file = new P4RemoteFileImpl(depotPath, depotDisplayName, localPath);

        // 3. file path
        FilePath path;
        // 3.a. is file path used - int
        int hasFilePath = dataInput.readInt();
        if (hasFilePath == 0) {
            path = null;
        } else {
            // 3.a.i. file path - utf
            path = VcsUtil.getFilePath(dataInput.readUTF());
        }

        // 4. Revision - int
        VcsRevisionNumber.Int rev = new VcsRevisionNumber.Int(dataInput.readInt());

        // 5. Charset - utf
        Charset charset = Charset.forName(dataInput.readUTF());

        return P4RemoteFileContentRevision.delayCreation(project, file, path, rev, loader, charset);
    } else {
        return null;
    }
}
 
Example 12
Source File: MoveFileTest.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
@ExtendWith(TemporaryFolderExtension.class)
@Test
void move_sourceEdited(TemporaryFolder tmpDir)
        throws IOException {
    idea.useInlineThreading(null);
    MockConfigPart part = new MockConfigPart()
            // By using the RSH port, it means that the connection will be kept open
            // (NTS connection).  By keeping the connection open until explicitly
            // disconnected, this will indirectly be testing that the
            // SimpleConnectionManager closes the connection.
            .withServerName(server.getRshUrl())
            .withUsername(server.getUser())
            .withNoPassword()
            .withClientname("client1");
    final ServerConfig serverConfig = ServerConfig.createFrom(part);
    final ClientConfig clientConfig = ClientConfig.createFrom(serverConfig, part);
    final File clientRoot = tmpDir.newFile("clientRoot");
    final FilePath fromFile = VcsUtil.getFilePath(touchFile(clientRoot, "abc.txt"));
    final FilePath toFile = VcsUtil.getFilePath(touchFile(clientRoot, "xyz.txt"));
    final P4CommandUtil cmd = new P4CommandUtil();
    final MoveFile moveFile = new MoveFile(idea.getMockProject(), cmd);

    setContents(fromFile, "initial");
    assertEquals("initial", getContents(fromFile));
    assertTrue(toFile.getIOFile().delete());

    setupClient(clientConfig, tmpDir, clientRoot)
            .mapAsync((runner) ->
                    runner.withConnection(clientConfig, (client) -> {
                        List<IFileSpec> srcFiles = FileSpecBuildUtil.forFilePaths(fromFile);
                        List<IFileSpec> msgs = cmd.addFiles(client, srcFiles, null, null, null);
                        MessageStatusUtil.throwIfError(msgs);
                        IChangelist change = client.getServer().getChangelist(IChangelist.DEFAULT);
                        P4ChangelistId clId = createChangelistId(change, clientConfig);
                        change.setDescription("add initial file");
                        msgs = cmd.submitChangelist(client, null, null, change, Collections.singletonList(fromFile));
                        MessageStatusUtil.throwIfError(msgs);

                        // Open for edit source.
                        msgs = client.editFiles(srcFiles, new EditFilesOptions());
                        MessageStatusUtil.throwIfError(msgs);

                        // Alter contents of source.
                        setContents(fromFile, "updated");
                        assertEquals("updated", getContents(fromFile));

                        MoveFileResult res =
                                moveFile.moveFile(client, clientConfig,
                                        new MoveFileAction(fromFile, toFile, clId));
                        msgs = res.getServerMessages();
                        assertSize(1, msgs);
                        assertNull(msgs.get(0).getStatusMessage());
                        assertEquals(toFile.getPath(), msgs.get(0).getLocalPathString());

                        // The move operation is setup to not perform the underlying move, that is left to the IDE.
                        assertTrue(fromFile.getIOFile().exists());
                        assertFalse(toFile.getIOFile().exists());

                        return null;
                    })
            )
            .whenFailed(Assertions::fail);
}
 
Example 13
Source File: RemoteFileUtil.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
static FilePath createRelativePath(@NotNull FilePath localFile, @NotNull P4RemoteFile localDepot,
        P4RemoteFile remote) {
    List<String> localDepotPaths = splitDepotPaths(localDepot.getDisplayName());
    List<String> remoteDepotPaths = splitDepotPaths(remote.getDisplayName());

    // Count depot path parts forward to see up to what part do they differ.
    // Then, the distance from that point to the end of the local depot paths is the
    // stuff to cut out of the local file paths, and add on after that the parts after the
    // shared remote depot paths.

    int diffPos = 0;
    while (diffPos < localDepotPaths.size() && diffPos < remoteDepotPaths.size()
            && localDepotPaths.get(diffPos).equals(remoteDepotPaths.get(diffPos))) {
        diffPos++;
    }
    if (diffPos <= 0) {
        // Everything is different
        if (LOG.isDebugEnabled()) {
            LOG.debug("No similarities between " + localDepot + " and " + remote.getDepotPath());
        }
        return null;
    }
    // We now have the number of shared path parts between local and remote.
    // We then count backwards from the end of the local depot path to find
    // what is the base path.
    List<String> localFilePaths = splitFilePaths(localFile);
    int localRelativeSize =
            // The source we're trying to find the final length of
            localFilePaths.size() - (
                // The relative difference path, think of this as a ".."
                localDepotPaths.size() - diffPos
            );
    // and pop those off of the paths...
    while (localFilePaths.size() > localRelativeSize) {
        localFilePaths.remove(localFilePaths.size() - 1);
    }

    // Now we stick on the different paths for the remote.
    for (int i = diffPos; i < remoteDepotPaths.size(); i++) {
        localFilePaths.add(remoteDepotPaths.get(i));
    }

    StringBuilder ret = new StringBuilder();
    boolean first = true;
    for (String part : localFilePaths) {
        if (first) {
            first = false;
        } else {
            ret.append(File.separator);
        }
        ret.append(part);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Transformed local " + localDepot + " + remote " + remote + " -> " + ret);
    }
    return VcsUtil.getFilePath(ret.toString());
}
 
Example 14
Source File: ChangeListManagerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isIgnoredFile(@Nonnull VirtualFile file) {
  FilePath filePath = VcsUtil.getFilePath(file);
  return ContainerUtil.exists(IgnoredFileProvider.IGNORE_FILE.getExtensionList(), it -> it.isIgnoredFile(myProject, filePath));
}
 
Example 15
Source File: OpenFileStatusTest.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
@ExtendWith(TemporaryFolderExtension.class)
@Test
void statusSort_move(TemporaryFolder tmpDir)
        throws IOException {
    idea.useInlineThreading(null);
    MockConfigPart part = new MockConfigPart()
            // By using the RSH port, it means that the connection will be kept open
            // (NTS connection).  By keeping the connection open until explicitly
            // disconnected, this will indirectly be testing that the
            // SimpleConnectionManager closes the connection.
            .withServerName(server.getRshUrl())
            .withUsername(server.getUser())
            .withNoPassword()
            .withClientname("client1");
    final ServerConfig serverConfig = ServerConfig.createFrom(part);
    final ClientConfig clientConfig = ClientConfig.createFrom(serverConfig, part);
    final File clientRoot = tmpDir.newFile("clientRoot");
    final FilePath srcFile = VcsUtil.getFilePath(touchFile(clientRoot, "abc.txt"));
    final FilePath tgtFile = VcsUtil.getFilePath(touchFile(clientRoot, "def.txt"));
    final P4CommandUtil cmd = new P4CommandUtil();

    setupClient(clientConfig, tmpDir, clientRoot)
            .mapAsync((runner) ->
                    runner.withConnection(clientConfig, (client) -> {
                        // Add and submit the file to Perforce
                        List<IFileSpec> addFiles = FileSpecBuildUtil.forFilePaths(srcFile);
                        List<IFileSpec> msgs = cmd.addFiles(client, addFiles, null, null, null);
                        MessageStatusUtil.throwIfError(msgs);
                        IChangelist change = client.getServer().getChangelist(IChangelist.DEFAULT);
                        change.setDescription("add initial file");
                        msgs = cmd.submitChangelist(client, null, null, change, Collections.singletonList(srcFile));
                        MessageStatusUtil.throwIfError(msgs);

                        // Move, which is a two step process.
                        List<IFileSpec> srcFiles = FileSpecBuildUtil.escapedForFilePaths(srcFile);
                        List<IFileSpec> tgtFiles = FileSpecBuildUtil.forFilePaths(tgtFile);
                        msgs = cmd.editFiles(client, srcFiles, null, null, null);
                        MessageStatusUtil.throwIfError(msgs);
                        msgs = cmd.moveFile(client, srcFiles.get(0), tgtFiles.get(0), null);
                        MessageStatusUtil.throwIfError(msgs);

                        List<IFileSpec> allFiles = Arrays.asList(srcFiles.get(0), tgtFiles.get(0));

                        // Get the status
                        return new OpenFileStatus(cmd.getFileDetailsForOpenedSpecs(client.getServer(),
                                allFiles, 1000));
                    })
            )
            .whenCompleted((r) -> {
                assertSize(1, r.getAdd());
                assertEmpty(r.getMessages());
                assertEmpty(r.getFilesWithMessages());
                assertSize(1, r.getMoveMap().keySet());
                assertSize(1, r.getDelete());
                assertEmpty(r.getEdit());
                assertEmpty(r.getSkipped());
                assertSize(2, r.getOpen());
                assertEquals(2, r.getOpenedCount());

                IExtendedFileSpec spec = r.getDelete().iterator().next();
                assertNotNull(spec);
                assertEquals(spec.getDepotPathString(), "//depot/abc.txt");
                assertEquals(spec.getClientPathString(), "//client1/abc.txt");
                assertEquals(spec.getLocalPathString(), srcFile.getPath());

                spec = r.getAdd().iterator().next();
                assertNotNull(spec);
                assertEquals(spec.getDepotPathString(), "//depot/def.txt");
                assertEquals(spec.getClientPathString(), "//client1/def.txt");
                assertEquals(spec.getLocalPathString(), tgtFile.getPath());

                Map.Entry<IExtendedFileSpec, IExtendedFileSpec> moveSpec =
                        r.getMoveMap().entrySet().iterator().next();
                assertNotNull(moveSpec.getKey());
                assertNotNull(moveSpec.getValue());
                assertEquals(moveSpec.getKey().getDepotPathString(), "//depot/abc.txt");
                assertEquals(moveSpec.getValue().getDepotPathString(), "//depot/def.txt");
            })
            .whenFailed(Assertions::fail);
}
 
Example 16
Source File: P4VFSListener.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
@Override
protected void performAdding(
        @NotNull final Collection<VirtualFile> addedFiles,
        @NotNull final Map<VirtualFile, VirtualFile> copyFromMap) {

    // TODO all add requests must go through the IgnoreFileSet.

    // Copies are handled as add commands, so we don't need to worry about
    // performing integrations - this is the common use case desired by the
    // user - they want to use another file as a template for work.
    // This could eventually be supported as a feature flag if the user really
    // wants it.  If they are implemented, then the "add" files should first be
    // pruned of the "integrate" files.

    // Bug #102: The keys in the "copyFromMap" will also be in the "addedFiles"
    // list.  If copy rather than integrate is supported, this loop will need to be
    // changed.
    Map<ClientServerRef, P4ChangelistId> activeChangelistIds = getActiveChangelistIds();
    for (VirtualFile file : addedFiles) {
        if (file.isDirectory()) {
            LOG.warn("Attempted to add a directory " + file);
            continue;
        }
        ClientConfigRoot root = getClientFor(file);
        if (root != null) {
            FilePath fp = VcsUtil.getFilePath(file);
            P4ChangelistId id = getActiveChangelistFor(root, activeChangelistIds);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Opening for add/edit: " + fp + " (@" + id + ")");
            }
            P4ServerComponent
            .perform(myProject, root.getClientConfig(),
                    new AddEditAction(fp, getFileType(fp), id, (String) null))
            .whenAnyState(() -> {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Completed call to add " + addedFiles + "; copy " + copyFromMap);
                }
            });
        } else {
            LOG.info("Skipped adding " + file + "; not under known P4 client");
        }
    }
}
 
Example 17
Source File: UpdateInfoTree.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static FilePath getFilePath(@Nonnull VirtualFilePointer filePointer) {
  return VcsUtil.getFilePath(filePointer.getPresentableUrl(), false);
}
 
Example 18
Source File: VcsCurrentRevisionProxy.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public FilePath getFile() {
  return VcsUtil.getFilePath(myFile);
}
 
Example 19
Source File: ApplyPatchContext.java    From consulo with Apache License 2.0 4 votes vote down vote up
public FilePath getPathBeforeRename(final VirtualFile file) {
  final FilePath path = myPathsBeforeRename.get(file);
  if (path != null) return path;
  return VcsUtil.getFilePath(file);
}
 
Example 20
Source File: TFSChangeList.java    From azure-devops-intellij with MIT License 4 votes vote down vote up
private static FilePath readPath(final DataInput stream) throws IOException {
    return VcsUtil.getFilePath(stream.readUTF(), stream.readBoolean());
}