com.intellij.openapi.vfs.VirtualFileManager Java Examples

The following examples show how to use com.intellij.openapi.vfs.VirtualFileManager. 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: VFileCreateEvent.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param requestor
 * @param parent
 * @param childName
 * @param isDirectory
 * @param attributes null means should read from the created file
 * @param symlinkTarget
 * @param isFromRefresh
 * @param children null means children not available (e.g. the created file is not a directory) or unknown
 */
public VFileCreateEvent(Object requestor,
                        @Nonnull VirtualFile parent,
                        @Nonnull String childName,
                        boolean isDirectory,
                        @Nullable FileAttributes attributes,
                        @Nullable String symlinkTarget,
                        boolean isFromRefresh,
                        @Nullable ChildInfo[] children) {
  super(requestor, isFromRefresh);
  myParent = parent;
  myDirectory = isDirectory;
  myAttributes = attributes;
  mySymlinkTarget = symlinkTarget;
  myChildren = children;
  myChildNameId = VirtualFileManager.getInstance().storeName(childName);
}
 
Example #2
Source File: DirectoryUrl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public Object[] createPath(final Project project) {
  if (moduleName != null) {
    final Module module = ApplicationManager.getApplication().runReadAction(new Computable<Module>() {
      @Nullable
      @Override
      public Module compute() {
        return ModuleManager.getInstance(project).findModuleByName(moduleName);
      }
    });
    if (module == null) return null;
  }
  final VirtualFileManager virtualFileManager = VirtualFileManager.getInstance();
  final VirtualFile file = virtualFileManager.findFileByUrl(url);
  if (file == null) return null;
  final PsiDirectory directory = ApplicationManager.getApplication().runReadAction(new Computable<PsiDirectory>() {
    @Nullable
    @Override
    public PsiDirectory compute() {
      return PsiManager.getInstance(project).findDirectory(file);
    }
  });
  if (directory == null) return null;
  return new Object[]{directory};
}
 
Example #3
Source File: ThriftFacetConf.java    From intellij-thrift with Apache License 2.0 6 votes vote down vote up
@Override
public void reset() {
  final List<Generator> list = translators.getData();
  list.clear();
  try {
    for (Generator g : config.getGenerators()) {
      list.add(g.clone());
    }
  }
  catch (CloneNotSupportedException e) {
    throw new RuntimeException("Failed to clone generator settings");
  }

  final List<VirtualFile> includes = includesList.getData();
  includes.clear();
  for (String inc : config.getIncludes()) {
    includes.add(VirtualFileManager.getInstance().findFileByUrl(inc));
  }

  cleanOnBuildCheckBox.setSelected(config.isCleanOutput());
  modified = false;
}
 
Example #4
Source File: TemplateUtils.java    From code-generator with Apache License 2.0 6 votes vote down vote up
private static void generateSourceFile(String source, String baseDir) {
    String packageName = extractPackage(source);
    String className = extractClassName(source);
    String sourcePath = buildSourcePath(baseDir, className, packageName);
    VirtualFileManager manager = VirtualFileManager.getInstance();
    VirtualFile virtualFile = manager.refreshAndFindFileByUrl(VfsUtil.pathToUrl(sourcePath));
    if (virtualFile == null || !virtualFile.exists() || userConfirmedOverride(className)) {
        ApplicationManager.getApplication().runWriteAction(() -> {
            try {
                if (virtualFile != null && virtualFile.exists()) {
                    virtualFile.setBinaryContent(source.getBytes("utf8"));

                } else {
                    File file = new File(sourcePath);
                    FileUtils.writeStringToFile(file, source, "utf8");
                    manager.refreshAndFindFileByUrl(VfsUtil.pathToUrl(sourcePath));
                }
            } catch (IOException e) {
                log.error(e);
            }
        });
    }
}
 
Example #5
Source File: LocalHistoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected void initHistory() {
  ChangeListStorage storage;
  try {
    storage = new ChangeListStorageImpl(getStorageDir());
  }
  catch (Throwable e) {
    LocalHistoryLog.LOG.warn("cannot create storage, in-memory  implementation will be used", e);
    storage = new InMemoryChangeListStorage();
  }
  myChangeList = new ChangeList(storage);
  myVcs = new LocalHistoryFacade(myChangeList);

  myGateway = new IdeaGateway();

  myEventDispatcher = new LocalHistoryEventDispatcher(myVcs, myGateway);

  CommandProcessor.getInstance().addCommandListener(myEventDispatcher, this);

  myConnection = myBus.connect();
  myConnection.subscribe(VirtualFileManager.VFS_CHANGES, myEventDispatcher);

  VirtualFileManager fm = VirtualFileManager.getInstance();
  fm.addVirtualFileManagerListener(myEventDispatcher, this);
}
 
Example #6
Source File: LibraryRootsComponent.java    From consulo with Apache License 2.0 6 votes vote down vote up
private Set<VirtualFile> getNotExcludedRoots() {
  Set<VirtualFile> roots = new LinkedHashSet<VirtualFile>();
  String[] excludedRootUrls = getLibraryEditor().getExcludedRootUrls();
  Set<VirtualFile> excludedRoots = new HashSet<VirtualFile>();
  for (String url : excludedRootUrls) {
    ContainerUtil.addIfNotNull(excludedRoots, VirtualFileManager.getInstance().findFileByUrl(url));
  }
  for (OrderRootType type : OrderRootType.getAllTypes()) {
    VirtualFile[] files = getLibraryEditor().getFiles(type);
    for (VirtualFile file : files) {
      if (!VfsUtilCore.isUnder(file, excludedRoots)) {
        roots.add(PathUtil.getLocalFile(file));
      }
    }
  }
  return roots;
}
 
Example #7
Source File: UploadActionBase.java    From markdown-image-kit with MIT License 6 votes vote down vote up
/**
 * 所有子类都走这个逻辑, 做一些前置判断和解析 markdown image mark
 *
 * @param event the an action event
 */
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
    // 先刷新一次, 避免才添加的文件未被添加的 VFS 中, 导致找不到文件的问题
    VirtualFileManager.getInstance().syncRefresh();

    final Project project = event.getProject();
    if (project != null) {
        EventData data = new EventData()
            .setActionEvent(event)
            .setProject(project)
            // 使用子类的具体 client
            .setClient(getClient())
            .setClientName(getName());

        // 开启后台任务
        new ActionTask(project, MikBundle.message("mik.action.upload.process", getName()), ActionManager.buildUploadChain(data)).queue();
    }
}
 
Example #8
Source File: SMTestProxy.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected Location getLocation(@Nonnull Project project, @Nonnull GlobalSearchScope searchScope, String locationUrl) {
  if (locationUrl != null && myLocator != null) {
    String protocolId = VirtualFileManager.extractProtocol(locationUrl);
    if (protocolId != null) {
      String path = VirtualFileManager.extractPath(locationUrl);
      if (!DumbService.isDumb(project) || DumbService.isDumbAware(myLocator)) {
        return DumbService.getInstance(project).computeWithAlternativeResolveEnabled(() -> {
          List<Location> locations = myLocator.getLocation(protocolId, path, myMetainfo, project, searchScope);
          return !locations.isEmpty() ? locations.get(0) : null;
        });
      }
    }
  }

  return null;
}
 
Example #9
Source File: PlatformDocumentationUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static List<String> getHttpRoots(final String[] roots, String relPath) {
  final ArrayList<String> result = new ArrayList<String>();
  for (String root : roots) {
    final VirtualFile virtualFile = VirtualFileManager.getInstance().findFileByUrl(root);
    if (virtualFile != null) {
      if (virtualFile.getFileSystem() instanceof HttpFileSystem) {
        String url = virtualFile.getUrl();
        if (!url.endsWith("/")) url += "/";
        result.add(url + relPath);
      }
      else {
        VirtualFile file = virtualFile.findFileByRelativePath(relPath);
        if (file != null) result.add(file.getUrl());
      }
    }
  }

  return result.isEmpty() ? null : result;
}
 
Example #10
Source File: HighlightingSettingsPerFile.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void loadState(Element element) {
  List children = element.getChildren(SETTING_TAG);
  for (final Object aChildren : children) {
    final Element child = (Element)aChildren;
    final String url = child.getAttributeValue(FILE_ATT);
    if (url == null) continue;
    final VirtualFile fileByUrl = VirtualFileManager.getInstance().findFileByUrl(url);
    if (fileByUrl != null) {
      final List<FileHighlightingSetting> settings = new ArrayList<FileHighlightingSetting>();
      int index = 0;
      while (child.getAttributeValue(ROOT_ATT_PREFIX + index) != null) {
        final String attributeValue = child.getAttributeValue(ROOT_ATT_PREFIX + index++);
        settings.add(Enum.valueOf(FileHighlightingSetting.class, attributeValue));
      }
      myHighlightSettings.put(fileByUrl, settings.toArray(new FileHighlightingSetting[settings.size()]));
    }
  }
}
 
Example #11
Source File: CompilerPathsImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@javax.annotation.Nullable
public static String getModuleOutputPath(final Module module, final ContentFolderTypeProvider contentFolderType) {
  final String outPathUrl;
  final Application application = ApplicationManager.getApplication();
  final ModuleCompilerPathsManager pathsManager = ModuleCompilerPathsManager.getInstance(module);

  if (application.isDispatchThread()) {
    outPathUrl = pathsManager.getCompilerOutputUrl(contentFolderType);
  }
  else {
    outPathUrl = application.runReadAction(new Computable<String>() {
      @Override
      public String compute() {
        return pathsManager.getCompilerOutputUrl(contentFolderType);
      }
    });
  }

  return outPathUrl != null ? VirtualFileManager.extractPath(outPathUrl) : null;
}
 
Example #12
Source File: UnindexedFilesUpdater.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void scheduleInitialVfsRefresh() {
  ProjectRootManagerEx.getInstanceEx(myProject).markRootsForRefresh();

  Application app = ApplicationManager.getApplication();
  if (!app.isCommandLine()) {
    long sessionId = VirtualFileManager.getInstance().asyncRefresh(null);
    MessageBusConnection connection = app.getMessageBus().connect();
    connection.subscribe(ProjectManager.TOPIC, new ProjectManagerListener() {
      @Override
      public void projectClosed(@Nonnull Project project, @Nonnull UIAccess uiAccess) {
        if (project == myProject) {
          RefreshQueue.getInstance().cancelSession(sessionId);
          connection.disconnect();
        }
      }
    });
  }
  else {
    VirtualFileManager.getInstance().syncRefresh();
  }
}
 
Example #13
Source File: IntellijLanguageClient.java    From lsp4intellij with Apache License 2.0 6 votes vote down vote up
@Override
public void initComponent() {
    try {
        // Adds project listener.
        ApplicationManager.getApplication().getMessageBus().connect().subscribe(ProjectManager.TOPIC,
                new LSPProjectManagerListener());
        // Adds editor listener.
        EditorFactory.getInstance().addEditorFactoryListener(new LSPEditorListener(), this);
        // Adds VFS listener.
        VirtualFileManager.getInstance().addVirtualFileListener(new VFSListener());
        // Adds document event listener.
        ApplicationManager.getApplication().getMessageBus().connect().subscribe(AppTopics.FILE_DOCUMENT_SYNC,
                new LSPFileDocumentManagerListener());

        // in case if JVM forcefully exit.
        Runtime.getRuntime().addShutdownHook(new Thread(() -> projectToLanguageWrappers.values().stream()
                .flatMap(Collection::stream).filter(RUNNING).forEach(s -> s.stop(true))));

        LOG.info("Intellij Language Client initialized successfully");
    } catch (Exception e) {
        LOG.warn("Fatal error occurred when initializing Intellij language client.", e);
    }
}
 
Example #14
Source File: EditorBasedStatusBarPopup.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void install(@Nonnull StatusBar statusBar) {
  super.install(statusBar);
  registerCustomListeners();
  EditorFactory.getInstance().getEventMulticaster().addDocumentListener(new DocumentListener() {
    @Override
    public void documentChanged(@Nonnull DocumentEvent e) {
      Document document = e.getDocument();
      updateForDocument(document);
    }
  }, this);
  if (myWriteableFileRequired) {
    ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(VirtualFileManager.VFS_CHANGES, new BulkVirtualFileListenerAdapter(new VirtualFileListener() {
      @Override
      public void propertyChanged(@Nonnull VirtualFilePropertyEvent event) {
        if (VirtualFile.PROP_WRITABLE.equals(event.getPropertyName())) {
          updateForFile(event.getFile());
        }
      }
    }));
  }
}
 
Example #15
Source File: BlazeJavascriptWebTestEventsHandlerTest.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Nullable
private Location<?> getLocation(String url) {
  String protocol = VirtualFileManager.extractProtocol(url);
  if (protocol == null) {
    return null;
  }
  String path = VirtualFileManager.extractPath(url);
  assertThat(handler.getTestLocator()).isNotNull();
  @SuppressWarnings("rawtypes")
  List<Location> locations =
      handler
          .getTestLocator()
          .getLocation(protocol, path, getProject(), GlobalSearchScope.allScope(getProject()));
  assertThat(locations).hasSize(1);
  return locations.get(0);
}
 
Example #16
Source File: LocalFsFinder.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public LookupFile find(@Nonnull final String path) {
  final VirtualFile byUrl = VirtualFileManager.getInstance().findFileByUrl(path);
  if (byUrl != null) {
    return new VfsFile(this, byUrl);
  }

  String toFind = normalize(path);
  if (toFind.length() == 0) {
    File[] roots = File.listRoots();
    if (roots.length > 0) {
      toFind = roots[0].getAbsolutePath();
    }
  }
  final File file = new File(toFind);
  // '..' and '.' path components will be eliminated
  VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(file);
  if (vFile != null) {
    return new VfsFile(this, vFile);
  } else if (file.isAbsolute()) {
    return new IoFile(new File(path));
  }
  return null;
}
 
Example #17
Source File: LightFilePointer.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void refreshFile() {
  VirtualFile file = myFile;
  if (file != null && file.isValid()) return;
  VirtualFileManager vfManager = VirtualFileManager.getInstance();
  VirtualFile virtualFile = vfManager.findFileByUrl(myUrl);
  if (virtualFile == null && !myRefreshed) {
    myRefreshed = true;
    Application application = ApplicationManager.getApplication();
    if (application.isDispatchThread() || !application.isReadAccessAllowed()) {
      virtualFile = vfManager.refreshAndFindFileByUrl(myUrl);
    }
    else {
      application.executeOnPooledThread(() -> vfManager.refreshAndFindFileByUrl(myUrl));
    }
  }

  myFile = virtualFile != null && virtualFile.isValid() ? virtualFile : null;
}
 
Example #18
Source File: BlazeWebGoTestEventsHandlerTest.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Nullable
private Location<?> getLocation(String url) {
  String protocol = VirtualFileManager.extractProtocol(url);
  if (protocol == null) {
    return null;
  }
  String path = VirtualFileManager.extractPath(url);
  assertThat(handler.getTestLocator()).isNotNull();
  @SuppressWarnings("rawtypes")
  List<Location> locations =
      handler
          .getTestLocator()
          .getLocation(protocol, path, getProject(), GlobalSearchScope.allScope(getProject()));
  assertThat(locations).hasSize(1);
  return locations.get(0);
}
 
Example #19
Source File: PersistentFileSetManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void loadState(Element state) {
  final VirtualFileManager vfManager = VirtualFileManager.getInstance();
  for (Object child : state.getChildren(FILE_ELEMENT)) {
    if (child instanceof Element) {
      final Element fileElement = (Element)child;
      final Attribute filePathAttr = fileElement.getAttribute(PATH_ATTR);
      if (filePathAttr != null) {
        final String filePath = filePathAttr.getValue();
        VirtualFile vf = vfManager.findFileByUrl(filePath);
        if (vf != null) {
          myFiles.add(vf);
        }
      }
    }
  }
}
 
Example #20
Source File: IdeaLightweightExtension.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
private void initializeApplication(Application application) {
    DefaultPicoContainer pico = new DefaultPicoContainer();
    when(application.getPicoContainer()).thenReturn(pico);

    MessageBus bus = new SingleThreadedMessageBus(null);
    when(application.getMessageBus()).thenReturn(bus);

    // Service setup.  See ServiceManager
    pico.registerComponent(service(PasswordSafe.class, new MockPasswordSafe()));
    pico.registerComponent(service(VcsContextFactory.class, new MockVcsContextFactory()));

    VirtualFileManager vfm = mock(VirtualFileManager.class);
    when(application.getComponent(VirtualFileManager.class)).thenReturn(vfm);

    AccessToken readToken = mock(AccessToken.class);
    when(application.acquireReadActionLock()).thenReturn(readToken);

    ApplicationInfo appInfo = mock(ApplicationInfo.class);
    when(appInfo.getApiVersion()).thenReturn("IC-182.1.1");
    registerApplicationService(ApplicationInfo.class, appInfo);
}
 
Example #21
Source File: ModuleManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nonnull
public Module newModule(@Nonnull @NonNls String name, @Nullable @NonNls String dirPath) {
  assertWritable();

  final String dirUrl = dirPath == null ? null : VirtualFileManager.constructUrl(StandardFileSystems.FILE_PROTOCOL, dirPath);

  ModuleEx moduleEx = null;
  if (dirUrl != null) {
    moduleEx = getModuleByDirUrl(dirUrl);
  }

  if (moduleEx == null) {
    moduleEx = createModule(name, dirUrl, null);
    initModule(moduleEx);
  }
  return moduleEx;
}
 
Example #22
Source File: PantsUtil.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
public static void synchronizeFiles() {
  /**
   * Run in SYNC in unit test mode, and {@link com.twitter.intellij.pants.testFramework.PantsIntegrationTestCase.doImport}
   * is required to be wrapped in WriteAction. Otherwise it will run in async mode.
   */
  if (ApplicationManager.getApplication().isUnitTestMode() && ApplicationManager.getApplication().isWriteAccessAllowed()) {
    ApplicationManager.getApplication().runWriteAction(() -> {
      FileDocumentManager.getInstance().saveAllDocuments();
      SaveAndSyncHandler.getInstance().refreshOpenFiles();
      VirtualFileManager.getInstance().refreshWithoutFileWatcher(false); /** synchronous */
    });
  }
  else {
    ApplicationManager.getApplication().invokeLater(() -> {
      FileDocumentManager.getInstance().saveAllDocuments();
      SaveAndSyncHandler.getInstance().refreshOpenFiles();
      VirtualFileManager.getInstance().refreshWithoutFileWatcher(true); /** asynchronous */
    });
  }
}
 
Example #23
Source File: Listener.java    From floobits-intellij with Apache License 2.0 6 votes vote down vote up
public synchronized void shutdown() {
    if (connection != null) {
        connection.disconnect();
        connection = null;
    }
    if (em != null) {
        em.removeSelectionListener(this);
        em.removeDocumentListener(this);
        em.removeCaretListener(this);
        em.removeVisibleAreaListener(this);
        em = null;
    }
    if (virtualFileAdapter != null) {
        VirtualFileManager.getInstance().removeVirtualFileListener(virtualFileAdapter);
        virtualFileAdapter = null;
    }

}
 
Example #24
Source File: OrderEntryAppearanceServiceImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static CellAppearanceEx formatRelativePath(@Nonnull final ContentFolder folder, @Nonnull final Image icon) {
  LightFilePointer folderFile = new LightFilePointer(folder.getUrl());
  VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(folder.getContentEntry().getUrl());
  if (file == null) return FileAppearanceService.getInstance().forInvalidUrl(folderFile.getPresentableUrl());

  String contentPath = file.getPath();
  String relativePath;
  SimpleTextAttributes textAttributes;
  VirtualFile folderFileFile = folderFile.getFile();
  if (folderFileFile == null) {
    String absolutePath = folderFile.getPresentableUrl();
    relativePath = absolutePath.startsWith(contentPath) ? absolutePath.substring(contentPath.length()) : absolutePath;
    textAttributes = SimpleTextAttributes.ERROR_ATTRIBUTES;
  }
  else {
    relativePath = VfsUtilCore.getRelativePath(folderFileFile, file, File.separatorChar);
    textAttributes = SimpleTextAttributes.REGULAR_ATTRIBUTES;
  }

  relativePath = StringUtil.isEmpty(relativePath) ? "." + File.separatorChar : relativePath;
  return new SimpleTextCellAppearance(relativePath, icon, textAttributes);
}
 
Example #25
Source File: ExtractConceptHandler.java    From Intellij-Plugin with Apache License 2.0 6 votes vote down vote up
public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile psiFile) {
    this.psiFile = psiFile;
    this.editor = editor;
    try {
        List<PsiElement> steps = getSteps(this.editor, this.psiFile);
        if (steps.size() == 0)
            throw new RuntimeException("Cannot Extract to Concept, selected text contains invalid elements");
        ExtractConceptInfoCollector collector = new ExtractConceptInfoCollector(editor, builder.getTextToTableMap(), steps, project);
        ExtractConceptInfo info = collector.getAllInfo();
        if (!info.cancelled) {
            VirtualFileManager.getInstance().refreshWithoutFileWatcher(false);
            FileDocumentManager.getInstance().saveAllDocuments();
            Api.ExtractConceptResponse response = makeExtractConceptRequest(steps, info.fileName, info.conceptName, false, psiFile);
            if (!response.getIsSuccess()) throw new RuntimeException(response.getError());
            new UndoHandler(response.getFilesChangedList(), project, "Extract Concept").handle();
        }
    } catch (Exception e) {
        Messages.showErrorDialog(e.getMessage(), "Extract To Concept");
    }
}
 
Example #26
Source File: AddControllerForm.java    From r2m-plugin-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onGenerateFinished(boolean result, File file) {
    SaveAndSyncHandlerImpl.refreshOpenFiles();
    VirtualFileManager.getInstance().refreshWithoutFileWatcher(false);
    ProjectManagerEx.getInstanceEx().unblockReloadingProjectOnExternalChanges();
    project.getBaseDir().refresh(false, true);

    if (null == JavaPsiFacade.getInstance(project).findPackage("com.magnet.android.mms.async")) {
        showMissingDependencies();
    }

    if (!result) {
        showCloseDialog(file);
    } else {
        getThis().setVisible(true);
    }
}
 
Example #27
Source File: HaxeFileUtil.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
/**
 * Find a file, given a path.  If the path is not absolute, then try as relative
 * to other given paths.
 *
 * @param path Path to test.  Null or empty path is not an error, but will return a null result.
 * @param rootPaths Variable number of other root paths to search.
 * @return null if the file could not be located; a VirtualFile if it could.
 */
@Nullable
public static VirtualFile locateFile(String path, String... rootPaths) {
  if (null == path || path.isEmpty()) {
    return null;
  }

  String tryPath = fixUrl(path);

  VirtualFileManager vfs = VirtualFileManager.getInstance();
  VirtualFile file = vfs.findFileByUrl(tryPath);
  if (null == file && !isAbsolutePath(tryPath)) {
    String nonUrlPath = vfs.extractPath(path);
    for (String root : rootPaths) {
      if (null != root && !root.isEmpty()) {
        tryPath = fixUrl(joinPath(root, nonUrlPath));
        file = vfs.findFileByUrl(tryPath);
        if (null != file) {
          break;
        }
      }
    }
  }

  return file;
}
 
Example #28
Source File: FileChangeTracker.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Check whether all the class path entries in the manifest are valid.
 *
 * @param project current project.
 * @return true iff the manifest jar is valid.
 */
private static boolean isManifestJarValid(@NotNull Project project) {
  Optional<VirtualFile> manifestJar = PantsUtil.findProjectManifestJar(project);
  if (!manifestJar.isPresent()) {
    return false;
  }
  VirtualFile file = manifestJar.get();
  if (!new File(file.getPath()).exists()) {
    return false;
  }
  try {
    VirtualFile manifestInJar =
      VirtualFileManager.getInstance().refreshAndFindFileByUrl("jar://" + file.getPath() + "!/META-INF/MANIFEST.MF");
    if (manifestInJar == null) {
      return false;
    }
    Manifest manifest = new Manifest(manifestInJar.getInputStream());
    List<String> relPaths = PantsUtil.parseCmdParameters(manifest.getMainAttributes().getValue("Class-Path"));
    for (String path : relPaths) {
      // All rel paths in META-INF/MANIFEST.MF is relative to the jar directory
      if (!new File(file.getParent().getPath(), path).exists()) {
        return false;
      }
    }
    return true;
  }
  catch (IOException e) {
    e.printStackTrace();
    return false;
  }
}
 
Example #29
Source File: PantsProjectSettingsControl.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validate(@NotNull PantsProjectSettings settings) throws ConfigurationException {
  if(myNameField.getText().isEmpty()){
    throw new ConfigurationException(PantsBundle.message("pants.error.project.name.empty"));
  }

  if (myNameField.getText().length() > 200) {
    throw new ConfigurationException(PantsBundle.message("pants.error.project.name.tooLong"));
  }

  final String projectUrl = VfsUtil.pathToUrl(settings.getExternalProjectPath());
  final VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(projectUrl);
  ProjectPathFileType pathFileType = determinePathKind(file);
  switch (pathFileType) {
    case isNonExistent:
      throw new ConfigurationException(PantsBundle.message("pants.error.file.not.exists", projectUrl));
    case isNonPantsFile:
      throw new ConfigurationException(PantsBundle.message("pants.error.not.build.file.path.or.directory"));
    case executableScript:
      return true;
    case isBUILDFile:
      if (myTargetSpecsBox.getSelectedIndices().length == 0) {
        throw new ConfigurationException(PantsBundle.message("pants.error.no.targets.are.selected"));
      }
      break;
    case isRecursiveDirectory:
      break;
    default:
      throw new ConfigurationException("Unexpected project file state: " + pathFileType);
  }
  if (!errors.isEmpty()) {
    String errorMessage = String.join("\n", errors);
    errors.clear();
    throw new ConfigurationException(errorMessage);
  }
  return true;
}
 
Example #30
Source File: FileMonitor.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
public FileMonitor(Project project, Trigger trigger, VirtualFileManager fileManager) {
	super(project, trigger);
	this.fileManager = fileManager;
	this.listener = new Listener();
	fileManager.addVirtualFileListener(this.listener);
	check();
}