Fork channel

Create a new channel as a copy of main.

Rename channel

Rename main to:

Delete channel

Delete main? This cannot be undone.

PijulCheckingEnvironment.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.checkin

import com.github.jonathanxd.dracon.cache.FileStatusCache
import com.github.jonathanxd.dracon.config.PijulSettings
import com.github.jonathanxd.dracon.i18n.DraconBundle
import com.github.jonathanxd.dracon.pijul.SuccessStatusCode
import com.github.jonathanxd.dracon.pijul.pijul
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.util.Key
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.checkin.CheckinChangeListSpecificComponent
import com.intellij.openapi.vcs.checkin.CheckinEnvironment
import com.intellij.openapi.vcs.ui.RefreshableOnComponent
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.WindowManager
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.GridBag
import com.intellij.util.ui.JBUI
import com.intellij.vcs.commit.*
import com.intellij.vcs.log.VcsUser
import com.intellij.vcs.log.VcsUserEditor
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.awt.event.*
import java.util.*
import javax.swing.JComponent
import javax.swing.JPanel
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.relativeTo
import com.intellij.ui.EditorTextField

import com.intellij.psi.PsiDocumentManager

import com.intellij.psi.PsiElement

import com.intellij.psi.PsiFile
import com.intellij.testFramework.LightVirtualFile
import com.intellij.vcsUtil.VcsUtil
import java.nio.file.Paths


val COMMIT_AUTHOR_KEY = Key.create<VcsUser>("Pijul.Commit.Author")
val COMMIT_AUTHOR_DATE_KEY = Key.create<Date>("Pijul.Commit.AuthorDate")

internal var CommitContext.commitAuthor: VcsUser? by commitProperty(COMMIT_AUTHOR_KEY, null)
internal var CommitContext.commitAuthorDate: Date? by commitProperty(COMMIT_AUTHOR_DATE_KEY, null)

@Service(Service.Level.PROJECT)
class PijulCheckingEnvironment(val project: Project) : CheckinEnvironment {

    override fun createCommitOptions(
        commitPanel: CheckinProjectPanel,
        commitContext: CommitContext
    ): RefreshableOnComponent? {
        return PijulCheckinOptions(commitPanel, commitContext)
    }

    override fun getHelpId(): String? = null

    override fun getCheckinOperationName(): String =
        DraconBundle.Record.name

    override fun scheduleMissingFileForDeletion(files: MutableList<out FilePath>): MutableList<VcsException> {
        return mutableListOf()
    }

    override fun scheduleUnversionedFilesForAddition(files: MutableList<out VirtualFile>): MutableList<VcsException> {
        return mutableListOf()
    }

    override fun isRefreshAfterCommitNeeded(): Boolean = true



    @OptIn(ExperimentalPathApi::class)
    override fun commit(
        changes: MutableList<out Change>,
        commitMessage: String,
        commitContext: CommitContext,
        feedback: MutableSet<in String>
    ): MutableList<VcsException>? {
        val vcsManager = ProjectLevelVcsManager.getInstance(this.project)
        val root = vcsManager.allVcsRoots.first().path.toNioPath()
        val paths = changes.map {
            val root = vcsManager.getVcsRootFor(it.afterRevision!!.file)!!.toNioPath()
            val relative = it.afterRevision!!.file.ioFile.toPath().relativeTo(root)
            relative
        }

        val author = commitContext.commitAuthor

        val record = pijul(project).record(project, root, paths, author, commitMessage)

        return if (record.statusCode !is SuccessStatusCode) {
            mutableListOf(
                VcsException("Operation ${record.operation}, failed with statusCode: ${record.statusCode}")
            )
        } else {
            changes.mapNotNull { it.virtualFile }.forEach {
                val path = Paths.get(VcsUtil.getFilePath(it).path)
                this.project.service<FileStatusCache>().unload(path)
            }

            super.commit(changes, commitMessage, commitContext, feedback)
        }
    }

    class PijulCheckinOptions(val commitPanel: CheckinProjectPanel, val commitContext: CommitContext) : RefreshableOnComponent, Disposable {
        val optionsUi = PijulOptionsUi(commitPanel, commitContext)

        @Deprecated("Deprecated in Java")
        override fun refresh() {
            optionsUi.refresh()
        }

        override fun saveState() {
            optionsUi.saveState()
        }

        override fun restoreState() {
            optionsUi.restoreState()
        }

        override fun getComponent(): JComponent {
            return optionsUi.component
        }

        override fun dispose() {
            optionsUi.dispose()
        }

    }


    class PijulOptionsUi(private val commitPanel: CheckinProjectPanel,
                         private val commitContext: CommitContext) : RefreshableOnComponent,
        CheckinChangeListSpecificComponent,
        CommitAuthorListener,
        Disposable {

        private val CheckinProjectPanel.commitAuthorTracker: CommitAuthorTracker? get() = commitWorkflowHandler as? CommitAuthorTracker

        private val project get() = commitPanel.project
        private val settings = PijulSettings.instance

        private var authorDate: Date? = null

        private val panel = JPanel(GridBagLayout())
        private val authorField = VcsUserEditor(project, getKnownCommitAuthors())

        init {
            authorField.addFocusListener(object : FocusAdapter() {
                override fun focusLost(e: FocusEvent) {
                    updateCurrentCommitAuthor()
                }
            })

            buildLayout()

        }

        private fun buildLayout() = panel.apply {
            val gb = GridBag().setDefaultAnchor(GridBagConstraints.WEST).setDefaultInsets(JBUI.insets(2))

            val authorLabel = JBLabel(DraconBundle.message("record.author")).apply { labelFor = authorField }
            add(authorLabel, gb.nextLine().next())
            add(authorField, gb.next().fillCellHorizontally().weightx(1.0))
        }


        override fun dispose() = Unit

        override fun getComponent(): JComponent = panel

        override fun restoreState() {
            if (commitPanel.isNonModalCommit) {
                commitPanel.commitAuthorTracker?.addCommitAuthorListener(this, this)
            }
            refresh()
        }

        @Deprecated("Deprecated in Java")
        override fun refresh() {
            refresh(null)
            commitAuthorChanged()
        }

        override fun saveState() {
            val author = getAuthor()

            commitContext.apply {
                commitAuthor = author
                commitAuthorDate = authorDate
            }

            settings.apply {
                author?.let { saveAuthor(it) }
            }
        }

        override fun onChangeListSelected(list: LocalChangeList) {
            refresh(list)

            panel.revalidate()
            panel.repaint()
        }

        private fun refresh(changeList: LocalChangeList?) {
            setAuthor(changeList?.author)
            authorDate = changeList?.authorDate
        }

        fun getAuthor(): VcsUser? = authorField.user

        private fun setAuthor(author: VcsUser?) {
            val isAuthorNull = author == null
            authorField.user = author.takeUnless { isAuthorNull }
        }

        private fun updateCurrentCommitAuthor() {
            commitPanel.commitAuthorTracker?.commitAuthor = getAuthor()
        }

        override fun commitAuthorChanged() {
            val newAuthor = commitPanel.commitAuthorTracker?.commitAuthor
            if (getAuthor() != newAuthor) setAuthor(newAuthor)
        }

        override fun commitAuthorDateChanged() {
            // TODO:
        }

        private fun getKnownCommitAuthors(): List<String> =
            (VcsUserEditor.getAllUsers(project) + settings.getAuthor()?.let { listOf(it) }.orEmpty()).distinct().sorted()
    }
}