Fork channel

Create a new channel as a copy of main.

Rename channel

Rename main to:

Delete channel

Delete main? This cannot be undone.

PijulLog.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.revision.PijulRevisionNumber
import com.google.gson.*
import com.intellij.openapi.vcs.FileStatus
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.lang.StringEscapeUtils
import java.io.Serializable
import java.nio.charset.Charset
import java.nio.file.Path
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatterBuilder
import java.time.format.ResolverStyle
import java.time.temporal.ChronoField


data class Author(val name: String?, val fullName: String?, val email: String?): Serializable {
    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

data class PijulLog(val entries: List<PijulLogEntry>)

data class PijulLogEntry(
    val changeHash: String,
    val message: String,
    val date: ZonedDateTime,
    val authors: List<Author>,
    val dependencies: List<Dependency>,
    val hunks: List<Hunk>
): Serializable {
    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

val PijulLogEntry.asSha1Hash: String get() = DigestUtils.sha1Hex(this.changeHash)

val PijulLogEntry.revision: PijulRevisionNumber get() = PijulRevisionNumber(this.changeHash, this.date)

// Dependency

data class Dependency(
    val id: IntOrAsterisk,
    val type: DependencyType,
    val hash: String
): Serializable {
    companion object {
        private const val serialVersionUID: Long = 1L
    }

}

sealed class IntOrAsterisk: Serializable

/**
 * Only appears in dependencies of [extra-known type][DependencyType.EXTRA_KNOWN_DEPENDENCY].
 */
object Asterisk : IntOrAsterisk(), Serializable {
    private const val serialVersionUID: Long = 1L

    override fun toString(): String = "*"
}

/**
 * Appears in dependencies of [regular type][DependencyType.REGULAR_DEPENDENCY] and [change type][DependencyType.CHANGE_DEPENDENCY].
 */
data class IndexInt(val index: Int) : IntOrAsterisk(), Serializable {
    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

enum class DependencyType: Serializable {
    /**
     * Regular dependency.
     */
    REGULAR_DEPENDENCY,

    /**
     * Change dependency.
     */
    CHANGE_DEPENDENCY,

    /**
     * Extra known "context" changes.
     */
    EXTRA_KNOWN_DEPENDENCY,

    /**
     * Unknown dependency type.
     */
    UNKNOWN;

    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

// Hunk
sealed class Hunk: Serializable {
    abstract val hunkNumber: Int
    abstract val type: HunkType
    abstract val context: Context?
    abstract val mode: Mode?
    abstract val meta: Meta?
    abstract val flags: List<Flag>
}

interface HunkWithPath {
    val resolvedPath: String

    fun resolvePath(root: Path): Path =
        root.resolve(this.resolvedPath)
}

interface HunkWithEncoding {
	val encoding: Encoding
}

data class FileAddHunk(
    override val hunkNumber: Int,
    override val type: HunkType = HunkType.FILE_ADDITION,
    val path: Filename,
    val rootPath: FileDir,
    val lines: List<LineChange>,
    override val encoding: Encoding,
    override val mode: Mode?,
    override val meta: Meta?,
    override val flags: List<Flag> = emptyList(),
    override val context: Context?
): Hunk(), HunkWithPath, HunkWithEncoding, Serializable {
    override val resolvedPath: String
        get() =
            when {
                this.rootPath.dir == "/" -> this.path.name
                this.rootPath.dir.endsWith("/") -> (this.rootPath + this.path).fullPath
                this.rootPath.dir.isEmpty() -> this.path.name
                else -> (this.rootPath + this.path).fullPath
            }

    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

data class FileDelHunk(
    override val hunkNumber: Int,
    override val type: HunkType = HunkType.FILE_DELETION,
    val path: FilePath,
    val inode: Double?,
    val lines: List<LineChange>,
    override val encoding: Encoding,
    override val mode: Mode?,
    override val meta: Meta?,
    override val flags: List<Flag>,
    override val context: Context?
): Hunk(), HunkWithPath, HunkWithEncoding, Serializable {
    override val resolvedPath: String
        get() = this.path.fullPath

    companion object {
        private const val serialVersionUID: Long = 1L
    }
}


data class FileUnDelHunk(
    override val hunkNumber: Int,
    override val type: HunkType = HunkType.FILE_UN_DELETION,
    val path: FilePath,
    val inode: Double?,
    val lines: List<LineChange>,
    override val encoding: Encoding,
    override val mode: Mode?,
    override val meta: Meta?,
    override val flags: List<Flag>,
    override val context: Context?
): Hunk(), HunkWithPath, HunkWithEncoding, Serializable {
    override val resolvedPath: String
        get() = this.path.fullPath

    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

data class MoveHunk(
    override val hunkNumber: Int,
    override val type: HunkType = HunkType.FILE_MOVE,
    val older: FilePath,
    val new: FilePath,
    val inode: Double?,
    override val mode: Mode?,
    override val meta: Meta?,
    override val flags: List<Flag>,
    override val context: Context?
): Hunk(), HunkWithPath, Serializable {
    override val resolvedPath: String
        get() = this.new.fullPath

    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

data class EditHunk(
    override val hunkNumber: Int,
    override val type: HunkType = HunkType.FILE_EDIT,
    val path: FilePath,
    val startLine: Int,
    val inode: Double?,
    val lines: List<LineChange>,
    override val encoding: Encoding,
    override val mode: Mode?,
    override val meta: Meta?,
    override val flags: List<Flag>,
    override val context: Context?
): Hunk(), HunkWithPath, HunkWithEncoding, Serializable {
    override val resolvedPath: String
        get() = this.path.fullPath

    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

data class ReplacementHunk(
    override val hunkNumber: Int,
    override val type: HunkType = HunkType.REPLACEMENT,
    val path: FilePath,
    val startLine: Int,
    val inode: Double?,
    val lines: List<LineChange>,
    override val encoding: Encoding,
    override val mode: Mode?,
    override val meta: Meta?,
    override val flags: List<Flag>,
    override val context: Context?
): Hunk(), HunkWithPath, HunkWithEncoding, Serializable {
    override val resolvedPath: String
        get() = this.path.fullPath

    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

data class NameConflictHunk(
    override val hunkNumber: Int,
    override val type: HunkType,
    val path: FilePath,
    val inode: Double?,
    val deletedNames: List<String>,
    override val mode: Mode?,
    override val meta: Meta?,
    override val flags: List<Flag>,
    override val context: Context?
): Hunk(), HunkWithPath, Serializable {
    override val resolvedPath: String
        get() = this.path.fullPath

    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

data class OrderConflictHunk(
    override val hunkNumber: Int,
    override val type: HunkType,
    val path: FilePath,
    val index: Int?, // ??
    val inode: Double?,
    val lines: List<LineChange>,
    override val mode: Mode?,
    override val meta: Meta?,
    override val flags: List<Flag>,
    override val context: Context?
): Hunk(), HunkWithPath, Serializable {
    override val resolvedPath: String
        get() = this.path.fullPath

    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

data class ZombieResurrectHunk(
    override val hunkNumber: Int,
    override val type: HunkType = HunkType.ZOMBIE_RESURRECT,
    val path: FilePath,
    val line: Int,
    val inode: Double?,
    val lines: List<LineChange>,
    override val mode: Mode?,
    override val meta: Meta?,
    override val flags: List<Flag>,
    override val context: Context?
): Hunk(), HunkWithPath, Serializable {
    override val resolvedPath: String
        get() = this.path.fullPath

    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

/**
 * Mode is ignored as it is not needed for this plugin work.
 *
 * However, we still read metadata and store them, as they are useful to keep changelog reading consistent.
 */
data class Mode(val plain: String): Serializable {
    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

/**
 * Meta is ignored as it is not needed for this plugin work.
 *
 * However, we still read metadata and store them, as they are useful to keep changelog reading consistent.
 */
data class Meta(val plain: String): Serializable {
    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

/**
 * Flag is ignored as it is not needed for this plugin work.
 *
 * However, we still read flags and store them, as they are useful to keep changelog reading consistent.
 */
data class Flag(val plain: String): Serializable {
    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

data class Context(
    val up: List<Double>,
    val new: Range?,
    val down: List<Double>
): Serializable {
    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

data class Range(val start: Int, val end: Int): Serializable {
    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

fun List<Double>.doublesAsSource() =
    if(this.isEmpty()) "emptyList()"
    else "listOf(${this.joinToString(separator = ", ") { it.toString() }})"

fun Range.intRangeAsSource() = "Range(${this.start}, ${this.end})"

enum class HunkType: Serializable {
    FILE_ADDITION,
    FILE_DELETION,
    FILE_UN_DELETION,
    FILE_MOVE,
    FILE_EDIT,
    REPLACEMENT,
    SOLVING_NAME_CONFLICT,
    UN_SOLVING_NAME_CONFLICT,
    UNKNOWN_NAME_CONFLICT_RESOLUTION,
    SOLVING_ORDER_CONFLICT,
    UN_SOLVING_ORDER_CONFLICT,
    UNKNOWN_ORDER_CONFLICT_RESOLUTION,
    ZOMBIE_RESURRECT;

    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

data class LineChange(val type: LineChangeType, val data: String): Serializable {
    companion object {
        private const val serialVersionUID: Long = 1L
    }
}

enum class LineChangeType(val symbol: String): Serializable {
    ADD("+"),
    DEL("-");

    override fun toString(): String =
        "${this.name}(${this.symbol})"

    companion object {
        private const val serialVersionUID: Long = 1L

        fun fromSymbol(symbol: String): LineChangeType =
            when (symbol) {
                "+" -> ADD
                "-" -> DEL
                else -> throw IllegalArgumentException("Unknown change symbol: $symbol. Known symbols: +, -. For: ADD, DEL.")
            }
    }
}

val MESSAGE_PATTERN = Regex("message = '(.*)'\\n")
val MULTI_LINE_MESSAGE_PATTERN = Regex("message = '''(.*)'''", RegexOption.DOT_MATCHES_ALL)
val TIME_PATTERN = Regex("timestamp = '(.*)'\\n")
val AUTHORS_SECTION_PATTERN = Regex("\\[\\[authors\\]\\]\\n")
val AUTHOR_PATTERN = Regex("name = '(.*)'\\n?")
val DEPENDENCIES_SECTION_PATTERN = Regex("# Dependencies\\n")
val DEPENDENCY_PATTERN = Regex("\\[(\\d+|\\*)\\]([+ ])([A-Z0-9]+)\\n?")
val HUNK_SECTION_PATTERN = Regex("# Hunks\\n")
val HUNK_CONTEXT = Regex("up ((\\d+\\.\\d+ )*\\d+\\.\\d+)(, new \\d+:\\d+)?(, down ((\\d+\\.\\d+ )*\\d+\\.\\d+))?\\n?")


// Corner case: :D 9.1256 -> 4.12200:12305/9, B:BD 4.12200 -> 4.12200:12305/4
/**
 * Flags are currently ignored by Dracon, as they are not required for the plugin work correctly.
 */
val FLAG_PATTERN = Regex("(([BFD]+:[BFD]+ [^\\n]+)|(:[BFD]+ [^\\n]+))\\n?")

fun String.parseChange(hash: String): PijulLogEntry {
    val messageSingleLine = MESSAGE_PATTERN.find(this)?.groupValues?.get(1)
    val messageMultiLine = MULTI_LINE_MESSAGE_PATTERN.find(this)?.groupValues?.get(1)
    val timestamp = TIME_PATTERN.find(this)?.groupValues?.get(1)!!
    val authorsSection = AUTHORS_SECTION_PATTERN.find(this)?.range?.endInclusive
    val dependencySection = DEPENDENCIES_SECTION_PATTERN.find(this)?.range?.endInclusive
    val hunkSection = HUNK_SECTION_PATTERN.find(this)?.range?.endInclusive
    val authors = mutableListOf<Author>()
    val dependencies = mutableListOf<Dependency>()
    val hunks = mutableListOf<Hunk>()

    val message = if (messageMultiLine != null) messageMultiLine else messageSingleLine

    if (authorsSection != null) {
        var lastFound: Int? = authorsSection
        while (lastFound != null) {
            val foundAuthor = AUTHOR_PATTERN.find(this, lastFound)
            val foundAuthorGroup = foundAuthor?.groupValues?.get(1)

            if (foundAuthorGroup != null) {
                authors += Author(foundAuthorGroup, null, null)
                lastFound = if (foundAuthor.range.last.endsInNewLine(this)) {
                    null
                } else {
                    foundAuthor.range.last
                }
            } else {
                lastFound = null
            }
        }
    }

    if (dependencySection != null) {
        var lastFound: Int? = dependencySection
        while (lastFound != null) {
            val foundDependency = DEPENDENCY_PATTERN.find(this, lastFound)
            if (foundDependency != null) {
                val foundDependencyId = foundDependency.groupValues[1]
                val foundDependencySeparator = foundDependency.groupValues[2]
                val foundDependencyHash = foundDependency.groupValues[3]

                val dependencyType = when {
                    foundDependencyId == "*" && foundDependencySeparator == " " -> DependencyType.EXTRA_KNOWN_DEPENDENCY
                    foundDependencyId.toIntOrNull() != null && foundDependencySeparator == "+" -> DependencyType.CHANGE_DEPENDENCY
                    foundDependencyId.toIntOrNull() != null && foundDependencySeparator == " " -> DependencyType.REGULAR_DEPENDENCY
                    else -> DependencyType.UNKNOWN
                }

                val intOrAsterisk = foundDependencyId.toIntOrNull()?.let(::IndexInt) ?: Asterisk

                dependencies += Dependency(
                    intOrAsterisk,
                    dependencyType,
                    foundDependencyHash
                )

                lastFound = if (foundDependency.range.last.endsInNewLine(this)) {
                    null
                } else {
                    foundDependency.range.last
                }

            } else {
                lastFound = null
            }
        }
    }

    if (hunkSection != null) {
        var lastFound: Int? = hunkSection

        while (lastFound != null) {
            if (lastFound == this.length)
                break;
            
            if (this[lastFound] == '\n') {
                lastFound += 1
                continue;
            }

            if (this.substringUntil(lastFound, '\n') == "\\\n") {
                lastFound += 1
                continue
            }

            var anyFound = false

            val add = HunkAddPattern.matchEntire(this.substringUntil(lastFound, '\n'))
            if (add != null) {
                anyFound = true
                lastFound += add.matchResult.range.last
                val hunkNumber = add.changeNumber
                val fileOrPath = add.fileName.parseFilename()
                val rootPath = add.path.parseFileDir()
                val encoding = add.encoding
                val mode = add.mode?.trim()?.let(::Mode)
                val meta = add.meta?.trim()?.let(::Meta)
                val (context, stoppedLine) = this.tryReadContext(lastFound)
                lastFound = stoppedLine

                val (lines, lastKnownLine) = this.readLineChanges(lastFound)

                lastFound = lastKnownLine

                hunks += FileAddHunk(
                    hunkNumber = hunkNumber,
                    path = fileOrPath,
                    rootPath = rootPath,
                    lines = lines,
                    meta = meta,
                    context = context,
                    mode = mode,
                    encoding = encoding
                )
            }

            val remove = HunkDelPattern.matchEntire(this.substringUntil(lastFound, '\n'))

            if (remove != null) {
                anyFound = true
                lastFound += remove.matchResult.range.last
                val hunkNumber = remove.changeNumber
                val path = remove.fileName.parseFilePath()
                val inode = remove.inode
                val encoding = remove.encoding
                val (flags, flagsLastKnownLine) = this.readFlags(lastFound)
                lastFound = flagsLastKnownLine

                val (lines, linesLastKnownLine) = this.readLineChanges(lastFound)

                lastFound = linesLastKnownLine

                hunks += FileDelHunk(
                    hunkNumber = hunkNumber,
                    path = path,
                    inode = inode,
                    flags = flags,
                    lines = lines,
                    mode = null,
                    meta = null,
                    context = null,
                    encoding = encoding
                )
            }

            val undel = HunkUnDelPattern.matchEntire(this.substringUntil(lastFound, '\n'))

            if (undel != null) {
                anyFound = true
                lastFound += undel.matchResult.range.last
                val hunkNumber = undel.changeNumber
                val path = undel.fileName.parseFilePath()
                val inode = undel.inode
                val encoding = undel.encoding
                val (flags, flagsLastKnownLine) = this.readFlags(lastFound)
                lastFound = flagsLastKnownLine

                val (lines, linesLastKnownLine) = this.readLineChanges(lastFound)

                lastFound = linesLastKnownLine

                hunks += FileUnDelHunk(
                    hunkNumber = hunkNumber,
                    path = path,
                    inode = inode,
                    flags = flags,
                    lines = lines,
                    mode = null,
                    meta = null,
                    context = null,
                    encoding = encoding
                )
            }

            val move = HunkMovedPattern.matchEntire(this.substringUntil(lastFound, '\n'))

            if (move != null) {
                anyFound = true
                lastFound += move.matchResult.range.last
                val hunkNumber = move.changeNumber
                val new = move.new.parseFilePath()
                val old = move.old.parseFilePath()
                val inode = move.inode
                val meta = move.meta?.trim()?.let(::Meta)
                val (flags, flagsLastKnownLine) = this.readFlags(lastFound)
                lastFound = flagsLastKnownLine

                val (context, stoppedLine) = this.tryReadContext(lastFound)
                lastFound = stoppedLine

                hunks += MoveHunk(
                    hunkNumber = hunkNumber,
                    older = old,
                    new = new,
                    inode = inode,
                    flags = flags,
                    mode = null,
                    meta = meta,
                    context = context
                )
            }

            val edit = HunkEditPattern.matchEntire(this.substringUntil(lastFound, '\n'))

            if (edit != null) {
                anyFound = true
                lastFound += edit.matchResult.range.last
                val hunkNumber = edit.changeNumber
                val path = edit.file.parseFilePath()
                val line = edit.line
                val inode = edit.inode
                val encoding = edit.encoding
                val (flags, flagsLastKnownLine) = this.readFlags(lastFound)
                lastFound = flagsLastKnownLine

                val (context, stoppedLine) = this.tryReadContext(lastFound)
                lastFound = stoppedLine

                val (lines, linesLastKnownLine) = this.readLineChanges(lastFound)

                lastFound = linesLastKnownLine

                hunks += EditHunk(
                    hunkNumber = hunkNumber,
                    path = path,
                    startLine = line,
                    inode = inode,
                    flags = flags,
                    mode = null,
                    meta = null,
                    lines = lines,
                    context = context,
                    encoding = encoding
                )
            }

            val replacement = HunkReplacementPattern.matchEntire(this.substringUntil(lastFound, '\n'))

            if (replacement != null) {
                anyFound = true
                lastFound += replacement.matchResult.range.last
                val hunkNumber = replacement.changeNumber
                val path = replacement.fileName.parseFilePath()
                val line = replacement.line
                val inode = replacement.inode
                val encoding = replacement.encoding
                val (flags, flagsLastKnownLine) = this.readFlags(lastFound)
                lastFound = flagsLastKnownLine

                val (context, stoppedLine) = this.tryReadContext(lastFound)
                lastFound = stoppedLine

                val (lines, linesLastKnownLine) = this.readLineChanges(lastFound)

                lastFound = linesLastKnownLine

                hunks += ReplacementHunk(
                    hunkNumber = hunkNumber,
                    path = path,
                    startLine = line,
                    inode = inode,
                    flags = flags,
                    mode = null,
                    meta = null,
                    lines = lines,
                    context = context,
                    encoding = encoding
                )
            }

            val nameConflict = HunkNameConflictPattern.matchEntire(this.substringUntil(lastFound, '\n'))

            if (nameConflict != null) {
                anyFound = true
                lastFound += nameConflict.matchResult.range.last
                val hunkNumber = nameConflict.changeNumber
                val type = nameConflict.type
                val path = nameConflict.fileName.parseFilePath()
                val inode = nameConflict.inode
                val deletedNames = nameConflict.deletedNames

                val (flags, flagsLastKnownLine) = this.readFlags(lastFound)
                lastFound = flagsLastKnownLine

                val (context, stoppedLine) = this.tryReadContext(lastFound)
                lastFound = stoppedLine


                hunks += NameConflictHunk(
                    hunkNumber = hunkNumber,
                    path = path,
                    type = type,
                    inode = inode,
                    deletedNames = deletedNames,
                    flags = flags,
                    mode = null,
                    meta = null,
                    context = context
                )
            }

            val orderConflict = HunkOrderConflictPattern.matchEntire(this.substringUntil(lastFound, '\n'))

            if (orderConflict != null) {
                anyFound = true
                lastFound += orderConflict.matchResult.range.last
                val hunkNumber = orderConflict.changeNumber
                val type = orderConflict.type
                val path = orderConflict.fileName.parseFilePath()
                val pos = orderConflict.pos
                val inode = orderConflict.inode

                val (flags, flagsLastKnownLine) = this.readFlags(lastFound)
                lastFound = flagsLastKnownLine

                val (context, stoppedLine) = this.tryReadContext(lastFound)
                lastFound = stoppedLine

                val (lines, linesLastKnownLine) = this.readLineChanges(lastFound)

                lastFound = linesLastKnownLine

                hunks += OrderConflictHunk(
                    hunkNumber = hunkNumber,
                    path = path,
                    index = pos,
                    type = type,
                    inode = inode,
                    lines = lines,
                    flags = flags,
                    mode = null,
                    meta = null,
                    context = context
                )
            }

            val zombieLines = HunkZombiePattern.matchEntire(this.substringUntil(lastFound, '\n'))

            if (zombieLines != null) {
                anyFound = true
                lastFound += zombieLines.matchResult.range.last
                val hunkNumber = zombieLines.changeNumber
                val path = zombieLines.fileName.parseFilePath()
                val line = zombieLines.pos
                val inode = zombieLines.inode

                val (flags, flagsLastKnownLine) = this.readFlags(lastFound)
                lastFound = flagsLastKnownLine


                val (context, stoppedLine) = this.tryReadContext(lastFound)
                lastFound = stoppedLine

                val (lines, linesLastKnownLine) = this.readLineChanges(lastFound)

                lastFound = linesLastKnownLine

                hunks += ZombieResurrectHunk(
                    hunkNumber = hunkNumber,
                    path = path,
                    line = line,
                    inode = inode,
                    lines = lines,
                    flags = flags,
                    mode = null,
                    meta = null,
                    context = context
                )
            }

            if (!anyFound) {
                lastFound = null
            }
        }
    }

    return PijulLogEntry(hash, message!!, timestamp.parseAsLocalDateTime(), authors, dependencies, hunks)
}

fun String.substringUntil(start: Int, char: Char, includeChar: Boolean = true) =
    this.indexOf(char, start + 1).let {
        if (it == -1) {
            this.substring(start)
        } else {
            this.substring(start, if (includeChar) it + 1 else it)
        }
    }

fun String.tryReadContext(start: Int): Pair<Context?, Int> {
    val end = this.indexOf('\n', start + 1).let {
        if (it == -1) this.length
        else it
    }
    val text = this.substring(start, end).trim()
    val foundContext = HUNK_CONTEXT.find(text)
    if (foundContext != null) {
        val up = foundContext.groupValues[1].split(" ").map { it.toDouble() }
        val newText = foundContext.groupValues.getOrNull(3)
        val downText = foundContext.groupValues.getOrNull(4)

        val new = if (newText != null && newText.startsWith(", new ")) {
            val range = newText.substring(", new ".length)
            val rangeDivisor = range.indexOf(':')
            val firstPart = range.substring(0 until rangeDivisor).toInt()
            val secondPart = range.substring(rangeDivisor + 1).toInt()

            Range(firstPart, secondPart)
        } else {
            null
        }

        val down = if (downText != null && downText.startsWith(", down ")) {
            downText.substring(", down ".length).split(" ").map { it.toDouble() }
        } else {
            emptyList()
        }

        return Context(up, new, down) to end
    } else {
        return null to start
    }
}

fun String.readFlags(start: Int): Pair<List<Flag>, Int> {
    val flags = mutableListOf<Flag>()
    var lastKnownLine: Int = start
    var lastLine: Int? = start

    while (lastLine != null) {
        if (this[lastLine] == '\n') {
            lastLine += 1
            lastKnownLine = lastLine
            continue;
        }

        val foundFlag = FLAG_PATTERN.matchEntire(this.substringUntil(lastLine, '\n'))
        if (foundFlag != null) {
            lastKnownLine = lastLine + foundFlag.range.last

            val flag = foundFlag.groupValues[1]

            flags + Flag(flag)

            lastLine = if (lastKnownLine.endsInNewLine(this)) {
                null
            } else {
                lastKnownLine
            }
        } else {
            lastLine = null
        }
    }

    return flags to lastKnownLine
}

/**
 *
 * # Line changes format
 *
 * Prefix:
 * - `-`: Removed.
 * - `+`: Added.
 * - `\`: Previous line didn't end with a new line.
 */
fun String.readLineChanges(start: Int): Pair<List<LineChange>, Int> {
    val changes = mutableListOf<LineChange>()
    var lastKnownLine: Int = start
    var lastLine: Int? = start
    while (lastLine != null) {
        if (lastLine == this.length) {
            break;
        }

        if (this[lastLine] == '\n') {
            lastLine += 1;
            lastKnownLine = lastLine
            continue;
        }

        val computeLastLine = {
            if (lastKnownLine.endsInNewLine(this)
                && !lookupFor(lastKnownLine, '+', ' ')
                && !lookupFor(lastKnownLine, '-', ' ')
            ) {
                null
            } else {
                lastKnownLine
            }
        }
        val lineStr = this.substringUntil(lastLine, '\n')
        val isEndOfStream = {
            lastKnownLine + 1 == this.length
        }
        if (lineStr.startsWith("+ ") || lineStr.startsWith("- ")) {
            lastKnownLine = lastLine + lineStr.lastIndex

            val symbol = lineStr[0].toString()
            val data = lineStr.substring(2)

            changes += LineChange(LineChangeType.fromSymbol(symbol), data)

            lastLine = computeLastLine()
        } else if ((lineStr == "\\\n" || (lineStr == "\\" && isEndOfStream())) && changes.isNotEmpty()) {
            lastKnownLine = lastLine + lineStr.lastIndex
            if (isEndOfStream()) {
                lastKnownLine += 1
            }
            val last = changes.removeLast()
            changes += last.copy(data = last.data.substringBeforeLast("\n"))
            lastLine = computeLastLine()
        } else {
            // DEPRECATED: This is not how it works, a single slash (\) after any change
            //             means that the last line does not have a new line character, thus
            //             we need to remove it.
            // Single \ is used sometimes to represent an end of a change.
            if (lastKnownLine < this.length && this[lastKnownLine] == '\\' && lastKnownLine + 1 < this.length) {
                lastKnownLine += 1
            }
            lastLine = null
        }
    }

    return changes to lastKnownLine
}

private fun String.lookupFor(from: Int, charA: Char, charB: Char): Boolean {
    for (i in from..this.lastIndex) {
        if (this[i] == '\n') continue
        if (i + 1 >= this.length) return false
        return this[i] == charA && this[i + 1] == charB
    }
    return false
}

private fun Int.endsInNewLine(originalText: String): Boolean =
    this + 1 < originalText.length && originalText[this + 1] == '\n'

val RFC3339_FORMATTER = DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd'T'HH:mm:ss")
    .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
    .appendOffsetId()
    .toFormatter()
    .withResolverStyle(ResolverStyle.LENIENT)

fun String.parseAsLocalDateTime(): ZonedDateTime {
    return ZonedDateTime.parse(this, RFC3339_FORMATTER)
}

fun FileDelHunk.fileDelHunkAsSource() = "FileDelHunk(\n" +
        "hunkNumber = $hunkNumber,\n" +
        "type = ${this.type.hunkTypeAsSource()},\n" +
        "path = \"$path\",\n" +
        "inode = ${this.inode?.toString() ?: "null"},\n" +
        "lines = ${lines.asSource()},\n" +
        "meta = ${meta?.metaAsSource() ?: "null"},\n" +
        "flags = ${flags.flagsAsSource()},\n" +
        "context = ${context?.contextAsSource() ?: "null"},\n" +
        ")"

fun FileAddHunk.fileAddHunkAsSource() = "FileAddHunk(\n" +
        "hunkNumber = $hunkNumber,\n" +
        "type = ${this.type.hunkTypeAsSource()},\n" +
        "path = \"$path\",\n" +
        "rootPath = \"$rootPath\",\n" +
        "lines = ${lines.asSource()},\n" +
        "meta = ${meta?.metaAsSource() ?: "null"},\n" +
        "flags = ${flags.flagsAsSource()},\n" +
        "context = ${context?.contextAsSource() ?: "null"},\n" +
        ")"


fun FileUnDelHunk.fileUnDelHunkAsSource() = "FileUnDelHunk(\n" +
        "hunkNumber = $hunkNumber,\n" +
        "type = ${this.type.hunkTypeAsSource()},\n" +
        "path = \"$path\",\n" +
        "inode = ${this.inode?.toString() ?: "null"},\n" +
        "lines = ${lines.asSource()},\n" +
        "meta = ${meta?.metaAsSource() ?: "null"},\n" +
        "flags = ${flags.flagsAsSource()},\n" +
        "context = ${context?.contextAsSource() ?: "null"},\n" +
        ")"

fun MoveHunk.moveHunkAsSource() = "MoveHunk(\n" +
        "hunkNumber = $hunkNumber,\n" +
        "type = ${this.type.hunkTypeAsSource()},\n" +
        "older = \"$older\",\n" +
        "new = \"$new\",\n" +
        "meta = ${meta?.metaAsSource() ?: "null"},\n" +
        "flags = ${flags.flagsAsSource()},\n" +
        "context = ${context?.contextAsSource() ?: "null"},\n" +
        ")"

fun EditHunk.editHunkAsSource() = "EditHunk(\n" +
        "hunkNumber = $hunkNumber,\n" +
        "type = ${this.type.hunkTypeAsSource()},\n" +
        "path = \"$path\",\n" +
        "startLine = $startLine,\n" +
        "inode = ${inode?.toString() ?: "null"},\n" +
        "lines = ${lines.asSource()},\n" +
        "meta = ${meta?.metaAsSource() ?: "null"},\n" +
        "flags = ${flags.flagsAsSource()},\n" +
        "context = ${context?.contextAsSource() ?: "null"},\n" +
        ")"

fun ReplacementHunk.replacementHunkAsSource() = "ReplacementHunk(\n" +
        "hunkNumber = $hunkNumber,\n" +
        "type = ${this.type.hunkTypeAsSource()},\n" +
        "path = \"$path\",\n" +
        "startLine = $startLine,\n" +
        "inode = ${inode?.toString() ?: "null"},\n" +
        "lines = ${lines.asSource()},\n" +
        "meta = ${meta?.metaAsSource() ?: "null"},\n" +
        "flags = ${flags.flagsAsSource()},\n" +
        "context = ${context?.contextAsSource() ?: "null"},\n" +
        ")"

fun NameConflictHunk.nameConflictHunkAsSource() = "NameConflictHunk(\n" +
        "hunkNumber = $hunkNumber,\n" +
        "type = ${this.type.hunkTypeAsSource()},\n" +
        "path = \"$path\",\n" +
        "inode = ${inode?.toString() ?: "null"},\n" +
        "deletedNames = ${deletedNames.stringListAsSource()},\n" +
        "meta = ${meta?.metaAsSource() ?: "null"},\n" +
        "flags = ${flags.flagsAsSource()},\n" +
        "context = ${context?.contextAsSource() ?: "null"},\n" +
        ")"

fun OrderConflictHunk.orderConflictHunkAsSource() = "OrderConflictHunk(\n" +
        "hunkNumber = $hunkNumber,\n" +
        "type = ${this.type.hunkTypeAsSource()},\n" +
        "path = \"$path\",\n" +
        "index = ${index?.toString() ?: "null"},\n" +
        "inode = ${inode?.toString() ?: "null"},\n" +
        "lines = ${lines.asSource()},\n" +
        "meta = ${meta?.metaAsSource() ?: "null"},\n" +
        "flags = ${flags.flagsAsSource()},\n" +
        "context = ${context?.contextAsSource() ?: "null"},\n" +
        ")"

fun ZombieResurrectHunk.zombieResurrectHunkAsSource() = "ZombieResurrectHunk(\n" +
        "hunkNumber = $hunkNumber,\n" +
        "type = ${this.type.hunkTypeAsSource()},\n" +
        "path = \"$path\",\n" +
        "inode = ${inode?.toString() ?: "null"},\n" +
        "lines = ${lines.asSource()},\n" +
        "meta = ${meta?.metaAsSource() ?: "null"},\n" +
        "flags = ${flags.flagsAsSource()},\n" +
        "context = ${context?.contextAsSource() ?: "null"},\n" +
        ")"

fun HunkType.hunkTypeAsSource() = "HunkType.${this.name}"

fun List<LineChange>.asSource() =
    if(this.isEmpty()) "emptyList()"
    else "listOf(${this.joinToString(separator = ", ") { it.lineChangeAsSource() }})"


fun List<Flag>.flagsAsSource() =
    if(this.isEmpty()) "emptyList()"
    else "listOf(${this.joinToString(separator = ", ") { it.flagsAsSource() }})"

fun Meta.metaAsSource() = "Meta(\"${StringEscapeUtils.escapeJava(plain)}\")"

fun Flag.flagsAsSource() = "Flag(\"${StringEscapeUtils.escapeJava(plain)}\")"

fun List<String>.stringListAsSource() =
    if (this.isEmpty()) "emptyList()"
    else "listOf(\"${this.joinToString(separator = ", ") { StringEscapeUtils.escapeJava(it) }}\")"

fun Context.contextAsSource() = "Context(" +
        "up = ${this.up.doublesAsSource()}, " +
        "new = ${this.new?.intRangeAsSource() ?: "null"}, " +
        "down = ${this.down.doublesAsSource()}" +
        ")"

fun LineChange.lineChangeAsSource() = "LineChange(" +
        "type = LineChangeType.${type.name}, " +
        "data = \"${StringEscapeUtils.escapeJava(data)}\"" +
        ")"

val HunkWithPath.status: FileStatus
    get() = (this as Hunk).status

val Hunk.status: FileStatus
    get() = when(this) {
        is FileAddHunk -> FileStatus.ADDED
        is FileDelHunk -> FileStatus.DELETED
        is ReplacementHunk -> FileStatus.MODIFIED
        is EditHunk -> FileStatus.MODIFIED
        is MoveHunk -> FileStatus.SUPPRESSED
        else -> FileStatus.UNKNOWN
    }