Search in sources :

Example 16 with LocalFileSystem

use of com.intellij.openapi.vfs.LocalFileSystem in project android by JetBrains.

the class GradleEditorModelParserFacade method isParentProject.

private static boolean isParentProject(@NotNull File settingsFile, @NotNull VirtualFile targetConfigFile) {
    try {
        ImmutableList<String> lines = Files.asCharSource(settingsFile, Charset.forName("UTF-8")).readLines();
        String startLineMarker = "include ";
        for (String line : lines) {
            if (!line.startsWith(startLineMarker)) {
                continue;
            }
            List<String> subProjects = Lists.newArrayList();
            for (String s : Splitter.on(",").trimResults().omitEmptyStrings().split(line.substring(startLineMarker.length()))) {
                // Sub-projects are defined as strings with leading colon, e.g. include ':app'.
                s = GradleEditorModelUtil.unquote(s);
                if (s.startsWith(":")) {
                    s = s.substring(1);
                }
                subProjects.add(s);
            }
            List<String> dirs = Lists.newArrayList();
            LocalFileSystem fileSystem = LocalFileSystem.getInstance();
            VirtualFile rootDir = fileSystem.refreshAndFindFileByIoFile(settingsFile.getParentFile());
            if (rootDir == null) {
                return false;
            }
            for (VirtualFile dir = targetConfigFile.getParent(); dir != null; dir = dir.getParent()) {
                if (rootDir.equals(dir)) {
                    break;
                }
                dirs.add(dir.getName());
            }
            Collections.reverse(dirs);
            int i = 0;
            for (String subProject : subProjects) {
                if (i >= dirs.size() || !subProject.equals(dirs.get(i++))) {
                    return false;
                }
            }
            return true;
        }
    } catch (IOException e) {
        LOG.warn("Unexpected exception occurred on attempt to read contents of file " + settingsFile.getAbsolutePath());
    }
    return false;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) LocalFileSystem(com.intellij.openapi.vfs.LocalFileSystem) IOException(java.io.IOException)

Example 17 with LocalFileSystem

use of com.intellij.openapi.vfs.LocalFileSystem in project android by JetBrains.

the class ThemeEditorUtils method getResourceFolderRepositoriesFromSourceSet.

/**
   * Given a {@link SourceProvider}, it returns a list of all the available ResourceFolderRepositories
   */
@NotNull
public static List<ResourceFolderRepository> getResourceFolderRepositoriesFromSourceSet(@NotNull AndroidFacet facet, @Nullable SourceProvider provider) {
    if (provider == null) {
        return Collections.emptyList();
    }
    Collection<File> resDirectories = provider.getResDirectories();
    LocalFileSystem fileSystem = LocalFileSystem.getInstance();
    List<ResourceFolderRepository> folders = Lists.newArrayListWithExpectedSize(resDirectories.size());
    for (File dir : resDirectories) {
        VirtualFile virtualFile = fileSystem.findFileByIoFile(dir);
        if (virtualFile != null) {
            folders.add(ResourceFolderRegistry.get(facet, virtualFile));
        }
    }
    return folders;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) LocalFileSystem(com.intellij.openapi.vfs.LocalFileSystem) XmlFile(com.intellij.psi.xml.XmlFile) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) File(java.io.File) NotNull(org.jetbrains.annotations.NotNull)

Example 18 with LocalFileSystem

use of com.intellij.openapi.vfs.LocalFileSystem in project intellij-community by JetBrains.

the class GitRollbackEnvironment method rollbackChanges.

public void rollbackChanges(@NotNull List<Change> changes, final List<VcsException> exceptions, @NotNull final RollbackProgressListener listener) {
    HashMap<VirtualFile, List<FilePath>> toUnindex = new HashMap<>();
    HashMap<VirtualFile, List<FilePath>> toUnversion = new HashMap<>();
    HashMap<VirtualFile, List<FilePath>> toRevert = new HashMap<>();
    List<FilePath> toDelete = new ArrayList<>();
    listener.determinate();
    // collect changes to revert
    for (Change c : changes) {
        switch(c.getType()) {
            case NEW:
                // note that this the only change that could happen
                // for HEAD-less working directories.
                registerFile(toUnversion, c.getAfterRevision().getFile(), exceptions);
                break;
            case MOVED:
                registerFile(toRevert, c.getBeforeRevision().getFile(), exceptions);
                registerFile(toUnindex, c.getAfterRevision().getFile(), exceptions);
                toDelete.add(c.getAfterRevision().getFile());
                break;
            case MODIFICATION:
                // note that changes are also removed from index, if they got into index somehow
                registerFile(toUnindex, c.getBeforeRevision().getFile(), exceptions);
                registerFile(toRevert, c.getBeforeRevision().getFile(), exceptions);
                break;
            case DELETED:
                registerFile(toRevert, c.getBeforeRevision().getFile(), exceptions);
                break;
        }
    }
    // unindex files
    for (Map.Entry<VirtualFile, List<FilePath>> entry : toUnindex.entrySet()) {
        listener.accept(entry.getValue());
        try {
            unindex(entry.getKey(), entry.getValue(), false);
        } catch (VcsException e) {
            exceptions.add(e);
        }
    }
    // unversion files
    for (Map.Entry<VirtualFile, List<FilePath>> entry : toUnversion.entrySet()) {
        listener.accept(entry.getValue());
        try {
            unindex(entry.getKey(), entry.getValue(), true);
        } catch (VcsException e) {
            exceptions.add(e);
        }
    }
    // delete files
    for (FilePath file : toDelete) {
        listener.accept(file);
        try {
            final File ioFile = file.getIOFile();
            if (ioFile.exists()) {
                if (!ioFile.delete()) {
                    //noinspection ThrowableInstanceNeverThrown
                    exceptions.add(new VcsException("Unable to delete file: " + file));
                }
            }
        } catch (Exception e) {
            //noinspection ThrowableInstanceNeverThrown
            exceptions.add(new VcsException("Unable to delete file: " + file, e));
        }
    }
    // revert files from HEAD
    AccessToken token = DvcsUtil.workingTreeChangeStarted(myProject);
    try {
        for (Map.Entry<VirtualFile, List<FilePath>> entry : toRevert.entrySet()) {
            listener.accept(entry.getValue());
            try {
                revert(entry.getKey(), entry.getValue());
            } catch (VcsException e) {
                exceptions.add(e);
            }
        }
    } finally {
        token.finish();
    }
    LocalFileSystem lfs = LocalFileSystem.getInstance();
    HashSet<File> filesToRefresh = new HashSet<>();
    for (Change c : changes) {
        ContentRevision before = c.getBeforeRevision();
        if (before != null) {
            filesToRefresh.add(new File(before.getFile().getPath()));
        }
        ContentRevision after = c.getAfterRevision();
        if (after != null) {
            filesToRefresh.add(new File(after.getFile().getPath()));
        }
    }
    lfs.refreshIoFiles(filesToRefresh);
    for (GitRepository repo : GitUtil.getRepositoryManager(myProject).getRepositories()) {
        repo.update();
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) FilePath(com.intellij.openapi.vcs.FilePath) ContentRevision(com.intellij.openapi.vcs.changes.ContentRevision) Change(com.intellij.openapi.vcs.changes.Change) VcsException(com.intellij.openapi.vcs.VcsException) GitRepository(git4idea.repo.GitRepository) AccessToken(com.intellij.openapi.application.AccessToken) LocalFileSystem(com.intellij.openapi.vfs.LocalFileSystem) VcsException(com.intellij.openapi.vcs.VcsException) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File)

Example 19 with LocalFileSystem

use of com.intellij.openapi.vfs.LocalFileSystem in project intellij-community by JetBrains.

the class GitChangeProvider method appendNestedVcsRootsToDirt.

private static void appendNestedVcsRootsToDirt(final VcsDirtyScope dirtyScope, GitVcs vcs, final ProjectLevelVcsManager vcsManager) {
    final Set<FilePath> recursivelyDirtyDirectories = dirtyScope.getRecursivelyDirtyDirectories();
    if (recursivelyDirtyDirectories.isEmpty()) {
        return;
    }
    final LocalFileSystem lfs = LocalFileSystem.getInstance();
    final Set<VirtualFile> rootsUnderGit = new HashSet<>(Arrays.asList(vcsManager.getRootsUnderVcs(vcs)));
    final Set<VirtualFile> inputColl = new HashSet<>(rootsUnderGit);
    final Set<VirtualFile> existingInScope = new HashSet<>();
    for (FilePath dir : recursivelyDirtyDirectories) {
        VirtualFile vf = dir.getVirtualFile();
        if (vf == null) {
            vf = lfs.findFileByIoFile(dir.getIOFile());
        }
        if (vf == null) {
            vf = lfs.refreshAndFindFileByIoFile(dir.getIOFile());
        }
        if (vf != null) {
            existingInScope.add(vf);
        }
    }
    inputColl.addAll(existingInScope);
    if (LOG.isDebugEnabled())
        LOG.debug("appendNestedVcsRoots. collection to remove ancestors: " + inputColl);
    FileUtil.removeAncestors(inputColl, new Convertor<VirtualFile, String>() {

        @Override
        public String convert(VirtualFile o) {
            return o.getPath();
        }
    }, new PairProcessor<VirtualFile, VirtualFile>() {

        @Override
        public boolean process(VirtualFile parent, VirtualFile child) {
            if (!existingInScope.contains(child) && existingInScope.contains(parent)) {
                LOG.debug("adding git root for check. child: " + child.getPath() + ", parent: " + parent.getPath());
                ((VcsModifiableDirtyScope) dirtyScope).addDirtyDirRecursively(VcsUtil.getFilePath(child));
            }
            return true;
        }
    });
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) LocalFileSystem(com.intellij.openapi.vfs.LocalFileSystem)

Example 20 with LocalFileSystem

use of com.intellij.openapi.vfs.LocalFileSystem in project intellij-community by JetBrains.

the class ImportMavenRepositoriesTask method performTask.

private void performTask() {
    if (myProject.isDisposed())
        return;
    if (ApplicationManager.getApplication().isUnitTestMode())
        return;
    final LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
    final List<PsiFile> psiFileList = ContainerUtil.newArrayList();
    final ModuleManager moduleManager = ModuleManager.getInstance(myProject);
    for (Module module : moduleManager.getModules()) {
        if (!ExternalSystemApiUtil.isExternalSystemAwareModule(GradleConstants.SYSTEM_ID, module))
            continue;
        final String modulePath = ExternalSystemApiUtil.getExternalProjectPath(module);
        if (modulePath == null)
            continue;
        String buildScript = FileUtil.findFileInProvidedPath(modulePath, GradleConstants.DEFAULT_SCRIPT_NAME);
        if (StringUtil.isEmpty(buildScript))
            continue;
        VirtualFile virtualFile = localFileSystem.refreshAndFindFileByPath(buildScript);
        if (virtualFile == null)
            continue;
        final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(virtualFile);
        if (psiFile == null)
            continue;
        psiFileList.add(psiFile);
    }
    final PsiFile[] psiFiles = ArrayUtil.toObjectArray(psiFileList, PsiFile.class);
    final Set<MavenRemoteRepository> mavenRemoteRepositories = new ReadAction<Set<MavenRemoteRepository>>() {

        @Override
        protected void run(@NotNull Result<Set<MavenRemoteRepository>> result) throws Throwable {
            Set<MavenRemoteRepository> myRemoteRepositories = ContainerUtil.newHashSet();
            for (PsiFile psiFile : psiFiles) {
                List<GrClosableBlock> repositoriesBlocks = ContainerUtil.newArrayList();
                repositoriesBlocks.addAll(findClosableBlocks(psiFile, "repositories"));
                for (GrClosableBlock closableBlock : findClosableBlocks(psiFile, "buildscript", "subprojects", "allprojects", "project", "configure")) {
                    repositoriesBlocks.addAll(findClosableBlocks(closableBlock, "repositories"));
                }
                for (GrClosableBlock repositoriesBlock : repositoriesBlocks) {
                    myRemoteRepositories.addAll(findMavenRemoteRepositories(repositoriesBlock));
                }
            }
            result.setResult(myRemoteRepositories);
        }
    }.execute().getResultObject();
    if (mavenRemoteRepositories == null || mavenRemoteRepositories.isEmpty())
        return;
    // register imported maven repository URLs but do not force to download the index
    // the index can be downloaded and/or updated later using Maven Configuration UI (Settings -> Build, Execution, Deployment -> Build tools -> Maven -> Repositories)
    MavenRepositoriesHolder.getInstance(myProject).update(mavenRemoteRepositories);
    MavenProjectIndicesManager.getInstance(myProject).scheduleUpdateIndicesList(indexes -> {
        if (myProject.isDisposed())
            return;
        final List<String> repositoriesWithEmptyIndex = ContainerUtil.mapNotNull(indexes, index -> index.getUpdateTimestamp() == -1 && MavenRepositoriesHolder.getInstance(myProject).contains(index.getRepositoryPathOrUrl()) ? index.getRepositoryPathOrUrl() : null);
        if (!repositoriesWithEmptyIndex.isEmpty()) {
            final NotificationData notificationData = new NotificationData(GradleBundle.message("gradle.integrations.maven.notification.not_updated_repository.title"), "\n<br>" + GradleBundle.message("gradle.integrations.maven.notification.not_updated_repository.text", StringUtil.join(repositoriesWithEmptyIndex, "<br>")), NotificationCategory.WARNING, NotificationSource.PROJECT_SYNC);
            notificationData.setBalloonNotification(true);
            notificationData.setBalloonGroup(UNINDEXED_MAVEN_REPOSITORIES_NOTIFICATION_GROUP);
            notificationData.setListener("#open", new NotificationListener.Adapter() {

                @Override
                protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent e) {
                    ShowSettingsUtil.getInstance().showSettingsDialog(myProject, MavenRepositoriesConfigurable.class);
                }
            });
            notificationData.setListener("#disable", new NotificationListener.Adapter() {

                @Override
                protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent e) {
                    final int result = Messages.showYesNoDialog(myProject, "Notification will be disabled for all projects.\n\n" + "Settings | Appearance & Behavior | Notifications | " + UNINDEXED_MAVEN_REPOSITORIES_NOTIFICATION_GROUP + "\ncan be used to configure the notification.", "Unindexed Maven Repositories Gradle Detection", "Disable Notification", CommonBundle.getCancelButtonText(), Messages.getWarningIcon());
                    if (result == Messages.YES) {
                        NotificationsConfigurationImpl.getInstanceImpl().changeSettings(UNINDEXED_MAVEN_REPOSITORIES_NOTIFICATION_GROUP, NotificationDisplayType.NONE, false, false);
                        notification.hideBalloon();
                    }
                }
            });
            ExternalSystemNotificationManager.getInstance(myProject).showNotification(GradleConstants.SYSTEM_ID, notificationData);
        }
    });
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) HyperlinkEvent(javax.swing.event.HyperlinkEvent) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) ModuleManager(com.intellij.openapi.module.ModuleManager) NotNull(org.jetbrains.annotations.NotNull) Notification(com.intellij.notification.Notification) Result(com.intellij.openapi.application.Result) LocalFileSystem(com.intellij.openapi.vfs.LocalFileSystem) ReadAction(com.intellij.openapi.application.ReadAction) MavenRemoteRepository(org.jetbrains.idea.maven.model.MavenRemoteRepository) MavenRepositoriesConfigurable(org.jetbrains.idea.maven.indices.MavenRepositoriesConfigurable) Module(com.intellij.openapi.module.Module) NotificationData(com.intellij.openapi.externalSystem.service.notification.NotificationData) NotificationListener(com.intellij.notification.NotificationListener)

Aggregations

LocalFileSystem (com.intellij.openapi.vfs.LocalFileSystem)58 VirtualFile (com.intellij.openapi.vfs.VirtualFile)52 File (java.io.File)27 Nullable (org.jetbrains.annotations.Nullable)9 NotNull (org.jetbrains.annotations.NotNull)8 IOException (java.io.IOException)6 Project (com.intellij.openapi.project.Project)5 Change (com.intellij.openapi.vcs.changes.Change)5 Test (org.junit.Test)5 Module (com.intellij.openapi.module.Module)4 Application (com.intellij.openapi.application.Application)3 Library (com.intellij.openapi.roots.libraries.Library)3 LibraryTable (com.intellij.openapi.roots.libraries.LibraryTable)3 VfsUtilCore.virtualToIoFile (com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile)3 PsiFile (com.intellij.psi.PsiFile)3 Notification (com.intellij.notification.Notification)2 ModuleManager (com.intellij.openapi.module.ModuleManager)2 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)2 StringUtil (com.intellij.openapi.util.text.StringUtil)2 FileAnnotation (com.intellij.openapi.vcs.annotate.FileAnnotation)2