Fork channel

Create a new channel as a copy of main.

Rename channel

Rename main to:

Delete channel

Delete main? This cannot be undone.

PijulIgnoredFileContentProvider.kt
/**
 * Dracon - An IntelliJ-Pijul integration.
 * Copyright 2021 JonathanxD <jhrldev@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.github.jonathanxd.dracon.ignore

import com.github.jonathanxd.dracon.PijulVcs
import com.github.jonathanxd.dracon.pijul.Pijul
import com.github.jonathanxd.dracon.pijul.pijul
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.LocalFilePath
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.VcsKey
import com.intellij.openapi.vcs.actions.VcsContextFactory
import com.intellij.openapi.vcs.changes.IgnoreSettingsType
import com.intellij.openapi.vcs.changes.IgnoredFileContentProvider
import com.intellij.openapi.vcs.changes.IgnoredFileDescriptor
import com.intellij.openapi.vcs.changes.IgnoredFileProvider
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcsUtil.VcsUtil
import java.nio.file.Files
import java.nio.file.Paths

private val LOG = logger<PijulIgnoredFileContentProvider>()

class PijulIgnoredFileContentProvider(private val project: Project) : IgnoredFileContentProvider {

    override fun getSupportedVcs(): VcsKey = PijulVcs.KEY

    override fun getFileName() = ".ignore"

    override fun buildIgnoreFileContent(
        ignoreFileRoot: VirtualFile,
        ignoredFileProviders: Array<IgnoredFileProvider>
    ): String {
        if (!Pijul.isUnderPijul(ignoreFileRoot)) return ""
        val repoRoot = VcsUtil.getVcsRootFor(project, ignoreFileRoot)
        if (repoRoot == null || repoRoot != ignoreFileRoot) return ""

        val content = StringBuilder()
        val lineSeparator = System.lineSeparator()
        val untrackedFiles = getUntrackedFiles(repoRoot, VcsUtil.getFilePath(ignoreFileRoot))

        if (untrackedFiles.isEmpty()) return ""

        for (provider in ignoredFileProviders) {
            val ignoredFiles =
                provider.getIgnoredFiles(project).ignoreBeansToRelativePaths(ignoreFileRoot, untrackedFiles)

            if (ignoredFiles.isEmpty()) continue

            if (content.isNotEmpty()) {
                content.append(lineSeparator).append(lineSeparator)
            }

            val description = provider.ignoredGroupDescription

            if (description.isNotBlank()) {
                content.append(buildIgnoreGroupDescription(provider))
                content.append(lineSeparator)
            }

            content.append(ignoredFiles.joinToString(lineSeparator))
        }

        return content.toString()//if (content.isNotEmpty()) "syntax: glob$lineSeparator$lineSeparator$content" else ""
    }

    private fun getUntrackedFiles(root: VirtualFile, ignoreFileRoot: FilePath): Set<FilePath> =
        try {
            val rootPath = Paths.get(VcsUtil.getFilePath(root).path)
            HashSet(
                pijul(project).untrackedFiles(project, rootPath)
                    .result!!
                    .map {
                        LocalFilePath(it, Files.isDirectory(it))
                    }.filter {
                        isAncestor(ignoreFileRoot, it, true)
                    }
            )
        } catch (e: VcsException) {
            LOG.warn("Cannot get untracked files: ", e)
            emptySet()
        }

    fun isAncestor(ancestor: FilePath, file: FilePath, strict: Boolean): Boolean {
        var parent = if (strict) file.parentPath else file
        while (true) {
            if (parent == null) return false
            if (parent == ancestor) return true
            parent = parent.parentPath
        }
    }

    private fun Iterable<IgnoredFileDescriptor>.ignoreBeansToRelativePaths(
        ignoreFileRoot: VirtualFile,
        untrackedFiles: Set<FilePath>
    ): List<String> {
        val vcsRoot = VcsUtil.getVcsRootFor(project, ignoreFileRoot)
        val vcsContextFactory = VcsContextFactory.SERVICE.getInstance()
        return filter { ignoredBean ->
            when (ignoredBean.type) {
                IgnoreSettingsType.UNDER_DIR -> shouldIgnoreUnderDir(
                    ignoredBean,
                    untrackedFiles,
                    ignoreFileRoot,
                    vcsRoot,
                    vcsContextFactory
                )
                IgnoreSettingsType.FILE -> shouldIgnoreFile(
                    ignoredBean,
                    untrackedFiles,
                    ignoreFileRoot,
                    vcsRoot,
                    vcsContextFactory
                )
                IgnoreSettingsType.MASK -> shouldIgnoreByMask(ignoredBean, untrackedFiles)
            }
        }.map { ignoredBean ->
            when (ignoredBean.type) {
                IgnoreSettingsType.MASK -> ignoredBean.mask!!
                IgnoreSettingsType.UNDER_DIR -> buildIgnoreEntryContent(ignoreFileRoot, ignoredBean)
                IgnoreSettingsType.FILE -> buildIgnoreEntryContent(ignoreFileRoot, ignoredBean)
            }
        }
    }

    private fun shouldIgnoreUnderDir(
        ignoredBean: IgnoredFileDescriptor,
        untrackedFiles: Set<FilePath>,
        ignoreFileRoot: VirtualFile,
        vcsRoot: VirtualFile?,
        vcsContextFactory: VcsContextFactory
    ) =
        FileUtil.exists(ignoredBean.path)
                && untrackedFiles.any { FileUtil.isAncestor(ignoredBean.path!!, it.path, true) }
                && FileUtil.isAncestor(ignoreFileRoot.path, ignoredBean.path!!, false)
                && Comparing.equal(
            vcsRoot,
            VcsUtil.getVcsRootFor(project, vcsContextFactory.createFilePath(ignoredBean.path!!, true))
        )

    private fun shouldIgnoreFile(
        ignoredBean: IgnoredFileDescriptor,
        untrackedFiles: Set<FilePath>,
        ignoreFileRoot: VirtualFile,
        vcsRoot: VirtualFile?,
        vcsContextFactory: VcsContextFactory
    ) =
        FileUtil.exists(ignoredBean.path)
                && untrackedFiles.any { ignoredBean.matchesFile(it) }
                && FileUtil.isAncestor(ignoreFileRoot.path, ignoredBean.path!!, false)
                && Comparing.equal(
            vcsRoot,
            VcsUtil.getVcsRootFor(project, vcsContextFactory.createFilePath(ignoredBean.path!!, false))
        )

    private fun shouldIgnoreByMask(ignoredBean: IgnoredFileDescriptor, untrackedFiles: Set<FilePath>) =
        untrackedFiles.any { ignoredBean.matchesFile(it) }

    override fun buildUnignoreContent(ignorePattern: String) = throw UnsupportedOperationException()

    override fun buildIgnoreGroupDescription(ignoredFileProvider: IgnoredFileProvider) =
        prependCommentHashCharacterIfNeeded(ignoredFileProvider.ignoredGroupDescription)

    override fun buildIgnoreEntryContent(ignoreEntryRoot: VirtualFile, ignoredFileDescriptor: IgnoredFileDescriptor) =
        FileUtil.getRelativePath(ignoreEntryRoot.path, ignoredFileDescriptor.path!!, '/') ?: ""

    override fun supportIgnoreFileNotInVcsRoot() = false

    private fun prependCommentHashCharacterIfNeeded(description: @NlsSafe String): @NlsSafe String =
        if (description.startsWith("#")) description else "# $description"
}