Fork channel

Create a new channel as a copy of main.

Rename channel

Rename main to:

Delete channel

Delete main? This cannot be undone.

PijulLogProvider.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.log

import com.github.jonathanxd.dracon.PijulVcs
import com.github.jonathanxd.dracon.changes.PijulCommittedChangeList
import com.github.jonathanxd.dracon.pijul.Pijul
import com.github.jonathanxd.dracon.pijul.pijul
import com.github.jonathanxd.dracon.repository.PijulRepository
import com.github.jonathanxd.dracon.repository.PijulRepositoryChangeListener
import com.github.jonathanxd.dracon.repository.PijulVcsLogRefManager
import com.github.jonathanxd.dracon.util.convertToNio
import com.github.jonathanxd.dracon.util.pijul
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsKey
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Consumer
import com.intellij.util.messages.MessageBusConnection
import com.intellij.vcs.log.*
import com.intellij.vcs.log.impl.HashImpl
import com.intellij.vcs.log.impl.LogDataImpl
import com.intellij.vcs.log.impl.VcsUserImpl
import org.apache.commons.codec.digest.DigestUtils
import java.time.ZoneId

class PijulLogProvider(val project: Project) : VcsLogProvider {
    val manager = PijulVcsLogRefManager(project)

    override fun readFirstBlock(
        root: VirtualFile,
        requirements: VcsLogProvider.Requirements
    ): VcsLogProvider.DetailedLogData {
        return createMetadata(this.project, root) {
            this.project.pijul().log(this.project, root.convertToNio(), it).result?.entries.orEmpty()
        }
    }

    override fun readAllHashes(root: VirtualFile, commitConsumer: Consumer<in TimedVcsCommit>): VcsLogProvider.LogData {
        return createMetadata(this.project, root, {
            this.project.pijul().log(this.project, root.convertToNio(), it).result?.entries.orEmpty()
        }, { commitConsumer.consume(it) })
    }

    override fun readMetadata(
        root: VirtualFile,
        hashes: MutableList<String>,
        consumer: Consumer<in VcsCommitMetadata>
    ) {
        createMetadata(this.project, root, {
            this.project.pijul().log(this.project, root.convertToNio(), it).result?.entries.orEmpty().filter {
                hashes.contains(DigestUtils.sha1Hex(it.changeHash))
            }
        }, {
            consumer.consume(it)
        })
    }

    override fun readFullDetails(
        root: VirtualFile,
        hashes: MutableList<String>,
        commitConsumer: Consumer<in VcsFullCommitDetails>
    ) {
        createMetadataForEntries(this.project, root, {
            this.project.pijul().log(this.project, root.convertToNio(), it).result?.entries.orEmpty().filter {
                hashes.contains(DigestUtils.sha1Hex(it.changeHash))
            }
        }, { _, it ->
            commitConsumer.consume(PijulRecordDetails(this.project, root, it))
        })
    }

    override fun getSupportedVcs(): VcsKey {
        return PijulVcs.KEY
    }

    override fun getReferenceManager(): VcsLogRefManager =
        this.manager

    override fun subscribeToRootRefreshEvents(
        roots: MutableCollection<out VirtualFile>,
        refresher: VcsLogRefresher
    ): Disposable {
        val connection: MessageBusConnection = this.project.messageBus.connect()
        connection.subscribe(PijulRepository.PIJUL_REPO_CHANGE, PijulRepositoryChangeListener { repository ->
            val root: VirtualFile = repository.root
            if (roots.contains(root)) {
                refresher.refresh(root)
            }
        })
        return connection
    }

    override fun getCommitsMatchingFilter(
        root: VirtualFile,
        filterCollection: VcsLogFilterCollection,
        maxCount: Int
    ): MutableList<TimedVcsCommit> {
        val rootPath = root.convertToNio()
        val channelFilters = mutableListOf<(String) -> Boolean>()
        val filters = mutableListOf<(PijulLogEntry) -> Boolean>()
        val fullDetailsFilters = mutableListOf<(VcsFullCommitDetails) -> Boolean>()
        val metadataFilters = mutableListOf<(VcsCommitMetadata) -> Boolean>()

        val date = filterCollection.get(VcsLogFilterCollection.DATE_FILTER)

        date?.after?.let { after ->
            filters.add {
                it.date.isAfter(after.toInstant().atZone(ZoneId.of("UTC")))
            }
        }

        date?.before?.let { before ->
            filters.add {
                it.date.isBefore(before.toInstant().atZone(ZoneId.of("UTC")))
            }
        }

        filterCollection.get(VcsLogFilterCollection.BRANCH_FILTER)?.let { filter ->
            channelFilters.add {
                filter.matches(it)
            }
        }

        filterCollection.get(VcsLogFilterCollection.REVISION_FILTER)?.let { filter ->
            filters.add {
                filter.heads.any { head ->
                    it.asSha1Hash == head.hash.asString()
                }
            }
        }

        filterCollection.get(VcsLogFilterCollection.USER_FILTER)?.let { filter ->
            metadataFilters.add {
                filter.matches(it)
            }
        }

        filterCollection.get(VcsLogFilterCollection.HASH_FILTER)?.let { filter ->
            filters.add {
                filter.hashes.any { hash ->
                    it.changeHash == hash || it.asSha1Hash == hash
                }
            }
        }

        filterCollection.get(VcsLogFilterCollection.TEXT_FILTER)?.let { filter ->
            filters.add {
                filter.matches(it.message)
            }
        }

        filterCollection.get(VcsLogFilterCollection.STRUCTURE_FILTER)?.let { filter ->
            filters.add {
                filter.files.any { filterRoot ->
                    val filterRootPath = filterRoot.convertToNio()

                    it.hunks.any { hunk ->
                        (hunk is HunkWithPath) && hunk.resolvePath(rootPath).startsWith(filterRootPath)
                    }
                }
            }
        }

        filterCollection.get(VcsLogFilterCollection.ROOT_FILTER)?.let { filter ->
            filters.add {
                filter.roots.any { filterRoot ->
                    val filterRootPath = filterRoot.convertToNio()

                    it.hunks.any { hunk ->
                        (hunk is HunkWithPath) && hunk.resolvePath(rootPath).startsWith(filterRootPath)
                    }
                }
            }
        }


        val records = mutableListOf<TimedVcsCommit>()
        createMetadataForEntries(this.project, root, {
            if (channelFilters.all { filter -> filter(it) }) {
                this.project.pijul().log(this.project, root.convertToNio(), it).result?.entries.orEmpty()
                    .filter { filters.all { filter -> filter(it) } }
            } else {
                emptyList()
            }
        }, { _, it ->
            if (fullDetailsFilters.all { filter -> filter(it) }) {
                val meta = createMetadata(project, root, it)
                if (metadataFilters.all { filter -> filter(meta) }) {
                    records += meta
                }
            }
        })

        return records
    }

    override fun getCurrentUser(root: VirtualFile): VcsUser? {
        return null
    }

    override fun getContainingBranches(root: VirtualFile, commitHash: Hash): MutableCollection<String> {
        val channels = mutableListOf<String>()
        createMetadataForEntries(this.project, root, {
            this.project.pijul().log(this.project, root.convertToNio(), it).result?.entries.orEmpty().filter {
                DigestUtils.sha1Hex(it.changeHash) == commitHash.asString()
            }
        }, { c, it ->
            channels += c
        })

        return channels
    }

    override fun <T : Any?> getPropertyValue(property: VcsLogProperties.VcsLogProperty<T>?): T? {
        if (property == VcsLogProperties.HAS_COMMITTER) {
            return true as T
        }

        return null
    }

    override fun getVcsRoot(project: Project, detectedRoot: VirtualFile, filePath: FilePath): VirtualFile? {
        return Pijul.findPijulDirectory(detectedRoot)
    }

    override fun getCurrentBranch(root: VirtualFile): String? {
        return this.project.pijul().channel(this.project, root).result?.channels?.firstOrNull { it.current }?.name
    }

    companion object {
        fun createMetadata(
            project: Project,
            root: VirtualFile,
            fetcher: (channel: String) -> List<PijulLogEntry>
        ): VcsLogProvider.DetailedLogData {
            val commits = mutableListOf<VcsCommitMetadata>()
            val log = createMetadata(project, root, fetcher) {
                commits.add(it)
            }

            return LogDataImpl(log.refs, commits)
        }

        fun createMetadataForEntries(
            project: Project,
            root: VirtualFile,
            fetcher: (channel: String) -> List<PijulLogEntry>,
            consumer: (channel: String, PijulLogEntryCommitDetails) -> Unit
        ): VcsLogProvider.LogData {
            val latest = project.pijul().latestRevisionNumber(project, root.convertToNio()).result?.hash
            val allChannels = project.pijul().channel(project, root.convertToNio()).result?.channels.orEmpty()
            val currentChannel = allChannels.firstOrNull {
                it.current
            }

            val refs = mutableSetOf<VcsRef>()
            val authors = mutableSetOf<VcsUser>()

            val rootPath = root.convertToNio()
            val factory = getObjectsFactoryWithDisposeCheck(project) ?: return LogDataImpl.empty()
            allChannels.forEach { channel ->
                val allTags = if (channel.current) {
                    // Only current tag of current channel is available through `pijul tag` ATM
                    project.pijul().tags(project, root.convertToNio()).result.orEmpty()
                } else {
                    emptyList()
                }

                allTags.forEach {
                    val hash = HashImpl.build(DigestUtils.sha1Hex(it.hash))//PijulHash(it.hash)
                    val ref = factory.createRef(hash, it.simpleMessage, PijulVcsLogRefManager.TAG, root)
                    if (!refs.contains(ref)) refs.add(ref)
                }

                var first = true
                fetcher(channel.name).forEach {
                    val hash = HashImpl.build(DigestUtils.sha1Hex(it.changeHash))//PijulHash(it.changeHash)
                    authors.addAll(it.authors.filter { it.name != null && it.email != null }
                        .map { VcsUserImpl(it.name!!, it.email!!) })

                    if (channel.current) {
                        // Only current tag of current channel is available through `pijul tag` ATM
                        val tag = allTags.singleOrNull()
                        if (tag != null) {
                            if (first) {
                                val ref = factory.createRef(hash, tag.simpleMessage, PijulVcsLogRefManager.TAG, root)
                                if (!refs.contains(ref)) refs.add(ref)
                            }
                        }
                    }

                    first = false

                    if (it.changeHash == latest) {
                        val ref = factory.createRef(hash, "CURRENT", PijulVcsLogRefManager.CURRENT, root)
                        if (!refs.contains(ref)) refs.add(ref)
                    }

                    val ref = factory.createRef(hash, channel.name, PijulVcsLogRefManager.CHANNEL, root)
                    if (!refs.contains(ref)) refs.add(ref)

                    val details = PijulLogEntryCommitDetails(
                        rootPath,
                        project,
                        it,
                    ) {
                        val changes = mutableListOf<PijulCommittedChangeList>()
                        pijul(project).changes(project, rootPath, it, 1, {
                            true
                        }) {
                            changes += it
                        }
                        changes.single().changes.toList()
                    }

                    consumer(channel.name, details)
                }
            }

            return LogDataImpl(refs, authors)
        }

        fun createMetadata(
            project: Project,
            root: VirtualFile,
            fetcher: (channel: String) -> List<PijulLogEntry>,
            consumer: (VcsCommitMetadata) -> Unit
        ): VcsLogProvider.LogData {
            val factory = getObjectsFactoryWithDisposeCheck(project) ?: return LogDataImpl.empty()

            return createMetadataForEntries(project, root, fetcher) { _, it ->
                // Use empty parents since Pijul hierarchy is not linear
                // this leads to a problem shown in the [pijul-log-tree.png] file.
                val parents = emptyList<Hash>()//it.parents
                consumer(
                    factory.createCommitMetadata(
                        it.id,
                        parents,
                        it.commitTime,
                        root,
                        it.subject,
                        it.author.name,
                        it.author.email,
                        it.fullMessage,
                        it.committer.name,
                        it.committer.email,
                        it.authorTime
                    )
                )
            }
        }

        fun createMetadata(
            project: Project,
            root: VirtualFile,
            it: PijulLogEntryCommitDetails
        ): VcsCommitMetadata {
            val factory = getObjectsFactoryWithDisposeCheck(project)!!

            return factory.createCommitMetadata(
                it.id,
                emptyList(),
                it.commitTime,
                root,
                it.subject,
                it.author.name,
                it.author.email,
                it.fullMessage,
                it.committer.name,
                it.committer.email,
                it.authorTime
            )

        }

        fun getObjectsFactoryWithDisposeCheck(project: Project): VcsLogObjectsFactory? {
            return ReadAction.compute<VcsLogObjectsFactory?, RuntimeException> {
                if (!project.isDisposed) {
                    return@compute project.getService(VcsLogObjectsFactory::class.java)
                }
                null
            }
        }
    }
}