コード例 #1
0
  @Override
  public <S> List<S> filterUniqueRoots(
      final List<S> in, final Convertor<S, VirtualFile> convertor) {
    Collections.sort(
        in, new ComparatorDelegate<S, VirtualFile>(convertor, FilePathComparator.getInstance()));

    for (int i = 1; i < in.size(); i++) {
      final S sChild = in.get(i);
      final VirtualFile child = convertor.convert(sChild);
      final VirtualFile childRoot = HgUtil.getHgRootOrNull(myProject, child);
      if (childRoot == null) {
        continue;
      }
      for (int j = i - 1; j >= 0; --j) {
        final S sParent = in.get(j);
        final VirtualFile parent = convertor.convert(sParent);
        // if the parent is an ancestor of the child and that they share common root, the child is
        // removed
        if (VfsUtil.isAncestor(parent, child, false)
            && VfsUtil.isAncestor(childRoot, parent, false)) {
          in.remove(i);
          //noinspection AssignmentToForLoopParameter
          --i;
          break;
        }
      }
    }
    return in;
  }
  /**
   * @see fr.adrienbrault.idea.symfony2plugin.templating.util.TwigUtil#getTemplateNameByOverwrite
   */
  public void testTemplateOverwriteNameGeneration() {

    if (true == true) {
      return;
    }

    assertEquals(
        "TwigUtilIntegrationBundle:layout.html.twig",
        TwigUtil.getTemplateNameByOverwrite(
            getProject(),
            VfsUtil.findRelativeFile(
                getProject().getBaseDir(),
                "app/Resources/TwigUtilIntegrationBundle/views/layout.html.twig".split("/"))));

    assertEquals(
        "TwigUtilIntegrationBundle:Foo/layout.html.twig",
        TwigUtil.getTemplateNameByOverwrite(
            getProject(),
            VfsUtil.findRelativeFile(
                getProject().getBaseDir(),
                "app/Resources/TwigUtilIntegrationBundle/views/Foo/layout.html.twig".split("/"))));

    assertEquals(
        "TwigUtilIntegrationBundle:Foo/Bar/layout.html.twig",
        TwigUtil.getTemplateNameByOverwrite(
            getProject(),
            VfsUtil.findRelativeFile(
                getProject().getBaseDir(),
                "app/Resources/TwigUtilIntegrationBundle/views/Foo/Bar/layout.html.twig"
                    .split("/"))));
  }
コード例 #3
0
ファイル: TestAll.java プロジェクト: rgb/intellij-community
 public static String[] getClassRoots() {
   String testRoots = System.getProperty("test.roots");
   if (testRoots != null) {
     System.out.println(
         "Collecting tests from roots specified by test.roots property: " + testRoots);
     return testRoots.split(";");
   }
   final String[] roots = ExternalClasspathClassLoader.getRoots();
   if (roots != null) {
     System.out.println(
         "Collecting tests from roots specified by classpath.file property: "
             + Arrays.toString(roots));
     return roots;
   } else {
     final ClassLoader loader = TestAll.class.getClassLoader();
     if (loader instanceof URLClassLoader) {
       final URL[] urls = ((URLClassLoader) loader).getURLs();
       final String[] classLoaderRoots = new String[urls.length];
       for (int i = 0; i < urls.length; i++) {
         classLoaderRoots[i] = VfsUtil.urlToPath(VfsUtil.convertFromUrl(urls[i]));
       }
       System.out.println(
           "Collecting tests from classloader: " + Arrays.toString(classLoaderRoots));
       return classLoaderRoots;
     }
     return System.getProperty("java.class.path").split(File.pathSeparator);
   }
 }
コード例 #4
0
  @NotNull
  private static String getFileFqn(final PsiFile file) {
    final VirtualFile virtualFile = file.getVirtualFile();
    if (virtualFile == null) {
      return file.getName();
    }
    final Project project = file.getProject();
    final LogicalRoot logicalRoot =
        LogicalRootsManager.getLogicalRootsManager(project).findLogicalRoot(virtualFile);
    if (logicalRoot != null) {
      String logical =
          FileUtil.toSystemIndependentName(
              VfsUtil.virtualToIoFile(logicalRoot.getVirtualFile()).getPath());
      String path =
          FileUtil.toSystemIndependentName(VfsUtil.virtualToIoFile(virtualFile).getPath());
      return "/" + FileUtil.getRelativePath(logical, path, '/');
    }

    final VirtualFile contentRoot =
        ProjectRootManager.getInstance(project).getFileIndex().getContentRootForFile(virtualFile);
    if (contentRoot != null) {
      return "/"
          + FileUtil.getRelativePath(
              VfsUtil.virtualToIoFile(contentRoot), VfsUtil.virtualToIoFile(virtualFile));
    }
    return virtualFile.getPath();
  }
コード例 #5
0
 private static boolean fileExists(@NotNull VirtualFile bundleDir, @NotNull String className) {
   return VfsUtil.findRelativeFile(
               bundleDir, "DependencyInjection", "Compiler", className + ".php")
           != null
       || VfsUtil.findRelativeFile(
               bundleDir, "DependencyInjection", "CompilerPass", className + ".php")
           != null;
 }
コード例 #6
0
  public void testToUri() {
    if (!SystemInfo.isWindows) {
      assertEquals("file:///asd", VfsUtil.toUri(new File("/asd")).toASCIIString());
      assertEquals("file:///asd%20/sd", VfsUtil.toUri(new File("/asd /sd")).toASCIIString());
    }

    URI uri = VfsUtil.toUri("file:///asd");
    assertNotNull(uri);
    assertEquals("file", uri.getScheme());
    assertEquals("/asd", uri.getPath());

    uri = VfsUtil.toUri("file:///asd/ ads/ad#test");
    assertNotNull(uri);
    assertEquals("file", uri.getScheme());
    assertEquals("/asd/ ads/ad", uri.getPath());
    assertEquals("test", uri.getFragment());

    uri = VfsUtil.toUri("file:///asd/ ads/ad#");
    assertNotNull(uri);
    assertEquals("file:///asd/%20ads/ad#", uri.toString());

    uri = VfsUtil.toUri("mailto:[email protected]");
    assertNotNull(uri);
    assertEquals("*****@*****.**", uri.getSchemeSpecificPart());

    if (SystemInfo.isWindows) {
      uri = VfsUtil.toUri("file://C:/p");
      assertNotNull(uri);
      assertEquals("file", uri.getScheme());
      assertEquals("/C:/p", uri.getPath());
    }

    uri = VfsUtil.toUri("file:///Users/S pace");
    assertNotNull(uri);
    assertEquals("file", uri.getScheme());
    assertEquals("/Users/S pace", uri.getPath());
    assertEquals("/Users/S%20pace", uri.getRawPath());
    assertEquals("file:///Users/S%20pace", uri.toString());

    uri = VfsUtil.toUri("http://developer.android.com/guide/developing/tools/avd.html");
    assertNotNull(uri);
    assertEquals("http", uri.getScheme());
    assertEquals("/guide/developing/tools/avd.html", uri.getRawPath());
    assertEquals("http://developer.android.com/guide/developing/tools/avd.html", uri.toString());

    uri = VfsUtil.toUri("http://developer.android.com/guide/developing/tools/avd.html?f=23r2ewd");
    assertNotNull(uri);
    assertEquals("http", uri.getScheme());
    assertEquals("/guide/developing/tools/avd.html", uri.getRawPath());
    assertEquals(
        "http://developer.android.com/guide/developing/tools/avd.html?f=23r2ewd", uri.toString());
    assertEquals("f=23r2ewd", uri.getQuery());
  }
コード例 #7
0
  protected boolean doSetIcon(
      DefaultMutableTreeNode node, @Nullable String path, Component component) {
    if (StringUtil.isNotEmpty(path) && !new File(path).isFile()) {
      Messages.showErrorDialog(
          component,
          IdeBundle.message("error.file.not.found.message", path),
          IdeBundle.message("title.choose.action.icon"));
      return false;
    }

    String actionId = getActionId(node);
    if (actionId == null) return false;

    final AnAction action = ActionManager.getInstance().getAction(actionId);
    if (action != null && action.getTemplatePresentation() != null) {
      if (StringUtil.isNotEmpty(path)) {
        Image image = null;
        try {
          image =
              ImageLoader.loadFromStream(
                  VfsUtil.convertToURL(VfsUtil.pathToUrl(path.replace(File.separatorChar, '/')))
                      .openStream());
        } catch (IOException e) {
          LOG.debug(e);
        }
        Icon icon = new File(path).exists() ? IconLoader.getIcon(image) : null;
        if (icon != null) {
          if (icon.getIconWidth() > EmptyIcon.ICON_18.getIconWidth()
              || icon.getIconHeight() > EmptyIcon.ICON_18.getIconHeight()) {
            Messages.showErrorDialog(
                component,
                IdeBundle.message("custom.icon.validation.message"),
                IdeBundle.message("title.choose.action.icon"));
            return false;
          }
          node.setUserObject(Pair.create(actionId, icon));
          mySelectedSchema.addIconCustomization(actionId, path);
        }
      } else {
        node.setUserObject(Pair.create(actionId, null));
        mySelectedSchema.removeIconCustomization(actionId);
        final DefaultMutableTreeNode nodeOnToolbar = findNodeOnToolbar(actionId);
        if (nodeOnToolbar != null) {
          editToolbarIcon(actionId, nodeOnToolbar);
          node.setUserObject(nodeOnToolbar.getUserObject());
        }
      }
      return true;
    }
    return false;
  }
コード例 #8
0
  public OperationStatus ensureFilesWritable(@NotNull VirtualFile... files) {
    if (files.length == 0) {
      return new OperationStatusImpl(VirtualFile.EMPTY_ARRAY);
    }
    ApplicationManager.getApplication().assertIsDispatchThread();

    Set<VirtualFile> realFiles = new THashSet<VirtualFile>(files.length);
    for (VirtualFile file : files) {
      if (file instanceof VirtualFileWindow) file = ((VirtualFileWindow) file).getDelegate();
      if (file != null) {
        realFiles.add(file);
      }
    }
    files = VfsUtil.toVirtualFileArray(realFiles);

    for (WritingAccessProvider accessProvider : myAccessProviders) {
      Collection<VirtualFile> denied = accessProvider.requestWriting(files);
      if (!denied.isEmpty()) {
        return new OperationStatusImpl(VfsUtil.toVirtualFileArray(denied));
      }
    }

    final FileInfo[] fileInfos = createFileInfos(files);
    if (fileInfos.length == 0) { // if all files are already writable
      return createResultStatus(files);
    }

    if (ApplicationManager.getApplication().isUnitTestMode()) {
      return createResultStatus(files);
    }

    // This event count hack is necessary to allow actions that called this stuff could still get
    // data from their data contexts.
    // Otherwise data manager stuff will fire up an assertion saying that event count has been
    // changed (due to modal dialog show-up)
    // The hack itself is safe since we guarantee that focus will return to the same component had
    // it before modal dialog have been shown.
    final int savedEventCount = IdeEventQueue.getInstance().getEventCount();
    if (myState.SHOW_DIALOG) {
      new ReadOnlyStatusDialog(myProject, fileInfos).show();
    } else {
      processFiles(
          new ArrayList<FileInfo>(Arrays.asList(fileInfos)),
          null); // the collection passed is modified
    }
    IdeEventQueue.getInstance().setEventCount(savedEventCount);
    return createResultStatus(files);
  }
  @NotNull
  private static Document setupFileEditorAndDocument(
      @NotNull String fileName, @NotNull String fileText) throws IOException {
    EncodingProjectManager.getInstance(getProject()).setEncoding(null, CharsetToolkit.UTF8_CHARSET);
    EncodingProjectManager.getInstance(ProjectManager.getInstance().getDefaultProject())
        .setEncoding(null, CharsetToolkit.UTF8_CHARSET);
    PostprocessReformattingAspect.getInstance(ourProject).doPostponedFormatting();
    deleteVFile();
    myVFile = getSourceRoot().createChildData(null, fileName);
    VfsUtil.saveText(myVFile, fileText);
    final FileDocumentManager manager = FileDocumentManager.getInstance();
    final Document document = manager.getDocument(myVFile);
    assertNotNull("Can't create document for '" + fileName + "'", document);
    manager.reloadFromDisk(document);
    document.insertString(0, " ");
    document.deleteString(0, 1);
    myFile = getPsiManager().findFile(myVFile);
    assertNotNull(
        "Can't create PsiFile for '" + fileName + "'. Unknown file type most probably.", myFile);
    assertTrue(myFile.isPhysical());
    myEditor = createEditor(myVFile);
    myVFile.setCharset(CharsetToolkit.UTF8_CHARSET);

    PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
    return document;
  }
コード例 #10
0
    public MkDirs(@NotNull String newName, @NotNull PsiDirectory directory) {
      if (SystemInfo.isWindows) {
        newName = newName.replace('\\', '/');
      }
      if (newName.contains("/")) {
        final List<String> subDirs = StringUtil.split(newName, "/");
        newName = subDirs.remove(subDirs.size() - 1);
        boolean firstToken = true;
        for (String dir : subDirs) {
          if (firstToken && "~".equals(dir)) {
            final VirtualFile userHomeDir = VfsUtil.getUserHomeDir();
            if (userHomeDir == null)
              throw new IncorrectOperationException("User home directory not found");
            final PsiDirectory directory1 = directory.getManager().findDirectory(userHomeDir);
            if (directory1 == null)
              throw new IncorrectOperationException("User home directory not found");
            directory = directory1;
          } else if ("..".equals(dir)) {
            final PsiDirectory parentDirectory = directory.getParentDirectory();
            if (parentDirectory == null)
              throw new IncorrectOperationException("Not a valid directory");
            directory = parentDirectory;
          } else if (!".".equals(dir)) {
            final PsiDirectory sub = directory.findSubdirectory(dir);
            directory = sub == null ? directory.createSubdirectory(dir) : sub;
          }
          firstToken = false;
        }
      }

      this.newName = newName;
      this.directory = directory;
    }
コード例 #11
0
  @NotNull
  private static List<VirtualFile> findClasses(File file, boolean isJre) {
    List<VirtualFile> result = ContainerUtil.newArrayList();
    VirtualFileManager fileManager = VirtualFileManager.getInstance();

    String path = file.getPath();
    if (JrtFileSystem.isModularJdk(path)) {
      String url =
          VirtualFileManager.constructUrl(
              JrtFileSystem.PROTOCOL,
              FileUtil.toSystemIndependentName(path) + JrtFileSystem.SEPARATOR);
      for (String module : JrtFileSystem.listModules(path)) {
        ContainerUtil.addIfNotNull(result, fileManager.findFileByUrl(url + module));
      }
    }

    for (File root : JavaSdkUtil.getJdkClassesRoots(file, isJre)) {
      String url = VfsUtil.getUrlForLibraryRoot(root);
      ContainerUtil.addIfNotNull(result, fileManager.findFileByUrl(url));
    }

    Collections.sort(result, (o1, o2) -> o1.getPath().compareTo(o2.getPath()));

    return result;
  }
    @Override
    protected void addCompletions(
        @NotNull CompletionParameters completionParameters,
        final ProcessingContext processingContext,
        @NotNull final CompletionResultSet completionResultSet) {

      PsiFile originalFile = completionParameters.getOriginalFile();
      final PsiDirectory containingDirectory = originalFile.getContainingDirectory();
      if (containingDirectory == null) {
        return;
      }

      final VirtualFile containingDirectoryFiles = containingDirectory.getVirtualFile();
      VfsUtil.visitChildrenRecursively(
          containingDirectoryFiles,
          new VirtualFileVisitor() {
            @Override
            public boolean visitFile(@NotNull VirtualFile file) {

              String relativePath = VfsUtil.getRelativePath(file, containingDirectoryFiles, '/');
              if (relativePath == null) {
                return super.visitFile(file);
              }

              completionResultSet.addElement(
                  LookupElementBuilder.create(relativePath).withIcon(file.getFileType().getIcon()));

              return super.visitFile(file);
            }
          });
    }
コード例 #13
0
  @Override
  public void recalculateOutputDirs() {
    final Module[] allModules = ModuleManager.getInstance(myProject).getModules();

    final Set<VirtualFile> allDirs = new OrderedSet<VirtualFile>();
    final Set<VirtualFile> testOutputDirs = new java.util.HashSet<VirtualFile>();
    final Set<VirtualFile> productionOutputDirs = new java.util.HashSet<VirtualFile>();

    CompilerPathsManager pathsManager = CompilerPathsManager.getInstance(getProject());
    for (Module module : allModules) {
      final VirtualFile output =
          pathsManager.getCompilerOutput(module, ProductionContentFolderTypeProvider.getInstance());
      if (output != null && output.isValid()) {
        allDirs.add(output);
        productionOutputDirs.add(output);
      }

      final VirtualFile testsOutput =
          pathsManager.getCompilerOutput(module, TestContentFolderTypeProvider.getInstance());
      if (testsOutput != null && testsOutput.isValid()) {
        allDirs.add(testsOutput);
        testOutputDirs.add(testsOutput);
      }
    }
    myOutputDirectories = VfsUtil.toVirtualFileArray(allDirs);
    // need this to ensure that the sent contains only _dedicated_ test output dirs
    // Directories that are configured for both test and production classes must not be added in the
    // resulting set
    testOutputDirs.removeAll(productionOutputDirs);
    myTestOutputDirectories = Collections.unmodifiableSet(testOutputDirs);
  }
コード例 #14
0
 @Override
 public IFile createFile(String path) {
   File file = new File(context.absPath(path));
   String name = file.getName();
   String parentPath = file.getParent();
   try {
     VfsUtil.createDirectories(parentPath);
   } catch (IOException e) {
     Flog.error("Create directories error %s", e);
     context.errorMessage("The Floobits plugin was unable to create directories for file.");
     return null;
   }
   VirtualFile parent = LocalFileSystem.getInstance().findFileByPath(parentPath);
   if (parent == null) {
     Flog.error("Virtual file is null? %s", parentPath);
     return null;
   }
   VirtualFile newFile;
   try {
     newFile = parent.findOrCreateChildData(context, name);
   } catch (Throwable e) {
     Flog.error("Create file error %s", e);
     context.errorMessage(
         String.format("The Floobits plugin was unable to create a file: %s.", path));
     return null;
   }
   return new FileImpl(newFile);
 }
コード例 #15
0
  private void createNodesGroupedByDirectory(
      CheckedTreeNode root, final List<? extends DetectedFrameworkDescription> frameworks) {
    Map<VirtualFile, FrameworkDirectoryNode> nodes = new HashMap<>();
    List<DetectedFrameworkNode> externalNodes = new ArrayList<>();
    for (DetectedFrameworkDescription framework : frameworks) {
      VirtualFile parent = VfsUtil.getCommonAncestor(framework.getRelatedFiles());
      if (parent != null && !parent.isDirectory()) {
        parent = parent.getParent();
      }

      final DetectedFrameworkNode frameworkNode = new DetectedFrameworkNode(framework, myContext);
      if (parent != null) {
        createDirectoryNodes(parent, nodes).add(frameworkNode);
      } else {
        externalNodes.add(frameworkNode);
      }
    }
    List<FrameworkDirectoryNode> rootDirs = new ArrayList<>();
    for (FrameworkDirectoryNode directoryNode : nodes.values()) {
      if (directoryNode.getParent() == null) {
        rootDirs.add(directoryNode);
      }
    }
    for (FrameworkDirectoryNode dir : rootDirs) {
      root.add(collapseDirectoryNode(dir));
    }
    for (DetectedFrameworkNode node : externalNodes) {
      root.add(node);
    }
  }
コード例 #16
0
  @Nullable
  private MPSTreeNode getNode(MPSTreeNode rootTreeNode, VirtualFile file) {
    if (rootTreeNode instanceof AbstractFileTreeNode) {
      VirtualFile nodeFile = ((AbstractFileTreeNode) rootTreeNode).getFile();

      if (nodeFile != null) {
        if (nodeFile.getUrl().equals(file.getUrl())) {
          return rootTreeNode;
        }

        if (!VfsUtil.isAncestor(nodeFile, file, false)) {
          return null;
        }
      } else {
        return null;
      }
    }

    for (MPSTreeNode node : rootTreeNode) {
      node.init();
      MPSTreeNode result = getNode(node, file);
      if (result != null) {
        return result;
      }
    }

    return null;
  }
コード例 #17
0
 protected static void touch(VirtualFile file) throws IOException {
   file.setBinaryContent(
       file.contentsToByteArray(), file.getModificationStamp() + 1, file.getTimeStamp() + 1);
   File ioFile = VfsUtil.virtualToIoFile(file);
   assert ioFile.setLastModified(ioFile.lastModified() - 100000);
   file.refresh(false, false);
 }
コード例 #18
0
  public void _testCollectedPsiWithChangedDocument() throws IOException {
    VirtualFile dir = getVirtualFile(createTempDirectory());
    PsiTestUtil.addSourceContentToRoots(myModule, dir);

    final VirtualFile vFile = createChildData(dir, "Foo.java");
    VfsUtil.saveText(vFile, "class Foo {}");

    final GlobalSearchScope scope = GlobalSearchScope.allScope(getProject());
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(getProject());
    assertNotNull(facade.findClass("Foo", scope));
    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              @Override
              public void run() {
                PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(vFile);
                assertNotNull(psiFile);

                Document document = FileDocumentManager.getInstance().getDocument(vFile);
                document.deleteString(0, document.getTextLength());
                assertNotNull(facade.findClass("Foo", scope));

                psiFile = null;
                PlatformTestUtil.tryGcSoftlyReachableObjects();
                assertNull(
                    ((PsiManagerEx) PsiManager.getInstance(getProject()))
                        .getFileManager()
                        .getCachedPsiFile(vFile));

                // should be assertNull(facade.findClass("Foo", scope));
                // or the file should not be allowed to be gc'ed
                facade.findClass("Foo", scope).getText();
              }
            });
  }
 private void removeDescendants(VirtualFile file, VirtualFilePointerContainer container) {
   for (VirtualFile virtualFile : container.getFiles()) {
     if (VfsUtil.isAncestor(file, virtualFile, false)) {
       container.remove(myPointerManager.create(virtualFile, this, null));
     }
   }
 }
コード例 #20
0
  /**
   * Returns true if the root was loaded with conflict. False is returned in all other cases: in the
   * case of success and in case of some other error.
   */
  private boolean loadRoot(final VirtualFile root) {
    LOG.info("loadRoot " + root);
    myProgressIndicator.setText(GitHandlerUtil.formatOperationName("Unstashing changes to", root));

    GitRepository repository = myRepositoryManager.getRepositoryForRoot(root);
    if (repository == null) {
      LOG.error("Repository is null for root " + root);
      return false;
    }

    GitSimpleEventDetector conflictDetector =
        new GitSimpleEventDetector(GitSimpleEventDetector.Event.MERGE_CONFLICT_ON_UNSTASH);
    GitCommandResult result = myGit.stashPop(repository, conflictDetector);
    VfsUtil.markDirtyAndRefresh(false, true, false, root);
    if (result.success()) {
      return false;
    } else if (conflictDetector.hasHappened()) {
      return true;
    } else {
      LOG.info("unstash failed " + result.getErrorOutputAsJoinedString());
      GitUIUtil.notifyImportantError(
          myProject, "Couldn't unstash", "<br/>" + result.getErrorOutputAsHtmlString());
      return false;
    }
  }
コード例 #21
0
  public boolean execute(boolean drop, boolean isInsideStartFinishGroup) {
    if (!myUndoableGroup.isUndoable()) {
      reportCannotUndo(
          CommonBundle.message("cannot.undo.error.contains.nonundoable.changes.message"),
          myUndoableGroup.getAffectedDocuments());
      return false;
    }

    Set<DocumentReference> clashing = getStackHolder().collectClashingActions(myUndoableGroup);
    if (!clashing.isEmpty()) {
      reportCannotUndo(
          CommonBundle.message("cannot.undo.error.other.affected.files.changed.message"), clashing);
      return false;
    }

    if (!isInsideStartFinishGroup && myUndoableGroup.shouldAskConfirmation(isRedo())) {
      if (!askUser()) return false;
    } else {
      if (restore(getBeforeState())) {
        setBeforeState(new EditorAndState(myEditor, myEditor.getState(FileEditorStateLevel.UNDO)));
        return true;
      }
    }

    Collection<VirtualFile> readOnlyFiles = collectReadOnlyAffectedFiles();
    if (!readOnlyFiles.isEmpty()) {
      final Project project = myManager.getProject();
      final VirtualFile[] files = VfsUtil.toVirtualFileArray(readOnlyFiles);

      if (project == null) {
        return false;
      }

      final ReadonlyStatusHandler.OperationStatus operationStatus =
          ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(files);
      if (operationStatus.hasReadonlyFiles()) {
        return false;
      }
    }

    Collection<Document> readOnlyDocuments = collectReadOnlyDocuments();
    if (!readOnlyDocuments.isEmpty()) {
      for (Document document : readOnlyDocuments) {
        document.fireReadOnlyModificationAttempt();
      }
      return false;
    }

    getStackHolder().removeFromStacks(myUndoableGroup);
    if (!drop) {
      getReverseStackHolder().addToStacks(myUndoableGroup);
    }

    performAction();

    restore(getAfterState());

    return true;
  }
コード例 #22
0
  private boolean checkReadonlyUsages() {
    final Set<VirtualFile> readOnlyUsages = getReadOnlyUsagesFiles();

    return readOnlyUsages.isEmpty()
        || !ReadonlyStatusHandler.getInstance(myProject)
            .ensureFilesWritable(VfsUtil.toVirtualFileArray(readOnlyUsages))
            .hasReadonlyFiles();
  }
コード例 #23
0
 @Override
 public IFile findFileByIoFile(File file) {
   VirtualFile fileByIoFile = VfsUtil.findFileByIoFile(file, true);
   if (fileByIoFile == null) {
     return null;
   }
   return new FileImpl(fileByIoFile);
 }
コード例 #24
0
 public static VirtualFile findVirtualFile(String systemId) {
   try {
     return VfsUtil.findFileByURL(new URL(systemId));
   } catch (Exception e) {
     LOG.warn("Failed to build file from uri <" + systemId + ">", e);
     return VirtualFileManager.getInstance().findFileByUrl(VfsUtilCore.fixURLforIDEA(systemId));
   }
 }
 private static boolean isUnder(VirtualFile file, final VirtualFilePointerContainer container) {
   for (VirtualFile excludedFile : container.getFiles()) {
     if (VfsUtil.isAncestor(excludedFile, file, false)) {
       return true;
     }
   }
   return false;
 }
コード例 #26
0
  public boolean isInSet(VirtualFile file) {
    if (CacheUtil.isIgnored(file, myRootManager)) return false;

    for (VirtualFile vf : getRootFiles()) {
      if (VfsUtil.isAncestor(vf, file, true)) return true;
    }
    return false;
  }
コード例 #27
0
  @Nullable
  private VirtualFile setupGradleSettingsFile(
      @NotNull VirtualFile modelContentRootDir, @NotNull ModifiableRootModel model)
      throws ConfigurationException {
    VirtualFile file = null;
    if (myWizardContext.isCreatingNewProject()) {
      final String moduleDirName =
          VfsUtilCore.getRelativePath(modelContentRootDir, model.getProject().getBaseDir(), '/');
      file =
          getExternalProjectConfigFile(
              model.getProject().getBasePath(), GradleConstants.SETTINGS_FILE_NAME);
      if (file == null) return null;

      Map<String, String> attributes = ContainerUtil.newHashMap();
      final String projectName = model.getProject().getName();
      attributes.put(TEMPLATE_ATTRIBUTE_PROJECT_NAME, projectName);
      attributes.put(TEMPLATE_ATTRIBUTE_MODULE_DIR_NAME, moduleDirName);
      attributes.put(TEMPLATE_ATTRIBUTE_MODULE_NAME, model.getModule().getName());
      saveFile(file, TEMPLATE_GRADLE_SETTINGS, attributes);
    } else {
      Map<String, Module> moduleMap = ContainerUtil.newHashMap();
      for (Module module : ModuleManager.getInstance(model.getProject()).getModules()) {
        for (ContentEntry contentEntry : model.getContentEntries()) {
          if (contentEntry.getFile() != null) {
            moduleMap.put(contentEntry.getFile().getPath(), module);
          }
        }
      }

      VirtualFile virtualFile = modelContentRootDir;
      Module module = null;
      while (virtualFile != null && module == null) {
        module = moduleMap.get(virtualFile.getPath());
        virtualFile = virtualFile.getParent();
      }

      if (module != null) {
        String rootProjectPath =
            module.getOptionValue(ExternalSystemConstants.ROOT_PROJECT_PATH_KEY);

        if (!StringUtil.isEmpty(rootProjectPath)) {
          VirtualFile rootProjectFile = VfsUtil.findFileByIoFile(new File(rootProjectPath), true);
          if (rootProjectFile == null) return null;

          final String moduleDirName =
              VfsUtilCore.getRelativePath(modelContentRootDir, rootProjectFile, '/');
          file = getExternalProjectConfigFile(rootProjectPath, GradleConstants.SETTINGS_FILE_NAME);
          if (file == null) return null;

          Map<String, String> attributes = ContainerUtil.newHashMap();
          attributes.put(TEMPLATE_ATTRIBUTE_MODULE_DIR_NAME, moduleDirName);
          attributes.put(TEMPLATE_ATTRIBUTE_MODULE_NAME, model.getModule().getName());
          appendToFile(file, TEMPLATE_GRADLE_SETTINGS_MERGE, attributes);
        }
      }
    }
    return file;
  }
コード例 #28
0
 synchronized void clearPointerCaches(String url, VirtualFilePointerListener listener) {
   TreeMap<String, VirtualFilePointerImpl> urlToPointer = myUrlToPointerMaps.get(listener);
   if (urlToPointer == null && ApplicationManager.getApplication().isUnitTestMode()) return;
   assert urlToPointer != null;
   urlToPointer.remove(VfsUtil.urlToPath(url));
   if (urlToPointer.isEmpty()) {
     myUrlToPointerMaps.remove(listener);
   }
 }
コード例 #29
0
 @Override
 public boolean isInSet(VirtualFile file) {
   for (final VirtualFile root : getDirectories()) {
     if (VfsUtil.isAncestor(root, file, false)) {
       return true;
     }
   }
   return cachedFiles.contains(file);
 }
コード例 #30
0
ファイル: MvcFramework.java プロジェクト: Zeratyl-SK/consulo
  private PathsList removeFrameworkStuff(Module module, List<VirtualFile> rootFiles) {
    final List<File> toExclude = getImplicitClasspathRoots(module);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Before removing framework stuff: " + rootFiles);
      LOG.debug("Implicit roots:" + toExclude);
    }

    PathsList scriptClassPath = new PathsList();
    eachRoot:
    for (VirtualFile file : rootFiles) {
      for (final File excluded : toExclude) {
        if (VfsUtil.isAncestor(excluded, VfsUtil.virtualToIoFile(file), false)) {
          continue eachRoot;
        }
      }
      scriptClassPath.add(file);
    }
    return scriptClassPath;
  }