Fork channel

Create a new channel as a copy of main.

Rename channel

Rename main to:

Delete channel

Delete main? This cannot be undone.

PijulCmd.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.cmd

import com.github.jonathanxd.dracon.cache.HashMapCache
import com.github.jonathanxd.dracon.cache.PijulCache
import com.github.jonathanxd.dracon.cache.PijulLogEntryCache
import com.github.jonathanxd.dracon.changes.PijulCommittedChangeList
import com.github.jonathanxd.dracon.channel.ChannelInfo
import com.github.jonathanxd.dracon.channel.PijulChannel
import com.github.jonathanxd.dracon.config.PijulSettings
import com.github.jonathanxd.dracon.content.PijulContentRevision
import com.github.jonathanxd.dracon.context.PijulVcsContext
import com.github.jonathanxd.dracon.editor.EditorServer
import com.github.jonathanxd.dracon.editor.editorServerPath
import com.github.jonathanxd.dracon.editor.freePort
import com.github.jonathanxd.dracon.exec.execInTerminal
import com.github.jonathanxd.dracon.exec.terminalCommand
import com.github.jonathanxd.dracon.i18n.DraconBundle
import com.github.jonathanxd.dracon.log.*
import com.github.jonathanxd.dracon.pijul.*
import com.github.jonathanxd.dracon.pijul.credit.PijulCredit
import com.github.jonathanxd.dracon.pijul.credit.parseCredit
import com.github.jonathanxd.dracon.pijul.diff.PijulDiffJson
import com.github.jonathanxd.dracon.pijul.diff.toFileStatusMap
import com.github.jonathanxd.dracon.pijulVcs
import com.github.jonathanxd.dracon.revision.ChannelRevision
import com.github.jonathanxd.dracon.revision.ChannelRevisions
import com.github.jonathanxd.dracon.revision.PijulRevisionNumber
import com.github.jonathanxd.dracon.revision.PijulVcsFileRevision
import com.github.jonathanxd.dracon.util.*
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.FileStatus
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.text.trimMiddle
import com.intellij.vcs.log.VcsUser
import com.intellij.vcs.log.impl.VcsUserImpl
import com.intellij.vcsUtil.VcsFileUtil
import com.intellij.vcsUtil.VcsUtil
import kotlinx.coroutines.*
import java.nio.file.*
import java.util.*
import java.util.concurrent.CompletableFuture
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.relativeTo
import kotlin.streams.toList
import org.jetbrains.plugins.terminal.LocalTerminalDirectRunner
import org.jetbrains.plugins.terminal.TerminalView
import java.util.concurrent.Executors
import java.util.concurrent.locks.ReentrantLock

/**
 * Command-line based implementation of [Pijul] interface.
 *
 * An IPC (Inter Process Communication) version of [Pijul] could be implemented in the future,
 * however, an command-line based is enough for now.
 */
class PijulCmd(val project: Project) : Pijul {

    val pijulProcessContext = Executors.newSingleThreadExecutor(NamedThreadFactory("Pijul")).asCoroutineDispatcher()


    private val lock = ReentrantLock()
    private val cache: PijulCache = HashMapCache()
    private val pijulLogEntryCache by lazy {
        this.project.service<PijulLogEntryCache>()
    }


    @RequiresBackgroundThread
    override fun init(project: Project, root: VirtualFile): PijulOperationResult<Unit> {
        val path = Paths.get(VcsUtil.getFilePath(root).path)

        val execution = this.createExecPijulOperation(project, path, listOf("init", path.toString()))

        return this.doExecution("init", execution)
    }

    @RequiresBackgroundThread
    override fun init(project: Project, root: Path): PijulOperationResult<Unit> {
        val execution = this.createExecPijulOperation(project, root, listOf("init", root.toString()))

        return this.doExecution("init", execution)
    }

    @RequiresBackgroundThread
    override fun add(project: Project, root: VirtualFile, paths: List<FilePath>): PijulOperationResult<Unit> {
        val path = Paths.get(VcsUtil.getFilePath(root).path)

        val results = mutableListOf<PijulOperationResult<Unit>>()

        if (paths.isEmpty()) {
            val execution = this.createExecPijulOperation(project, path, listOf("add", "-r") + root.path)
            results + this.doExecution("add", execution)
        } else {
            for (pathList in VcsFileUtil.chunkPaths(root, paths)) {
                val execution = if (pathList.all { Files.isRegularFile(path.resolve(it)) }) {
                    this.createExecPijulOperation(project, path, listOf("add") + pathList)
                } else {
                    this.createExecPijulOperation(project, path, listOf("add", "-r") + pathList)
                }

                results + this.doExecution("add", execution)
            }
        }

        for (result in results) {
            if (result.statusCode !is SuccessStatusCode)
                return result
        }

        return PijulOperationResult("add", SuccessStatusCode, Unit)
    }

    @OptIn(ExperimentalPathApi::class)
    @RequiresBackgroundThread
    override fun fileStatus(project: Project, file: VirtualFile): PijulOperationResult<FileStatus> {
        val root = ProjectLevelVcsManager.getInstance(project).getVcsRootFor(file)
            ?: return PijulOperationResult("file_status", SuccessStatusCode, FileStatus.UNKNOWN)
        val rootPath = Paths.get(VcsUtil.getFilePath(root).path)

        val execution = this.createPainlessExecPijulOperation(project, rootPath, listOf("diff", "--json"), logOutput = false)

        val fileStatusBasedInPijulDiff = this.doExecutionWithMapper("file_status", execution) {
            try {
                val changes = PijulDiffJson.parseJson(it)
                val changeMap = changes.toFileStatusMap()

                val fPath = Paths.get(VcsUtil.getFilePath(file.path).path).relativeTo(rootPath).toString()
                if (fPath.isEmpty()) {
                    FileStatus.SUPPRESSED
                } else {
                    changeMap[fPath]?.firstOrNull()
                }
            } catch (t: Throwable) {
                logger<PijulCmd>().error(t)
                null
            }
        }

        val fileStatusBasedInPijulLs =
            this.doExecutionWithMapper(
                "file_status_from_ls",
                this.createExecPijulOperation(project, rootPath, listOf("ls"), log = false)
            ) {
                val trackedFiles = it.split("\n")

                val fPath = Paths.get(VcsUtil.getFilePath(file.path).path).relativeTo(rootPath).toString()
                if (trackedFiles.contains(fPath)) {
                    FileStatus.NOT_CHANGED
                } else {
                    FileStatus.UNKNOWN
                }
            }

        return if (fileStatusBasedInPijulDiff.statusCode !is SuccessStatusCode
            || fileStatusBasedInPijulDiff.result == null
            || fileStatusBasedInPijulDiff.result == FileStatus.SUPPRESSED
        ) {
            fileStatusBasedInPijulLs
        } else {
            fileStatusBasedInPijulDiff
        }
    }

    @OptIn(ExperimentalPathApi::class)
    @RequiresBackgroundThread
    override fun fileStatus(project: Project, file: Path): PijulOperationResult<FileStatus> {
        val root = project.service<PijulVcsContext>().root

        val execution = this.createPainlessExecPijulOperation(project, root, listOf("diff", "--json"), logOutput = false)

        val fileStatusBasedInPijulDiff = this.doExecutionWithMapper("file_status", execution) {
            try {
                val changes = PijulDiffJson.parseJson(it)
                val changeMap = changes.toFileStatusMap()

                val fPath = file.relativeTo(root).toString()
                if (fPath.isEmpty()) {
                    FileStatus.SUPPRESSED
                } else {
                    changeMap[fPath]?.firstOrNull()
                }
            } catch (t: Throwable) {
                logger<PijulCmd>().error(t)
                null
            }
        }

        val fileStatusBasedInPijulLs =
            this.doExecutionWithMapper(
                "file_status_from_ls",
                this.createExecPijulOperation(project, root, listOf("ls"), log = false)
            ) {
                val trackedFiles = it.split("\n")

                val fPath = file.relativeTo(root).toString()
                if (trackedFiles.contains(fPath)) {
                    FileStatus.NOT_CHANGED
                } else {
                    FileStatus.UNKNOWN
                }
            }

        return if (fileStatusBasedInPijulDiff.statusCode !is SuccessStatusCode
            || fileStatusBasedInPijulDiff.result == null
            || fileStatusBasedInPijulDiff.result == FileStatus.SUPPRESSED
        ) {
            fileStatusBasedInPijulLs
        } else {
            fileStatusBasedInPijulDiff
        }
    }

    @OptIn(ExperimentalPathApi::class)
    override fun credit(project: Project, root: Path, file: Path): PijulOperationResult<PijulCredit> {
        val filePath = file.relativeTo(root).toString()

        val credit = this.doExecutionWithMapper(
            "credit",
            this.createExecPijulOperation(project, root, listOf("credit", filePath))
        ) {
            if (it.isEmpty() || it.trim().isEmpty() || it.trim().isBlank()) null
            else it.parseCredit()
        }

        return credit
    }

    override fun untrackedFiles(project: Project, root: Path): PijulOperationResult<List<Path>> {
        return this.trackedFiles(project, root)
            .andThenValue { tracked ->
                Files.walk(root, FileVisitOption.FOLLOW_LINKS)
                    .filter { !tracked.contains(it) }
                    .toList()
            }
    }

    override fun fileStatusMap(project: Project): PijulOperationResult<PijulFilesStatus> {
        val root = project.service<PijulVcsContext>().root

        val fileStatusMap = mutableMapOf<Path, List<FileStatus>>()
        val tracked = mutableListOf<Path>()
        val execution = this.createPainlessExecPijulOperation(project, root, listOf("diff", "--json"), logOutput = false)

        val fileStatusBasedInPijulDiff = this.doExecutionWithMapper("file_status", execution) {
            try {
                val changes = PijulDiffJson.parseJson(it)
                val changeMap = changes.toFileStatusMap()
                for (c in changeMap) {
                    fileStatusMap[root.resolve(c.key)] = c.value
                }
            } catch (t: Throwable) {
                logger<PijulCmd>().error(t)
                null
            }
        }

        val fileStatusBasedInPijulLs =
            this.doExecutionWithMapper(
                "file_status_from_ls",
                this.createExecPijulOperation(project, root, listOf("ls"), log = false)
            ) {
                it.split("\n").mapTo(tracked) {
                    root.resolve(it)
                }
            }

        if (fileStatusBasedInPijulDiff.statusCode !is SuccessStatusCode) {
            return fileStatusBasedInPijulDiff as PijulOperationResult<PijulFilesStatus>
        }

        if (fileStatusBasedInPijulLs.statusCode !is SuccessStatusCode) {
            return fileStatusBasedInPijulLs as PijulOperationResult<PijulFilesStatus>
        }

        return PijulOperationResult("file_status", SuccessStatusCode, PijulFilesStatus(fileStatusMap, tracked))
    }

    override fun trackedFiles(project: Project, root: Path): PijulOperationResult<List<Path>> {
        return this.doExecutionWithMapper(
            "tracked_files_from_ls",
            this.createExecPijulOperation(project, root, listOf("ls"), log = false)
        ) {
            it.split("\n").map {
                root.resolve(it)
            }
        }
    }

    override fun rollbackTo(hash: String, project: Project, root: Path): PijulOperationResult<Boolean> {
        val logHashExecution = this.createPainlessExecPijulOperation(project, root, listOf("log", "--hash-only"))

        val hashes = this.doExecutionWithMapper("log--hash-only", logHashExecution) {
            it.lines()
        }

        if (hashes.statusCode !is SuccessStatusCode) {
            return hashes as PijulOperationResult<Boolean>
        } else {
            val hashList = hashes.result!!

            if (hashList.none { it == hash } || hashList.isEmpty()) {
                return PijulOperationResult(
                    "rollbackTo_${hash}",
                    NonZeroExitStatusCode(-1, "Could not find hash $hash in Pijul log."),
                    false
                )
            } else {
                if (hashList[0] == hash) {
                    return PijulOperationResult("rollbackTo_${hash}", SuccessStatusCode, true)
                } else {
                    val rollbacks = hashList.subList(0, hashList.indexOf(hash))

                    val rollback = this.doExecution(
                        "rollback_from_${hashList[0]}_until_$hash",
                        this.createPainlessExecPijulOperation(project, root, listOf("unrecord", "--reset") + rollbacks)
                    )

                    if (rollback.statusCode !is SuccessStatusCode) {
                        return rollback as PijulOperationResult<Boolean>
                    }

                    val reset = this.reset(project, root)

                    if (reset.statusCode !is SuccessStatusCode) {
                        return reset
                    }

                    return PijulOperationResult("rollbackTo_${hash}", SuccessStatusCode, true)
                }
            }
        }
    }

    override fun unrecord(project: Project, root: Path, hash: String): PijulOperationResult<Boolean> {
        val unrecord = this.doExecution(
            "unrecord_$hash",
            this.createPainlessExecPijulOperation(project, root, listOf("unrecord", "--reset", hash))
        )

        if (unrecord.statusCode !is SuccessStatusCode) {
            return unrecord as PijulOperationResult<Boolean>
        }

        val reset = this.reset(project, root)

        if (reset.statusCode !is SuccessStatusCode) {
            return reset
        }

        return PijulOperationResult("unrecord_${hash}", SuccessStatusCode, true)

    }

    override fun record(
        project: Project,
        root: Path,
        files: List<Path>,
        author: VcsUser?,
        message: String
    ): PijulOperationResult<Boolean> {
        val arguments = mutableListOf<String>("record")

        arguments.add("-a")
        if (author != null) {
            arguments.add("--author")
            arguments.add(author.name)
        }

        arguments.add("--message")
        arguments.add(message)

        if (files.isNotEmpty()) {
            arguments.add("--")
            arguments.addAll(files.map { it.toString() })
        } else {
            return PijulOperationResult("record", NonZeroExitStatusCode(-1, "Empty list of paths to record"), false)
        }

        return this.doExecutionWithMapper(
            "record",
            this.createPainlessExecPijulOperation(this.project, root, arguments)
        ) {
            true
        }
    }

    override fun recordToString(
        project: Project,
        root: Path
    ): PijulOperationResult<String> {
        val arguments = mutableListOf("record")

        val uuid = UUID.randomUUID().toString()
        val tempFile = createCopieTempFile(uuid)

        val operation = this.createPainlessExecPijulWithCopieOperation(
            this.project,
            root,
            tempFile,
            CopieMode.TO,
            arguments
        )
        return this.doExecutionWithMapperEvenFailed("record", operation) {
            val data = Files.readString(tempFile, Charsets.UTF_8)
            deleteCopieTempDir(uuid)
            data
        }
    }

    override fun record(
        project: Project,
        root: Path,
        editorServerConsumer: (EditorServer) -> Unit
    ): PijulOperationResult<String> {
        val arguments = mutableListOf("record")

        val operation = this.createPainlessExecPijulWithEditorServer(
            this.project,
            root,
            arguments,
            editorServerConsumer
        )
        return this.doExecutionWithMapper("record", operation) {
            it
        }
    }

    override fun push(
        project: Project,
        root: Path,
        editorServerConsumer: (EditorServer) -> Unit
    ): PijulOperationResult<String> {
        val arguments = mutableListOf("push")

        val operation = this.createPainlessExecPijulWithEditorServer(
            this.project,
            root,
            arguments,
            editorServerConsumer
        )
        return this.doExecutionWithMapper("push", operation) {
            it
        }
    }

    override fun push(
        project: Project,
        root: Path,
        fromChannel: String?,
        toChannel: String?,
        repository: String?,
        editorServerConsumer: (EditorServer) -> Unit
    ): PijulOperationResult<String> {
        val arguments = mutableListOf("push")

        if (fromChannel != null) {
            arguments.add("--from-channel")
            arguments.add(fromChannel)
        }

        if (toChannel != null) {
            arguments.add("--to-channel")
            arguments.add(toChannel)
        }

        if (repository != null) {
            arguments.add(repository)
        }

        val operation = this.createPainlessExecPijulWithEditorServer(
            this.project,
            root,
            arguments,
            editorServerConsumer
        )
        return this.doExecutionWithMapper("push", operation) {
            it
        }
    }

    override fun pushInTerminal(
        project: Project,
        root: Path,
        fromChannel: String?,
        toChannel: String?,
        repository: String?,
        editorServerConsumer: (EditorServer) -> Unit
    ): PijulOperationResult<String> {
        val arguments = mutableListOf("push")

        if (fromChannel != null) {
            arguments.add("--from-channel")
            arguments.add(fromChannel)
        }

        if (toChannel != null) {
            arguments.add("--to-channel")
            arguments.add(toChannel)
        }

        if (repository != null) {
            arguments.add(repository)
        }

        val operation = this.createPainlessExecPijulWithEditorServerInTerminal(
            this.project,
            root,
            arguments,
            editorServerConsumer
        )
        return this.doExecutionWithMapper("push", operation) {
            it
        }
    }

    override fun recordFromString(project: Project, root: Path, record: String): PijulOperationResult<String> {
        val arguments = mutableListOf("record")

        val uuid = UUID.randomUUID().toString()
        val tempFile = createCopieTempFile(uuid)

        Files.writeString(tempFile, record, Charsets.UTF_8, StandardOpenOption.CREATE_NEW)

        val operation = this.createPainlessExecPijulWithCopieOperation(
            this.project,
            root,
            tempFile,
            CopieMode.FROM,
            arguments
        )

        return this.doExecutionWithMapper("record", operation) {
            deleteCopieTempDir(uuid)
            it
        }
    }

    override fun reset(project: Project, root: Path): PijulOperationResult<Boolean> {
        val resetExecution = this.createExecPijulOperation(project, root, listOf("reset"))

        return this.doExecutionWithMapper("reset", resetExecution) {
            true
        }
    }

    override fun revisions(project: Project, root: Path, file: Path): PijulOperationResult<List<PijulVcsFileRevision>> {
        val historyList = mutableListOf<PijulVcsFileRevision>()

        val channels = this.channel(this.project, root)
        val currentChannel = channels.result?.channels?.firstOrNull { it.current }?.name

        val result = this.fileHistory(project, root, file, {
            it.hunks.filterIsInstance<HunkWithPath>().groupBy {
                it.resolvePath(root)
            }.forEach { (path, hunks) ->
                val deleted = hunks.any { it is FileDelHunk }
                historyList.add(
                    PijulVcsFileRevision(
                        this.project,
                        root,
                        path,
                        PijulRevisionNumber(it.changeHash, it.date),
                        it.authors.map { VcsUserImpl(it.name ?: "", it.email ?: "") }.filter { it.name.isNotEmpty() },
                        it.message,
                        currentChannel,
                        deleted
                    )
                )
            }
        }, {})

        return PijulOperationResult(result.operation, result.statusCode, historyList)
    }

    override fun log(project: Project, root: VirtualFile): PijulOperationResult<PijulLog> {
        val rootPath = Paths.get(VcsUtil.getFilePath(root).path)

        return this.log(project, rootPath)
    }

    override fun tags(project: Project, root: Path): PijulOperationResult<List<PijulTag>> {
        val result = this.doExecutionWithMapperEvenFailed("tag", this.createPainlessExecPijulOperation(project, root, listOf("tag"))) {
            it.parseTags()
        }

        if (result.result != null && result.result.isNotEmpty()) { // Force success because Pijul is failing with `Not a directory` even in success case.
            return PijulOperationResult("tag", SuccessStatusCode, result.result)
        } else {
            return result
        }
    }

    override fun log(project: Project, root: Path): PijulOperationResult<PijulLog> {

        val logHashExecution = this.createPainlessExecPijulOperation(project, root, listOf("log", "--hash-only"))

        val hashes = this.doExecutionWithMapper("log--hash-only", logHashExecution) {
            it.lines()
        }

        if (hashes.statusCode !is SuccessStatusCode) {
            return hashes as PijulOperationResult<PijulLog>
        } else {
            val entries = mutableListOf<PijulLogEntry>()
            for (hash in hashes.result!!) {
                if (hash.isEmpty()) {
                    break
                }

                val change = this.pijulLogEntryCache.load(hash) {
                    this.doExecutionWithMapper(
                        "change-$hash",
                        this.createPainlessExecPijulOperation(project, root, listOf("change", hash))
                    ) {
                        it.parseChange(hash)
                    }
                }

                if (change.statusCode !is SuccessStatusCode) {
                    return change as PijulOperationResult<PijulLog>
                } else if (change.result != null) {
                    entries += change.result
                }
            }

            return PijulOperationResult(hashes.operation, hashes.statusCode, PijulLog(entries))
        }
    }

    override fun log(project: Project, root: Path, channel: String): PijulOperationResult<PijulLog> {

        val logHashExecution = this.createPainlessExecPijulOperation(project, root, listOf("log", "--hash-only", "--channel", channel))

        val hashes = this.doExecutionWithMapper("log--hash-only", logHashExecution) {
            it.lines()
        }

        if (hashes.statusCode !is SuccessStatusCode) {
            return hashes as PijulOperationResult<PijulLog>
        } else {
            val entries = mutableListOf<PijulLogEntry>()
            for (hash in hashes.result!!) {
                if (hash.isEmpty()) {
                    break
                }

                val change = this.pijulLogEntryCache.load(hash) {
                    this.doExecutionWithMapper(
                        "change-$hash",
                        this.createPainlessExecPijulOperation(project, root, listOf("change", hash))
                    ) {
                        it.parseChange(hash)
                    }
                }

                if (change.statusCode !is SuccessStatusCode) {
                    return change as PijulOperationResult<PijulLog>
                } else if (change.result != null) {
                    entries += change.result
                }
            }

            return PijulOperationResult(hashes.operation, hashes.statusCode, PijulLog(entries))
        }
    }

    @OptIn(ExperimentalPathApi::class)
    override fun fileHistory(
        project: Project,
        root: VirtualFile,
        file: FilePath,
        consumer: (PijulLogEntry) -> Unit,
        errorConsumer: (PijulOperationResult<Unit>) -> Unit
    ): PijulOperationResult<Unit> {
        val ctx = project.service<PijulVcsContext>()
        val rootPath = Paths.get(VcsUtil.getFilePath(root).path)
        val filePath = ctx.resolveUnderVcs(file)
        val isRootPath = ctx.isRootPath(filePath)
        val filePathAsStr = ctx.resolveRelativeToRoot(filePath)

        return this.fileHistory(project, rootPath, filePath, consumer, errorConsumer)
    }


    @OptIn(ExperimentalPathApi::class)
    override fun fileHistory(
        project: Project,
        root: Path,
        file: Path,
        consumer: (PijulLogEntry) -> Unit,
        errorConsumer: (PijulOperationResult<Unit>) -> Unit
    ): PijulOperationResult<Unit> {
        val ctx = project.service<PijulVcsContext>()
        val filePath = ctx.resolveUnderVcs(file)
        val isRootPath = ctx.isRootPath(filePath)

        val logHashExecution = this.createPainlessExecPijulOperation(project, root, listOf("log", "--hash-only"))

        val hashes = this.doExecutionWithMapper("log--hash-only", logHashExecution) {
            it.lines()
        }

        if (hashes.statusCode !is SuccessStatusCode) {
            errorConsumer(hashes as PijulOperationResult<Unit>)
            return hashes
        } else {
            val hashList = hashes.result!!

            for (hash in hashList) {
                if (hash.isEmpty()) {
                    break
                }

                val change = this.pijulLogEntryCache.load(hash) {
                    this.doExecutionWithMapper(
                        "change-$hash",
                        this.createPainlessExecPijulOperation(project, root, listOf("change", hash))
                    ) {
                        it.parseChange(hash)
                    }
                }

                if (change.statusCode !is SuccessStatusCode) {
                    errorConsumer(change as PijulOperationResult<Unit>)
                } else if (change.result != null) {

                    var shouldConsume = false
                    var isAdd = false
                    for (hunk in change.result.hunks) {
                        if (hunk is HunkWithPath) {
                            val hunkPath = hunk.resolvePath(root)

                            if (isRootPath) {
                                shouldConsume = true
                            } else {
                                if (Files.isDirectory(filePath)) {
                                    if (hunkPath == filePath) {
                                        if (hunk is FileAddHunk) {
                                            isAdd = true
                                        }
                                        shouldConsume = true
                                    } else if (hunkPath.startsWith(filePath)) {
                                        shouldConsume = true
                                    }
                                } else {
                                    if (hunkPath == filePath) {
                                        if (hunk is FileAddHunk) {
                                            isAdd = true
                                        }

                                        shouldConsume = true
                                    }
                                }
                            }
                        }
                    }

                    if (shouldConsume) {
                        consumer(change.result)
                    }

                    if (isAdd) {
                        break
                    }
                }
            }
        }

        return hashes as PijulOperationResult<Unit>
    }

    override fun changes(
        project: Project,
        root: Path,
        revision: String?,
        maxCount: Int,
        filter: (PijulLogEntry) -> Boolean,
        consumer: (PijulCommittedChangeList) -> Unit
    ): PijulOperationResult<Unit> {
        val allRevisions = pijul(this.project).allRevisions(this.project, root).result!!

        val log = this.log(this.project, root)

        return log.result?.entries?.filter {
            filter(it)
        }?.filter {
            revision == null || it.revision.hash == revision
        }?.asSequence()?.map { entry ->
            PijulCommittedChangeList(
                entry.message.trimMiddle(20),
                entry.message,
                entry.authors.firstOrNull()?.name ?: "No author",
                Date.from(entry.date.toInstant()),
                entry.hunks.filterIsInstance<HunkWithPath>().groupBy { it.resolvePath(root) }.map { (p, hunks) ->
                    val hunk = hunks.firstOrNull { it is EditHunk }
                        ?: hunks.firstOrNull { it is ReplacementHunk }
                        ?: hunks.firstOrNull { it is FileDelHunk }
                        ?: hunks.firstOrNull { it is FileAddHunk }
                        ?: hunks.first()

                    val beforeRevision =
                        if (hunk is FileAddHunk) null
                        else findARevisionBefore(entry.changeHash, allRevisions)?.let {
                            PijulContentRevision(
                                root,
                                hunk.resolvePath(root),
                                it,
                                this.project
                            )
                        }

                    val afterRevision =
                        if (hunk is FileDelHunk) null
                        else PijulContentRevision(
                            root,
                            hunk.resolvePath(root),
                            entry.revision,
                            this.project
                        )

                    Change(
                        beforeRevision,
                        afterRevision,
                        hunk.status
                    )
                }.toMutableList(),
                entry.revision,
                false,
                pijulVcs(this.project)
            )
        }?.let { if (maxCount == -1) it else it.take(maxCount) }?.forEach {
            consumer(it)
        }?.let {
            PijulOperationResult("changes", SuccessStatusCode, Unit)
        } ?: PijulOperationResult("changes", log.statusCode, Unit)

    }


    fun findARevisionBefore(current: String, allRevisions: List<PijulRevisionNumber>): PijulRevisionNumber? {
        for (i in allRevisions.indices) {
            if (current == allRevisions[i].hash) {
                return if (i + 1 >= allRevisions.size) {
                    null
                } else {
                    allRevisions[i + 1]
                }
            }
        }

        return null
    }

    override fun diff(project: Project, root: VirtualFile): PijulOperationResult<PijulLogEntry> {
        val rootPath = Paths.get(VcsUtil.getFilePath(root).path)

        val change =
            this.doExecutionWithMapper("diff", this.createExecPijulOperation(project, rootPath, listOf("diff"))) {
                if (it.isEmpty()) null
                else it.parseChange("")
            }

        return change
    }

    override fun diff(project: Project, root: Path): PijulOperationResult<PijulLogEntry> {
        val change = this.doExecutionWithMapper("diff", this.createExecPijulOperation(project, root, listOf("diff"))) {
            if (it.isEmpty()) null
            else it.parseChange("")
        }

        return change
    }

    override fun latestRevisionNumber(project: Project, root: VirtualFile): PijulOperationResult<PijulRevisionNumber> {
        /*val root = ProjectLevelVcsManager.getInstance(project).getVcsRootFor(file)
            ?: return PijulOperationResult("file_status", SuccessStatusCode, FileStatus.UNKNOWN)*/
        val rootPath = Paths.get(VcsUtil.getFilePath(root).path)

        val log = this.log(project, root)

        return PijulOperationResult(log.operation, log.statusCode,
            log.result?.entries?.firstOrNull()?.let {
                PijulRevisionNumber(it.changeHash, it.date)
            }
        )
    }

    override fun latestRevisionNumber(project: Project, root: Path): PijulOperationResult<PijulRevisionNumber> {
        /*val root = ProjectLevelVcsManager.getInstance(project).getVcsRootFor(file)
            ?: return PijulOperationResult("file_status", SuccessStatusCode, FileStatus.UNKNOWN)*/
        val log = this.log(project, root)

        return PijulOperationResult(log.operation, log.statusCode,
            log.result?.entries?.firstOrNull()?.let {
                PijulRevisionNumber(it.changeHash, it.date)
            }
        )
    }

    override fun revisionByChannel(project: Project, root: Path): PijulOperationResult<ChannelRevisions> {
        return this.channel(project, root).flatMap {
            val mapped = it.channels.map { ch ->
                this.log(project, root, ch.name).map {
                    it.entries.firstOrNull()?.let {
                        ChannelRevision(ch.name, PijulRevisionNumber(it.changeHash, it.date))
                    }
                }
            }

            for (m in mapped) {
                if (m.result == null)
                    return@flatMap m as PijulOperationResult<ChannelRevisions>
            }

            PijulOperationResult(
                "revision by channel",
                SuccessStatusCode,
                ChannelRevisions(mapped.map { it.result!! })
            )
        }
    }

    override fun latestRevisionNumberForPath(
        project: Project,
        root: Path,
        filePath: Path
    ): PijulOperationResult<PijulRevisionNumber> {
        val log = this.log(project, root)

        return PijulOperationResult(log.operation, log.statusCode,
            log.result?.entries?.firstOrNull {
                it.hunks.filterIsInstance<HunkWithPath>().firstOrNull {
                    val resolved = it.resolvePath(root)
                    filePath == resolved
                } != null
            }?.let {
                PijulRevisionNumber(it.changeHash, it.date)
            }
        )
    }

    override fun allRevisions(project: Project, root: Path): PijulOperationResult<List<PijulRevisionNumber>> {
        val log = this.log(project, root)

        return PijulOperationResult(log.operation, log.statusCode,
            log.result?.entries?.map {
                PijulRevisionNumber(it.changeHash, it.date)
            }
        )
    }

    override fun channel(project: Project, root: VirtualFile): PijulOperationResult<ChannelInfo> {
        val rootPath = root.toNioPath()
        return this.channel(project, rootPath)
    }

    override fun channel(project: Project, root: Path): PijulOperationResult<ChannelInfo> {
        val channelOperation = this.createPainlessExecPijulOperation(project, root, listOf("channel"))

        return this.doExecutionWithMapper("channel list", channelOperation) {
            val channels = it.split("\n")
            if (channels.isEmpty()) null
            else ChannelInfo(channels.filter { it.isNotEmpty() }.map {
                val name = it.substring(1)
                val effectiveName = if (name.startsWith(" ")) name.substring(1) else name
                PijulChannel(it[0] == '*', effectiveName)
            })
        }
    }

    fun doExecution(name: String, execution: PijulExecution): PijulOperationResult<Unit> {
        val status = execution.status

        return if (status == 0) {
            PijulOperationResult(name, SuccessStatusCode, Unit)
        } else {
            val error = execution.errorStream
            PijulOperationResult(name, NonZeroExitStatusCode(status, error), Unit)
        }
    }

    fun <T> doExecutionWithMapper(
        name: String,
        execution: PijulExecution,
        regularStreamStringMapper: (String) -> T?
    ): PijulOperationResult<T> {
        val status = execution.status

        return if (status == 0) {
            val std = execution.regularStream

            PijulOperationResult(name, SuccessStatusCode, regularStreamStringMapper(std))
        } else {
            val error = execution.errorStream

            PijulOperationResult(name, NonZeroExitStatusCode(status, error), null) as PijulOperationResult<T>
        }
    }

    fun <T> doExecutionWithMapperEvenFailed(
        name: String,
        execution: PijulExecution,
        regularStreamStringMapper: (String) -> T?
    ): PijulOperationResult<T> {
        val status = execution.status

        return if (status == 0) {
            val std = execution.regularStream

            PijulOperationResult(name, SuccessStatusCode, regularStreamStringMapper(std))
        } else {
            val std = execution.regularStream
            val error = execution.errorStream

            PijulOperationResult(name, NonZeroExitStatusCode(status, error), regularStreamStringMapper(std))
        }
    }

    /**
     * Creates a [PijulExecution] operation that could be executed at any time. This operation uses Kotlin Coroutines
     * and can be executed immediately through [doExecution] or through [doExecutionWithMapper].
     *
     * As this implementation depends on System Processes, a [delay] should be provided as the interval between
     * [Process.isAlive] check before trying to retrieve [Process.onExit]. Bigger values yields less resource
     * intensive operation, smaller values yields less input lag and better feed back but in cost of intensive
     * scheduling.
     *
     * TODO: Support configurable Pijul path.
     *
     * Executes a pijul command and waits for the output status
     */
    @RequiresBackgroundThread
    private fun createExecPijulOperation(
        project: Project,
        dir: Path,
        args: List<String>,
        log: Boolean = true
    ): PijulExecution {
        val process = runBlocking {
            withContext(pijulProcessContext) {
                val process = ProcessBuilder()
                    .command(listOf(findPijul()) + args)
                    .directory(dir.toFile())
                    .start()
                process
            }
        }
        val input = String(process.inputStream.readAllBytes(), Charsets.UTF_8)
        val error = String(process.errorStream.readAllBytes(), Charsets.UTF_8)

        if (log) {
            input.split("\n").forEach {
                draconConsoleWriter(project).logCommand("pijul", args, it)
            }
        }

        if (log) {
            error.split("\n").forEach {
                draconConsoleWriter(project).logCommandError("pijul", args, it)
            }
        }

        val exit = process.waitFor()
        if (exit == 0) {
            draconConsoleWriter(project).logCommand("pijul", args, "<Exit status> $exit")
        } else {
            draconConsoleWriter(project).logCommandError("pijul", args, "<Exit status> $exit")
        }

        return PijulExecution(
            input,
            error,
            exit
        )
    }

    /**
     * Creates a [PijulExecution] operation that could be executed at any time. This operation uses Kotlin Coroutines
     * and can be executed immediately through [doExecution] or through [doExecutionWithMapper].
     *
     * This implementation does not requires a delay value to be provided, like [createExecPijulOperation] does, instead
     * it uses the kotlin conversion from `CompletionStage` to `Coroutines` and awaits the process through [Process.onExit].
     *
     * [doExecution] and [doExecutionWithMapper] does execution by scheduling task to [Dispatchers.IO], instead of Main Thread,
     * offloading the Process execution handling to a different scheduler. However, mapping operation of [doExecutionWithMapper]
     * is not offloaded from the caller context.
     *
     */
    @RequiresBackgroundThread
    private fun createPainlessExecPijulOperation(
        project: Project,
        dir: Path,
        args: List<String>,
        logOutput: Boolean = true,
    ): PijulExecution {
        val process =  runBlocking {
            withContext(pijulProcessContext) {
                val process = ProcessBuilder()
                    .command(listOf(findPijul()) + args)
                    .directory(dir.toFile())
                    .start()

                process
            }
        }
        val input = String(process.inputStream.readAllBytes(), Charsets.UTF_8)
        val error = String(process.errorStream.readAllBytes(), Charsets.UTF_8)

        if (logOutput) {
            if (input.trim().isNotEmpty()) {
                input.split("\n").forEach {
                    draconConsoleWriter(project).logCommand("pijul", args, it)
                }
            }
        }

        if (error.trim().isNotEmpty()) {
            error.split("\n").forEach {
                draconConsoleWriter(project).logCommandError("pijul", args, it)
            }
        }

        val exit = process.waitFor()
        if (exit == 0) {
            draconConsoleWriter(project).logCommand("pijul", args, "<Exit status> $exit")
        } else {
            draconConsoleWriter(project).logCommandError("pijul", args, "<Exit status> $exit")
        }

        return PijulExecution(
            input,
            error,
            exit
        )

    }

    /**
     * Creates a [PijulExecution] operation that could be executed at any time. This operation uses Kotlin Coroutines
     * and can be executed immediately through [doExecution] or through [doExecutionWithMapper].
     *
     * This implementation does not requires a delay value to be provided, like [createExecPijulOperation] does, instead
     * it uses the kotlin conversion from `CompletionStage` to `Coroutines` and awaits the process through [Process.onExit].
     *
     * [doExecution] and [doExecutionWithMapper] does execution by scheduling task to [Dispatchers.IO], instead of Main Thread,
     * offloading the Process execution handling to a different scheduler. However, mapping operation of [doExecutionWithMapper]
     * is not offloaded from the caller context.
     *
     */
    @RequiresBackgroundThread
    private fun <K : Any> createPainlessExecPijulOperationWithCache(
        project: Project,
        dir: Path,
        args: List<String>,
        key: K
    ): PijulExecution {
        return runBlocking {
            withContext(pijulProcessContext) {
                cache.cache(key) {
                    val process = ProcessBuilder()
                        .command(listOf(findPijul()) + args)
                        .directory(dir.toFile())
                        .start()

                    val input = String(process.inputStream.readAllBytes(), Charsets.UTF_8)
                    val error = String(process.errorStream.readAllBytes(), Charsets.UTF_8)

                    input.split("\n").forEach {
                        draconConsoleWriter(project).logCommand("pijul", args, it)
                    }

                    error.split("\n").forEach {
                        draconConsoleWriter(project).logCommandError("pijul", args, it)
                    }

                    val exit = process.waitFor()
                    if (exit == 0) {
                        draconConsoleWriter(project).logCommand("pijul", args, "<Exit status> $exit")
                    } else {
                        draconConsoleWriter(project).logCommandError("pijul", args, "<Exit status> $exit")
                    }

                    PijulExecution(
                        input,
                        error,
                        exit
                    )
                }
            }
        }
    }

    /**
     * Creates a [PijulExecution] operation that could be executed at any time. This operation uses Kotlin Coroutines
     * and can be executed immediately through [doExecution] or through [doExecutionWithMapper].
     *
     * This implementation does not requires a delay value to be provided, like [createExecPijulOperation] does, instead
     * it uses the kotlin conversion from `CompletionStage` to `Coroutines` and awaits the process through [Process.onExit].
     *
     * [doExecution] and [doExecutionWithMapper] does execution by scheduling task to [Dispatchers.IO], instead of Main Thread,
     * offloading the Process execution handling to a different scheduler. However, mapping operation of [doExecutionWithMapper]
     * is not offloaded from the caller context.
     *
     */
    @RequiresBackgroundThread
    private fun createPainlessExecPijulWithCopieOperation(
        project: Project,
        dir: Path,
        copiePath: Path,
        copieMode: CopieMode,
        args: List<String>
    ): PijulExecution {
        val process = runBlocking {
            withContext(pijulProcessContext) {
                val process = ProcessBuilder()
                    .apply {
                        when (copieMode) {
                            CopieMode.FROM -> environment()["COPIE_FROM"] = copiePath.toAbsolutePath().toString()
                            CopieMode.TO -> environment()["COPIE_TO"] = copiePath.toAbsolutePath().toString()
                        }

                        environment()["VISUAL"] = "copie"
                        environment()["EDITOR"] = "copie"
                    }
                    .command(listOf(findPijul()) + args)
                    .directory(dir.toFile())
                    .start()
                process
            }
        }

        val input = String(process.inputStream.readAllBytes(), Charsets.UTF_8)
        val error = String(process.errorStream.readAllBytes(), Charsets.UTF_8)

        input.split("\n").forEach {
            draconConsoleWriter(project).logCommand("pijul", args, it)
        }

        error.split("\n").forEach {
            draconConsoleWriter(project).logCommandError("pijul", args, it)
        }

        val exit = process.waitFor()
        if (exit == 0) {
            draconConsoleWriter(project).logCommand("pijul", args, "<Exit status> $exit")
        } else {
            draconConsoleWriter(project).logCommandError("pijul", args, "<Exit status> $exit")
        }

        return PijulExecution(
            input,
            error,
            exit
        )
    }


    /**
     * Creates a [PijulExecution] operation that could be executed at any time. This operation uses Kotlin Coroutines
     * and can be executed immediately through [doExecution] or through [doExecutionWithMapper].
     *
     * This implementation does not requires a delay value to be provided, like [createExecPijulOperation] does, instead
     * it uses the kotlin conversion from `CompletionStage` to `Coroutines` and awaits the process through [Process.onExit].
     *
     * [doExecution] and [doExecutionWithMapper] does execution by scheduling task to [Dispatchers.IO], instead of Main Thread,
     * offloading the Process execution handling to a different scheduler. However, mapping operation of [doExecutionWithMapper]
     * is not offloaded from the caller context.
     *
     */
    @RequiresBackgroundThread
    private fun createPainlessExecPijulWithEditorServer(
        project: Project,
        dir: Path,
        args: List<String>,
        editorServerConsumer: (EditorServer) -> Unit
    ): PijulExecution {
        val freePort = freePort()

        val process = runBlocking {
            withContext(pijulProcessContext) {
                val process = ProcessBuilder()
                    .apply {
                        environment()["EDITOR_SERVER_PORT"] = freePort.toString()
                        environment()["VISUAL"] = editorServerPath()
                        environment()["EDITOR"] = editorServerPath()
                    }
                    .command(listOf(findPijul()) + args)
                    .directory(dir.toFile())
                    .start()
                process
            }
        }

        editorServerConsumer(EditorServer(freePort) {
            !process.isAlive
        })

        val input = String(process.inputStream.readAllBytes(), Charsets.UTF_8)
        val error = String(process.errorStream.readAllBytes(), Charsets.UTF_8)

        input.split("\n").forEach {
            draconConsoleWriter(project).logCommand("pijul", args, it)
        }

        error.split("\n").forEach {
            draconConsoleWriter(project).logCommandError("pijul", args, it)
        }

        val exit = process.waitFor()
        if (exit == 0) {
            draconConsoleWriter(project).logCommand("pijul", args, "<Exit status> $exit")
        } else {
            draconConsoleWriter(project).logCommandError("pijul", args, "<Exit status> $exit")
        }

        return PijulExecution(
            input,
            error,
            exit
        )
    }

    /**
     * Creates a [PijulExecution] operation that could be executed at any time. This operation uses Kotlin Coroutines
     * and can be executed immediately through [doExecution] or through [doExecutionWithMapper].
     *
     * This implementation does not requires a delay value to be provided, like [createExecPijulOperation] does, instead
     * it uses the kotlin conversion from `CompletionStage` to `Coroutines` and awaits the process through [Process.onExit].
     *
     * [doExecution] and [doExecutionWithMapper] does execution by scheduling task to [Dispatchers.IO], instead of Main Thread,
     * offloading the Process execution handling to a different scheduler. However, mapping operation of [doExecutionWithMapper]
     * is not offloaded from the caller context.
     *
     */
    @RequiresBackgroundThread
    private fun createPainlessExecPijulWithEditorServerInTerminal(
        project: Project,
        dir: Path,
        args: List<String>,
        editorServerConsumer: (EditorServer) -> Unit
    ): PijulExecution {
        val freePort = freePort()

        val process = runBlocking {
            withContext(pijulProcessContext) {
                val cmd = listOf(findPijul()) + args
                val terminalCmd = terminalCommand("command.execute.text", cmd.joinToString(" "))

                val process = ProcessBuilder()
                    .apply {
                        environment()["EDITOR_SERVER_PORT"] = freePort.toString()
                        environment()["VISUAL"] = editorServerPath()
                        environment()["EDITOR"] = editorServerPath()
                    }
                    .command(terminalCmd)
                    .directory(dir.toFile())
                    .start()

                process
            }
        }

        editorServerConsumer(EditorServer(freePort) {
            !process.isAlive
        })

        val input = String(process.inputStream.readAllBytes(), Charsets.UTF_8)
        val error = String(process.errorStream.readAllBytes(), Charsets.UTF_8)

        input.split("\n").forEach {
            draconConsoleWriter(project).logCommand("pijul", args, it)
        }

        error.split("\n").forEach {
            draconConsoleWriter(project).logCommandError("pijul", args, it)
        }

        val exit = process.waitFor()
        if (exit == 0) {
            draconConsoleWriter(project).logCommand("pijul", args, "<Exit status> $exit")
        } else {
            draconConsoleWriter(project).logCommandError("pijul", args, "<Exit status> $exit")
        }

        return PijulExecution(
            input,
            error,
            exit
        )
    }

    fun createCopieTempFile(hash: String): Path {
        val tempDir = FileUtilRt.createTempDirectory("dracon_records-", hash).toPath()
        return tempDir.resolve("record")
    }

    fun deleteCopieTempDir(hash: String) {
        val tempDir = FileUtilRt.createTempDirectory("dracon_records-", hash).toPath()
        FileUtilRt.delete(tempDir.toFile())
    }

    enum class CopieMode {
        FROM,
        TO
    }
}

/**
 * Returns whether [resolvedPath] is a directory inside [this] [Path].
 *
 * @param root The root path for [this] [Path] and [resolvedPath].
 */
fun Path.isInside(root: Path, resolvedPath: String) =
    if (this == root) {
        true
    } else if (Files.isDirectory(this) && resolvedPath.startsWith(this.toString())) {
        true
    } else if (!Files.isDirectory(this)) {
        this.toString().equals(resolvedPath, ignoreCase = true)
    } else {
        false
    }


/**
 * Returns whether [this] path is equal the [path].
 */
fun String.isEqual(path: Path) =
    path.toString() == this

/**
 * Returns whether [this] path is equal the [path].
 */
fun String.isPathEqual(path: String) =
    this.removeTrailingSlash().equals(path.removeTrailingSlash(), ignoreCase = true)

fun String.removeTrailingSlash() =
    if (this.length > 1 && this.endsWith("/")) this.substring(0, this.length - 1)
    else this

/**
 * Returns whether [this] path is inside the [path].
 */
fun String.isInside(path: Path) =
    path.startsWith(this)