Java Code Examples for com.intellij.openapi.vcs.LocalFilePath

The following examples show how to use com.intellij.openapi.vcs.LocalFilePath. These examples are extracted from open source projects. 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 Project: GitLink   Source File: RepositoryLocator.java    License: MIT License 5 votes vote down vote up
@NotNull
public Repository locate(@NotNull final VirtualFile file) throws RepositoryNotFoundException {
    LocalFilePath path = new LocalFilePath(file.getPath(), file.isDirectory());
    GitRepository repository = GitUtil.getRepositoryManager(project).getRepositoryForFileQuick(path);

    if (repository == null) {
        throw new RepositoryNotFoundException();
    }

    Preferences preferences = Preferences.getInstance(project);

    return new Repository(repository, preferences.getDefaultBranch(), preferences.remoteName);
}
 
Example 2
Source Project: azure-devops-intellij   Source File: TFVCUtil.java    License: MIT License 5 votes vote down vote up
/**
 * Will return only invalid paths for TFVC (i.e. paths containing dollar in any component, or $tf / .tf service
 * directory).
 * <p>
 * Performs a quick check (without checking every VCS mapping) because we often need this in performance-sensitive
 * contexts.
 */
public static Stream<FilePath> collectInvalidTFVCPaths(@NotNull TFSVcs vcs, @NotNull Stream<FilePath> paths) {
    ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(vcs.getProject());
    List<FilePath> mappings = vcsManager.getDirectoryMappings(vcs).stream()
            .map(mapping -> new LocalFilePath(mapping.getDirectory(), true))
            .collect(Collectors.toList());
    return paths.filter(path -> isInServiceDirectory(path)
        || mappings.stream().anyMatch(
                mapping -> hasIllegalDollarInAnyComponent(mapping, path)));
}
 
Example 3
Source Project: azure-devops-intellij   Source File: TFVCUtil.java    License: MIT License 5 votes vote down vote up
/**
 * Will check invalid paths for TFVC (i.e. paths containing dollar in any component, or $tf / .tf service
 * directory).
 * <p>
 * Performs a quick check (without checking every VCS mapping) because we often need this in performance-sensitive
 * contexts.
 */
public static boolean isInvalidTFVCPath(@NotNull TFSVcs vcs, @NotNull FilePath path) {
    if (isInServiceDirectory(path)) return true;

    ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(vcs.getProject());

    return vcsManager.getDirectoryMappings(vcs).stream()
            .map(mapping -> new LocalFilePath(mapping.getDirectory(), true))
            .anyMatch(mapping -> hasIllegalDollarInAnyComponent(mapping, path));
}
 
Example 4
Source Project: azure-devops-intellij   Source File: TFVCUtil.java    License: MIT License 5 votes vote down vote up
private static List<FilePath> getMappingsFromWorkspace(@NotNull Project project) {
    Workspace workspace = CommandUtils.getPartialWorkspace(project);
    if (workspace == null) {
        return Collections.emptyList();
    }

    List<FilePath> mappingPaths = new ArrayList<FilePath>();
    for (Workspace.Mapping mapping : workspace.getMappings()) {
        mappingPaths.add(new LocalFilePath(mapping.getLocalPath(), true));
    }

    return mappingPaths;
}
 
Example 5
Source Project: azure-devops-intellij   Source File: TfIgnoreUtil.java    License: MIT License 5 votes vote down vote up
/**
 * Will find existing .tfignore file that is near the target file. If .tfignore doesn't exists, then the location
 * will be proposed.
 *
 * @param mappings workspace mappings (to properly determine root location)
 * @param file target file
 * @return path to .tfignore (not necessary an existing file); will return null if place to create .tfignore was not
 * found
 */
@Nullable
public static File findNearestOrRootTfIgnore(@NotNull Collection<Workspace.Mapping> mappings, @NotNull File file) {
    List<LocalFilePath> localRoots = mappings.stream()
            .map(m -> new LocalFilePath(m.getLocalPath(), Files.isDirectory(Paths.get(m.getLocalPath()))))
            .collect(Collectors.toList());
    File potentialTfIgnore = null;
    while (file != null) {
        if (file.isDirectory()) {
            LocalFilePath filePath = new LocalFilePath(file.getAbsolutePath(), true);
            if (localRoots.stream().noneMatch(root -> filePath.isUnder(root, false))) {
                // Path is not under any of the root mappings; return last potential tfignore location that was
                // under mapping.
                return potentialTfIgnore;
            }

            File tfIgnoreInCurrentDir = new File(FileUtil.join(file.getAbsolutePath(), TFIGNORE_FILE_NAME));
            if (!tfIgnoreInCurrentDir.isDirectory()) {
                // Remember as a potential location for .tfignore if is not occupied by a directory.
                potentialTfIgnore = tfIgnoreInCurrentDir;
                if (potentialTfIgnore.isFile()) {
                    // Return as a best match if already exists as a file.
                    return potentialTfIgnore;
                }
            }
        }

        file = file.getParentFile();
    }

    // We've ended at the file system root; finish here.
    return null;
}
 
Example 6
Source Project: azure-devops-intellij   Source File: TFSFileListener.java    License: MIT License 5 votes vote down vote up
private void removeInvalidTFVCAddedFiles(List<VirtualFile> addedFiles) {
    Map<VirtualFile, FilePath> addedFilePaths = addedFiles.stream()
            .collect(Collectors.toMap(vf -> vf, vf -> new LocalFilePath(vf.getPath(), vf.isDirectory())));
    Set<FilePath> invalidPaths = TFVCUtil.collectInvalidTFVCPaths((TFSVcs) myVcs, addedFilePaths.values().stream())
            .collect(Collectors.toSet());

    addedFiles.removeIf(file -> invalidPaths.contains(addedFilePaths.get(file)));
}
 
Example 7
Source Project: azure-devops-intellij   Source File: TFVCUtilTest.java    License: MIT License 5 votes vote down vote up
@Test
public void isFileUnderTFVCMappingShouldTests() {
    assertTrue(TFVCUtil.isFileUnderTFVCMapping(mockProject, new LocalFilePath("/tmp/localPath/1.txt", false)));
    assertTrue(TFVCUtil.isFileUnderTFVCMapping(mockProject, new LocalFilePath("/tmp/localPath", true)));
    assertFalse(TFVCUtil.isFileUnderTFVCMapping(mockProject, new LocalFilePath("/tmp/localPath1", true)));
    assertFalse(TFVCUtil.isFileUnderTFVCMapping(mockProject, new LocalFilePath("/tmp/localPath1/1.txt", false)));
}
 
Example 8
Source Project: azure-devops-intellij   Source File: TFVCUtilTest.java    License: MIT License 5 votes vote down vote up
@Test
public void filterValidTFVCPathsTest() {
    List<FilePath> localFiles = Arrays.asList(
            new LocalFilePath("/tmp/localPath", true),
            new LocalFilePath("/tmp/localPath/1.txt", false));
    List<FilePath> nonLocalFiles = Arrays.asList(
            new LocalFilePath("/tmp/localPath1", true),
            new LocalFilePath("/tmp/localPath1/1.txt", false));
    List<FilePath> allPaths = Lists.newArrayList(Iterables.concat(localFiles, nonLocalFiles));
    List<String> localFilePaths = localFiles.stream().map(FilePath::getPath).collect(Collectors.toList());
    assertThat(TFVCUtil.filterValidTFVCPaths(mockProject, allPaths), is(localFilePaths));
}
 
Example 9
Source Project: azure-devops-intellij   Source File: TFVCUtilTest.java    License: MIT License 5 votes vote down vote up
@Test
public void filterDollarTFVCPathsTest() {
    List<FilePath> localFiles = Arrays.asList(
            new LocalFilePath("/tmp/localPath", true),
            new LocalFilePath("/tmp/localPath/1.txt", false));
    List<FilePath> dollarFiles = Arrays.asList(
            new LocalFilePath("/tmp/localPath/$1.txt", false),
            new LocalFilePath("/tmp/localPath/$1/1.txt", false),
            new LocalFilePath("/tmp/localPath/$1", true));
    List<FilePath> allPaths = Lists.newArrayList(Iterables.concat(localFiles, dollarFiles));
    List<String> localFilePaths = localFiles.stream().map(FilePath::getPath).collect(Collectors.toList());
    assertThat(TFVCUtil.filterValidTFVCPaths(mockProject, allPaths), is(localFilePaths));
}
 
Example 10
Source Project: azure-devops-intellij   Source File: TFVCUtilTest.java    License: MIT License 5 votes vote down vote up
@Test
public void isInServiceDirectoryTests() {
    assertFalse(TFVCUtil.isInServiceDirectory(new LocalFilePath("C:\\Temp", true)));
    assertFalse(TFVCUtil.isInServiceDirectory(new LocalFilePath("/tmp/_tf/xxx", true)));
    assertTrue(TFVCUtil.isInServiceDirectory(new LocalFilePath("/tmp/$tf/xxx", true)));
    assertTrue(TFVCUtil.isInServiceDirectory(new LocalFilePath("/tmp/.tf/xxx", true)));
    assertTrue(TFVCUtil.isInServiceDirectory(new LocalFilePath("/tmp/.tf", false)));
}
 
Example 11
Source Project: azure-devops-intellij   Source File: TfvcRootCache.java    License: MIT License 4 votes vote down vote up
private static void assertNoServiceDirectory(Path path) {
    if (TFVCUtil.isInServiceDirectory(new LocalFilePath(path.toString(), true))) {
        throw new InvalidPathException(path.toString(), "Path contains TFVC service directory name");
    }
}
 
Example 12
Source Project: azure-devops-intellij   Source File: TFSFileSystemListener.java    License: MIT License 4 votes vote down vote up
/**
 * Move and rename logic the same
 *
 * @param oldFile
 * @param newPath
 * @return
 * @throws IOException
 */
private boolean renameOrMove(final VirtualFile oldFile, final String newPath) throws IOException {
    final TFSVcs vcs = VcsHelper.getTFSVcsByPath(oldFile);
    // no TFSVcs so not a TFVC project so do nothing
    if (vcs == null) {
        ourLogger.info("Not a TFVC project so not doing a TFVC rename/move");
        return false;
    }

    boolean isDirectory = oldFile.isDirectory();
    LocalFilePath oldFilePath = new LocalFilePath(oldFile.getPath(), isDirectory);
    if (TFVCUtil.isInvalidTFVCPath(vcs, oldFilePath)) {
        ourLogger.warn("Invalid old TFVC path, ignore rename or move: {}", oldFilePath);
        return false;
    }

    LocalFilePath newFilePath = new LocalFilePath(newPath, isDirectory);
    if (TFVCUtil.isInvalidTFVCPath(vcs, newFilePath)) {
        ourLogger.warn("Invalid new TFVC path, ignore rename or move: {}", newFilePath);
        return false;
    }

    final String oldPath = oldFile.getPath();
    try {
        // a single file may have 0, 1, or 2 pending changes to it
        // 0 - file has not been touched in the local workspace
        // 1 - file has versioned OR unversioned changes
        // 2 - file has versioned AND unversioned changes (rare but can happen)
        final List<PendingChange> pendingChanges = new ArrayList<>(2);
        pendingChanges.addAll(
                CommandUtils.getStatusForFiles(
                        myProject,
                        vcs.getServerContext(true),
                        ImmutableList.of(oldPath)));

        // ** Rename logic **
        // If 1 change and it's a candidate add that means it's a new unversioned file so rename thru the file system
        // Anything else can be renamed
        // Deleted files should not be at this point since IDE disables rename option for them
        if (pendingChanges.size() == 1 && pendingChanges.get(0).isCandidate() && pendingChanges.get(0).getChangeTypes().contains(ServerStatusType.ADD)) {
            ourLogger.info("Renaming unversioned file thru file system");
            return false;
        } else {
            ourLogger.info("Renaming file thru tf commandline");
            CommandUtils.renameFile(vcs.getServerContext(true), oldPath, newPath);
            return true;
        }
    } catch (Throwable t) {
        ourLogger.warn("renameOrMove experienced a failure while trying to rename a file", t);
        throw new IOException(t);
    }
}
 
Example 13
Source Project: GitToolBox   Source File: GtUtil.java    License: Apache License 2.0 4 votes vote down vote up
@NotNull
public static FilePath localFilePath(@NotNull VirtualFile file) {
  return new LocalFilePath(file.getPath(), file.isDirectory());
}
 
Example 14
Source Project: Crucible4IDEA   Source File: CruciblePanel.java    License: MIT License 4 votes vote down vote up
public void openDetailsToolWindow(@NotNull final Review review) {
  final ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(CrucibleBundle.message("crucible.toolwindow.id"));
  final ContentManager contentManager = toolWindow.getContentManager();
  final Content foundContent = contentManager.findContent("Details for " + review.getPermaId());
  if (foundContent != null) {
    contentManager.setSelectedContent(foundContent);
    return;
  }

  final DetailsPanel details = new DetailsPanel(myProject, review);
  final Content content = ContentFactory.SERVICE.getInstance().createContent(details,
                                                                             "Details for " + review.getPermaId(), false);
  contentManager.addContent(content);
  contentManager.setSelectedContent(content);
  details.setBusy(true);

  ApplicationManager.getApplication().invokeLater(new Runnable() {
    @Override
    public void run() {
      final List<CommittedChangeList> list = new ArrayList<CommittedChangeList>();
      final ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(myProject);
      final String projectDir = myProject.getBasePath();
      final AbstractVcs vcsFor = vcsManager.getVcsFor(new LocalFilePath(Objects.requireNonNull(projectDir), true));
      if (vcsFor == null) return;
      final Set<ReviewItem> reviewItems = review.getReviewItems();
      final Set<String> loadedRevisions = new HashSet<String>();

      final Map<String, VirtualFile> hash = CrucibleManager.getInstance(myProject).getRepoHash();
      for (ReviewItem reviewItem : reviewItems) {
        final String root = hash.containsKey(reviewItem.getRepo()) ? hash.get(reviewItem.getRepo()).getPath() : projectDir;
        try {
          list.addAll(reviewItem.loadChangeLists(myProject, vcsFor, loadedRevisions, VcsUtil.getFilePath(root)));
        }
        catch (VcsException e) {
          LOG.error(e);
        }
      }
      details.updateCommitsList(list);
      details.setBusy(false);

    }
  }, ModalityState.stateForComponent(toolWindow.getComponent()));
}
 
Example 15
Source Project: Crucible4IDEA   Source File: CrucibleApi.java    License: MIT License 4 votes vote down vote up
@Nullable
private static ReviewItem parsePatchReviewItem(ReviewItemRaw raw, Project project, CrucibleSession crucibleSession) throws IOException {
  final String id = raw.permId.id;
  final String toPath = raw.toPath;
  String patchUrl = raw.patchUrl;
  String file = crucibleSession.downloadFile(patchUrl);

  List<TextFilePatch> patchTexts;
  try {
    patchTexts = new PatchReader(file).readTextPatches();
  }
  catch (PatchSyntaxException e) {
    throw new IOException(e);
  }

  List<AbstractFilePatchInProgress> patches = new MatchPatchPaths(project).execute(patchTexts);

  if (patches.isEmpty()) {
    LOG.error("No patches generated for the following patch texts: " + patchTexts);
    return null;
  }

  AbstractFilePatchInProgress patchForItem = findBestMatchingPatchByPath(toPath, patches);
  if (!(patchForItem instanceof TextFilePatchInProgress)) {
    LOG.error("Patches is not instance of TextFilePatchInProgress");
    return null;
  }

  File base = patchForItem.getIoCurrentBase();
  if (base == null) {
    LOG.error("No base for the patch " + patchForItem.getPatch());
    return null;
  }

  final VirtualFile repo =
    ProjectLevelVcsManager.getInstance(project).getVcsRootFor(new LocalFilePath(base.getAbsolutePath(), base.isDirectory()));
  if (repo == null) {
    LOG.error("Couldn't find repository for base " + base);
    return null;
  }

  Map.Entry<String, VirtualFile> repoEntry = ContainerUtil.find(crucibleSession.getRepoHash().entrySet(),
                                                                new Condition<Map.Entry<String, VirtualFile>>() {
                                                                  @Override
                                                                  public boolean value(Map.Entry<String, VirtualFile> entry) {
                                                                    return entry.getValue().equals(repo);
                                                                  }
                                                                });

  if (repoEntry == null) {
    LOG.error("Couldn't find repository name for root " + repo);
    return null;
  }
  String key = repoEntry.getKey();
  return new PatchReviewItem(id, ((TextFilePatchInProgress)patchForItem).getNewContentRevision().getFile().getPath(),
                             key, patches, patchUrl.substring(patchUrl.lastIndexOf("/") + 1), "",
                             raw.authorName, new Date(raw.commitDate));
}
 
Example 16
Source Project: consulo   Source File: VcsContextFactoryImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public FilePath createFilePath(@Nonnull String path, boolean isDirectory) {
  return new LocalFilePath(path, isDirectory);
}