├── gradle.properties ├── images ├── logo.png ├── kit-tag.png ├── kit-help.png ├── kit-init.png ├── kit-add-status.png ├── kit-config-commit.png ├── kit-branch-checkout.png └── kit-convert-to-git.png ├── settings.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .idea ├── codeStyles │ ├── codeStyleConfig.xml │ └── Project.xml ├── kotlinc.xml ├── vcs.xml ├── inspectionProfiles │ └── Project_Default.xml ├── misc.xml ├── gradle.xml └── workspace.xml ├── src ├── main │ └── kotlin │ │ └── kit │ │ ├── Main.kt │ │ ├── cli │ │ ├── LogCommand.kt │ │ ├── StatusCommand.kt │ │ ├── GitCommand.kt │ │ ├── CommitCommand.kt │ │ ├── CheckoutCommand.kt │ │ ├── Cli.kt │ │ ├── AddCommand.kt │ │ ├── ConfigCommand.kt │ │ ├── UnStageCommand.kt │ │ ├── InitCommand.kt │ │ ├── BranchCommand.kt │ │ ├── TagCommand.kt │ │ └── Kit.kt │ │ ├── plumbing │ │ ├── Zlib.kt │ │ ├── GitIndex.kt │ │ └── plumbing.kt │ │ ├── utils │ │ └── Utils.kt │ │ └── porcelain │ │ ├── Config.kt │ │ └── Porcaline.kt └── test │ └── kotlin │ └── kit │ ├── utils │ └── UtilsKtTest.kt │ ├── porcelain │ └── PorcelainKtTest.kt │ └── plumbing │ └── PlumbingKtTest.kt ├── .gitignore ├── LICENSE ├── gradlew.bat ├── README.md └── gradlew /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official 2 | -------------------------------------------------------------------------------- /images/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Badr-1/Kit/HEAD/images/logo.png -------------------------------------------------------------------------------- /images/kit-tag.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Badr-1/Kit/HEAD/images/kit-tag.png -------------------------------------------------------------------------------- /images/kit-help.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Badr-1/Kit/HEAD/images/kit-help.png -------------------------------------------------------------------------------- /images/kit-init.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Badr-1/Kit/HEAD/images/kit-init.png -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | 2 | rootProject.name = "Git-A-Home-Made-Recipe-With-Kotlin" 3 | 4 | -------------------------------------------------------------------------------- /images/kit-add-status.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Badr-1/Kit/HEAD/images/kit-add-status.png -------------------------------------------------------------------------------- /images/kit-config-commit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Badr-1/Kit/HEAD/images/kit-config-commit.png -------------------------------------------------------------------------------- /images/kit-branch-checkout.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Badr-1/Kit/HEAD/images/kit-branch-checkout.png -------------------------------------------------------------------------------- /images/kit-convert-to-git.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Badr-1/Kit/HEAD/images/kit-convert-to-git.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Badr-1/Kit/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /src/main/kotlin/kit/Main.kt: -------------------------------------------------------------------------------- 1 | package kit 2 | 3 | import kit.cli.* 4 | 5 | object Main { 6 | @JvmStatic 7 | fun main(args: Array) { 8 | Cli.kit.main(args) 9 | } 10 | } -------------------------------------------------------------------------------- /.idea/kotlinc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists -------------------------------------------------------------------------------- /src/main/kotlin/kit/cli/LogCommand.kt: -------------------------------------------------------------------------------- 1 | package kit.cli 2 | 3 | import com.github.ajalt.clikt.core.CliktCommand 4 | import kit.porcelain.log 5 | 6 | class LogCommand : CliktCommand(name = "log", help = "Show commit logs") { 7 | override fun run() { 8 | log() 9 | } 10 | } -------------------------------------------------------------------------------- /src/main/kotlin/kit/cli/StatusCommand.kt: -------------------------------------------------------------------------------- 1 | package kit.cli 2 | 3 | import com.github.ajalt.clikt.core.CliktCommand 4 | import kit.porcelain.status 5 | 6 | class StatusCommand : CliktCommand(name = "status", help = "Show the working tree status") { 7 | override fun run() { 8 | status() 9 | } 10 | } -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 9 | 10 | -------------------------------------------------------------------------------- /src/main/kotlin/kit/cli/GitCommand.kt: -------------------------------------------------------------------------------- 1 | package kit.cli 2 | 3 | import com.github.ajalt.clikt.core.CliktCommand 4 | import java.io.File 5 | 6 | class GitCommand : CliktCommand(name = "git", help = "convert kit repository to git repository") { 7 | override fun run() { 8 | // change .kit to .git 9 | val kitDir = File("${System.getProperty("user.dir")}/.kit") 10 | val gitDir = File("${System.getProperty("user.dir")}/.git") 11 | kitDir.renameTo(gitDir) 12 | } 13 | } -------------------------------------------------------------------------------- /src/main/kotlin/kit/cli/CommitCommand.kt: -------------------------------------------------------------------------------- 1 | package kit.cli 2 | 3 | import com.github.ajalt.clikt.core.CliktCommand 4 | import com.github.ajalt.clikt.parameters.options.option 5 | import com.github.ajalt.clikt.parameters.options.required 6 | import kit.porcelain.commit 7 | 8 | class CommitCommand : CliktCommand(name = "commit", help = "Record changes to the repository") { 9 | private val message by option("-m", "--message", help = "Commit message").required() 10 | 11 | override fun run() { 12 | commit(message) 13 | } 14 | } -------------------------------------------------------------------------------- /src/main/kotlin/kit/cli/CheckoutCommand.kt: -------------------------------------------------------------------------------- 1 | package kit.cli 2 | 3 | import com.github.ajalt.clikt.core.CliktCommand 4 | import com.github.ajalt.clikt.parameters.arguments.argument 5 | import kit.porcelain.checkout 6 | 7 | class CheckoutCommand : CliktCommand(name = "checkout", help = "Switch branches or restore working tree files") { 8 | private val branchOrCommit by argument( 9 | help = "The branch or commit to checkout", 10 | name = "branchOrCommit" 11 | ) 12 | 13 | override fun run() { 14 | checkout(branchOrCommit) 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/kotlin/kit/cli/Cli.kt: -------------------------------------------------------------------------------- 1 | package kit.cli 2 | 3 | import com.github.ajalt.clikt.completion.CompletionCommand 4 | import com.github.ajalt.clikt.core.subcommands 5 | 6 | object Cli{ 7 | val kit = Kit().subcommands( 8 | InitCommand(), 9 | ConfigCommand(), 10 | GitCommand(), 11 | AddCommand(), 12 | UnStageCommand(), 13 | StatusCommand(), 14 | CommitCommand(), 15 | LogCommand(), 16 | CheckoutCommand(), 17 | BranchCommand(), 18 | TagCommand(), 19 | CompletionCommand() 20 | ) 21 | } -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 15 | 16 | -------------------------------------------------------------------------------- /src/main/kotlin/kit/cli/AddCommand.kt: -------------------------------------------------------------------------------- 1 | package kit.cli 2 | 3 | import com.github.ajalt.clikt.core.CliktCommand 4 | import com.github.ajalt.clikt.parameters.arguments.argument 5 | import kit.porcelain.add 6 | 7 | class AddCommand : CliktCommand(name = "add", help = "Add file contents to the index") { 8 | private val path by argument( 9 | help = "The path of the file to add", 10 | name = "path" 11 | ) 12 | 13 | override fun run() { 14 | if (path.startsWith(System.getProperty("user.dir"))) 15 | add(path) 16 | else 17 | add(System.getProperty("user.dir") + "/" + path) 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/kotlin/kit/cli/ConfigCommand.kt: -------------------------------------------------------------------------------- 1 | package kit.cli 2 | 3 | import com.github.ajalt.clikt.core.CliktCommand 4 | import com.github.ajalt.clikt.parameters.arguments.argument 5 | import kit.porcelain.Config 6 | 7 | 8 | class ConfigCommand : CliktCommand(name = "config", help = "Set kit configuration values") { 9 | private val name by argument( 10 | help = "The name of the configuration value", 11 | name = "name" 12 | ) 13 | private val value by argument( 14 | help = "The value of the configuration value", 15 | name = "value" 16 | ) 17 | 18 | override fun run() { 19 | Config.set(name, value) 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/kotlin/kit/cli/UnStageCommand.kt: -------------------------------------------------------------------------------- 1 | package kit.cli 2 | 3 | import com.github.ajalt.clikt.core.CliktCommand 4 | import com.github.ajalt.clikt.parameters.arguments.argument 5 | import kit.porcelain.unstage 6 | 7 | class UnStageCommand : CliktCommand(name = "unstage", help = "Remove file contents from the index") { 8 | private val path by argument( 9 | help = "The path of the file to unstage", 10 | name = "path" 11 | ) 12 | 13 | override fun run() { 14 | if (path.startsWith(System.getProperty("user.dir"))) 15 | unstage(path) 16 | else 17 | unstage(System.getProperty("user.dir") + "/" + path) 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/kotlin/kit/cli/InitCommand.kt: -------------------------------------------------------------------------------- 1 | package kit.cli 2 | 3 | import com.github.ajalt.clikt.core.CliktCommand 4 | import com.github.ajalt.clikt.parameters.arguments.argument 5 | import com.github.ajalt.clikt.parameters.arguments.optional 6 | import kit.porcelain.init 7 | import java.nio.file.Path 8 | 9 | class InitCommand : CliktCommand(name = "init", help = "Initialize a new, empty repository") { 10 | private val directory by argument( 11 | help = "Directory to initialize the repository in", 12 | name = "directory" 13 | ).optional() 14 | 15 | override fun run() { 16 | val path = Path.of(directory ?: "").toAbsolutePath() 17 | init(path) 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/kotlin/kit/cli/BranchCommand.kt: -------------------------------------------------------------------------------- 1 | package kit.cli 2 | 3 | import com.github.ajalt.clikt.core.CliktCommand 4 | import com.github.ajalt.clikt.parameters.arguments.argument 5 | import com.github.ajalt.clikt.parameters.arguments.optional 6 | import kit.porcelain.branch 7 | 8 | class BranchCommand : CliktCommand(name = "branch", help = "create branch") { 9 | private val branchName by argument( 10 | help = "The name of the branch", 11 | name = "branchName" 12 | ) 13 | private val ref by argument().optional() 14 | 15 | override fun run() { 16 | if (ref == null) 17 | branch(branchName) 18 | else 19 | branch(branchName, ref!!) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | !**/src/main/**/build/ 5 | !**/src/test/**/build/ 6 | working/ 7 | 8 | ### IntelliJ IDEA ### 9 | .idea/modules.xml 10 | .idea/jarRepositories.xml 11 | .idea/compiler.xml 12 | .idea/libraries/ 13 | *.iws 14 | *.iml 15 | *.ipr 16 | out/ 17 | !**/src/main/**/out/ 18 | !**/src/test/**/out/ 19 | 20 | ### Eclipse ### 21 | .apt_generated 22 | .classpath 23 | .factorypath 24 | .project 25 | .settings 26 | .springBeans 27 | .sts4-cache 28 | bin/ 29 | !**/src/main/**/bin/ 30 | !**/src/test/**/bin/ 31 | 32 | ### NetBeans ### 33 | /nbproject/private/ 34 | /nbbuild/ 35 | /dist/ 36 | /nbdist/ 37 | /.nb-gradle/ 38 | 39 | ### VS Code ### 40 | .vscode/ 41 | 42 | ### Mac OS ### 43 | .DS_Store -------------------------------------------------------------------------------- /src/main/kotlin/kit/cli/TagCommand.kt: -------------------------------------------------------------------------------- 1 | package kit.cli 2 | 3 | import com.github.ajalt.clikt.core.CliktCommand 4 | import com.github.ajalt.clikt.parameters.arguments.argument 5 | import com.github.ajalt.clikt.parameters.arguments.optional 6 | import com.github.ajalt.clikt.parameters.options.option 7 | import com.github.ajalt.clikt.parameters.options.required 8 | import kit.porcelain.tag 9 | 10 | class TagCommand : CliktCommand(name = "tag", help = "create tag") { 11 | private val tagName by argument( 12 | help = "The name of the tag", 13 | name = "tagName" 14 | ) 15 | private val ref by argument().optional() 16 | private val message by option("-m", "--message", help = "Tag message").required() 17 | override fun run() { 18 | if (ref == null) 19 | tag(tagName, message) 20 | else 21 | tag(tagName, message, ref!!) 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/kotlin/kit/cli/Kit.kt: -------------------------------------------------------------------------------- 1 | package kit.cli 2 | 3 | import com.github.ajalt.clikt.core.CliktCommand 4 | import kit.plumbing.GitIndex 5 | import kit.porcelain.Config 6 | import java.io.File 7 | import kotlin.system.exitProcess 8 | 9 | class Kit : CliktCommand(name = "kit", help = "The kit version control system") { 10 | override fun run() { 11 | val context = currentContext 12 | val subcommand = context.invokedSubcommand 13 | if (File("${System.getProperty("user.dir")}/.kit").exists()) { 14 | // load config file 15 | Config.read() 16 | // load index file 17 | GitIndex 18 | } else { 19 | // only the init command is allowed to run without a .kit directory 20 | if (subcommand?.commandName != "init") { 21 | echo("Not a kit repository (or any of the parent directories): .kit") 22 | exitProcess(1) 23 | } 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 badr 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /src/test/kotlin/kit/utils/UtilsKtTest.kt: -------------------------------------------------------------------------------- 1 | package kit.utils 2 | 3 | import org.junit.jupiter.api.Test 4 | 5 | import org.junit.jupiter.api.Assertions.* 6 | 7 | class UtilsKtTest { 8 | 9 | /** 10 | * Testing whether the runCommand function returns the correct output 11 | */ 12 | @Test 13 | fun runCommand() { 14 | val command = "echo Hello World" 15 | val output = command.runCommand() 16 | assertEquals( 17 | /* expected = */ "Hello World", 18 | /* actual = */ output, 19 | /* message = */ "The output should be equal" 20 | ) 21 | } 22 | /** 23 | * Testing whether it throws an exception when the command fails 24 | */ 25 | @Test 26 | fun runCommandFail() { 27 | val command = "ls -l /non/existing/path" 28 | try { 29 | command.runCommand() 30 | fail("The command should fail") 31 | } catch (e: RuntimeException) { 32 | assertEquals( 33 | /* expected = */ "Command '$command' failed", 34 | /* actual = */ e.message, 35 | /* message = */ "The exception message should be equal" 36 | ) 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /src/main/kotlin/kit/plumbing/Zlib.kt: -------------------------------------------------------------------------------- 1 | package kit.plumbing 2 | 3 | import java.io.ByteArrayOutputStream 4 | import java.util.zip.* 5 | 6 | /** 7 | * Zlib compression and decompression. 8 | */ 9 | object Zlib { 10 | 11 | /** 12 | * Compresses the given byte array using the Zlib algorithm. 13 | * @param content The byte array to compress. 14 | * @return The compressed byte array. 15 | */ 16 | @JvmStatic 17 | fun deflate(content: ByteArray): ByteArray { 18 | val deflater = Deflater() 19 | deflater.setInput(content) 20 | deflater.finish() 21 | val buffer = ByteArray(1024) 22 | val outputStream = ByteArrayOutputStream() 23 | while (!deflater.finished()) { 24 | val count = deflater.deflate(buffer) 25 | outputStream.write(buffer, 0, count) 26 | } 27 | outputStream.close() 28 | return outputStream.toByteArray() 29 | } 30 | 31 | /** 32 | * Decompresses the given byte array using the Zlib algorithm. 33 | * @param content The byte array to decompress. 34 | * @return The decompressed byte array. 35 | */ 36 | @JvmStatic 37 | fun inflate(content: ByteArray): ByteArray { 38 | val inflater = Inflater() 39 | inflater.setInput(content) 40 | val buffer = ByteArray(1024) 41 | val outputStream = ByteArrayOutputStream() 42 | while (!inflater.finished()) { 43 | val count = inflater.inflate(buffer) 44 | outputStream.write(buffer, 0, count) 45 | } 46 | outputStream.close() 47 | return outputStream.toByteArray() 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/kotlin/kit/utils/Utils.kt: -------------------------------------------------------------------------------- 1 | package kit.utils 2 | import java.io.File 3 | import java.nio.file.Files 4 | import java.util.concurrent.TimeUnit 5 | import kotlin.io.path.Path 6 | 7 | /** 8 | * Runs the given command and returns the output 9 | */ 10 | fun String.runCommand(): String { 11 | 12 | val process = ProcessBuilder(*split(" ").toTypedArray()) 13 | .redirectOutput(ProcessBuilder.Redirect.PIPE) 14 | .redirectError(ProcessBuilder.Redirect.PIPE) 15 | .start().apply { waitFor(60, TimeUnit.MINUTES) } 16 | 17 | val output = process.inputStream.bufferedReader().readText() 18 | 19 | if (process.exitValue() == 0) { 20 | return output.trim() 21 | } else { 22 | throw RuntimeException("Command '$this' failed") 23 | } 24 | } 25 | 26 | /** 27 | * convert a hex string to a byte array 28 | */ 29 | fun String.hexStringToByteArray(): ByteArray { 30 | val len = length 31 | require(len % 2 == 0) { "Hex string must have even number of characters" } 32 | val byteArray = ByteArray(len / 2) 33 | var i = 0 34 | while (i < len) { 35 | byteArray[i / 2] = ((Character.digit(get(i), 16) shl 4) 36 | + Character.digit(get(i + 1), 16)).toByte() 37 | i += 2 38 | } 39 | return byteArray 40 | } 41 | 42 | /** 43 | * returns the relative path of this file to the given path 44 | * @param path the path to which the relative path is calculated 45 | */ 46 | fun File.relativePath(path: String = System.getProperty("user.dir")): String = this.relativeTo(File(path)).path 47 | 48 | /** 49 | * helper function that returns the mode of a file 50 | * @param file the file 51 | * @return the mode based on git's documentation 52 | */ 53 | fun getMode(file: File): String { 54 | val mode = when { 55 | // check if the file is executable 56 | file.canExecute() -> "100755" 57 | // check if the file is a symlink 58 | Files.isSymbolicLink(Path(file.path)) -> "120000" 59 | // then it's a normal file 60 | else -> "100644" 61 | } 62 | return mode 63 | } 64 | 65 | /** 66 | * colorize the output in blue 67 | */ 68 | fun String.blue() = "\u001B[34m$this\u001B[0m" 69 | 70 | /** 71 | * colorize the output in red 72 | */ 73 | fun String.red() = "\u001B[31m$this\u001B[0m" 74 | 75 | /** 76 | * colorize the output in green 77 | */ 78 | fun String.green() = "\u001B[32m$this\u001B[0m" 79 | 80 | /** 81 | * colorize the output in yellow 82 | */ 83 | fun String.yellow() = "\u001B[33m$this\u001B[0m" -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/main/kotlin/kit/porcelain/Config.kt: -------------------------------------------------------------------------------- 1 | package kit.porcelain 2 | 3 | import java.io.File 4 | 5 | /** 6 | * a singleton object that represents the config file 7 | */ 8 | object Config { 9 | /** 10 | * consists of the following: 11 | * - sections, eg [ core ] 12 | * - keys, eg repositoryformatversion 13 | * - values, eg 0 14 | * */ 15 | private fun getConfigFile() = File("${System.getProperty("user.dir")}/.kit/config") 16 | private val sections = mutableSetOf("core") // to be updated when more sections are added 17 | private val values = mutableMapOf( 18 | "core" to mutableMapOf( 19 | "repositoryformatversion" to "0", "filemode" to "true", "bare" to "false", "logallrefupdates" to "true" 20 | ) 21 | ) 22 | 23 | /** 24 | * unset the config file to its default values 25 | */ 26 | fun unset() { 27 | sections.removeIf { it != "core" } 28 | } 29 | 30 | /** 31 | * write the config file 32 | */ 33 | fun write() { 34 | getConfigFile().createNewFile() 35 | getConfigFile().writeText("") 36 | for (section in sections) { 37 | getConfigFile().appendText("[$section]\n") 38 | for ((key, value) in values[section]!!) { 39 | getConfigFile().appendText("\t$key = $value\n") 40 | } 41 | } 42 | } 43 | 44 | /** 45 | * read the config file attributes 46 | */ 47 | fun read() { 48 | val lines = getConfigFile().readLines() 49 | for (line in lines) { 50 | if (line.startsWith("[")) { 51 | val section = line.substring(1, line.length - 1) 52 | sections.add(section) 53 | values[section] = mutableMapOf() 54 | } else if (line.startsWith("\t")) { 55 | val key = line.substring(line.indexOf("\t") + 1, line.indexOf(" = ")) 56 | val value = line.substring(line.indexOf(" = ") + 3) 57 | values[sections.last()]!![key] = value 58 | } 59 | } 60 | } 61 | 62 | /** 63 | * set a value in the config file and write it 64 | * @param sectionWithKey the section and key separated by a dot, e.g. core.repositoryformatversion 65 | * @param value the value to be set 66 | */ 67 | fun set(sectionWithKey: String, value: String) { 68 | val section = sectionWithKey.split(".")[0] 69 | val key = sectionWithKey.split(".")[1] 70 | if (!sections.contains(section)) { 71 | sections.add(section) 72 | values[section] = mutableMapOf() 73 | } 74 | values[section]!![key] = value 75 | write() 76 | } 77 | 78 | /** 79 | * get a value from the config file 80 | * @param sectionWithKey the section and key separated by a dot, e.g. core.repositoryformatversion 81 | * @return the value 82 | */ 83 | fun get(sectionWithKey: String): String { 84 | val section = sectionWithKey.split(".")[0] 85 | val key = sectionWithKey.split(".")[1] 86 | if (section == "user" && (key == "name" || key == "email")) { 87 | if (!sections.contains(section)) { 88 | sections.add(section) 89 | values[section] = mutableMapOf() 90 | } 91 | if (values[section]!![key] == null) values[section]!![key] = "Kit $key" 92 | } 93 | return values[section]!![key]!! 94 | } 95 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Git A Home-Made Recipe With Kotlin 2 |
3 | 4 |
5 | 6 | ## About 7 | 8 | This Project is My Attempt To Reimplement Git With Kotlin. 9 |
Why? I See You Wondering... Why Not?\ 10 | I've Been Reading About Git For Quite Some Time And have Explained It To Many Of My Peers.\ 11 | And While I Was Learning Kotlin With JetBrains Academy, One Of The Projects Was About Version Control System, especially 12 | Git, But The Implementation Level Wasn't That Interesting, After That I came Across [CodeCrafters](https://codecrafters.io/), 13 | They have modules for building some projects with theme `Build Your Own`, and one of them was `Build Your Own Git`, 14 | but it didn't also catch my attention, and they didn't have a kotlin version, so I decided to implement it myself, and make it compatible with git and I named it `kit (kotlin implementation of git).`\ 15 | my intention for this project was to learn more about git, and build a decent project with kotlin considering that it's my favorite language.\ 16 | also I'm not implementing the whole git, I'm just implementing the core features of git, and I'm not implementing it in the best way, I'm just trying to implement it in a way that I can understand it, and hopefully others can understand it too. 17 | so it's **an educational project**, also if you want to contribute, you're welcome. 18 | 19 | ## Features 20 | 21 | git have two types of commands: 22 | - **Low Level Commands ie plumbing commands**: these commands are the core commands of git, and they are the commands that git uses to implement the high level commands, you rarely use these commands directly, but you can use them if you want to. 23 | - **High Level Commands ie porcelain commands**: these commands are the commands that the user uses to interact with git. 24 | 25 | git model is based on four objects: 26 | - **Blob**: a blob is a file, it's the smallest unit of git, it's the content of a file. 27 | - **Tree**: a tree is a directory, it's a collection of blobs and trees. 28 | - **Commit**: a commit is a snapshot of the repository, it's a collection of trees and blobs. 29 | - **Tag**: a tag is a label for a commit, it's a pointer to a commit. 30 | 31 | I'v Implemented the following commands: 32 | ## Plumbing Commands 33 | - [x] hash-object 34 | - [x] cat-file 35 | - [x] update-index 36 | - [x] write-tree 37 | - [x] commit-tree 38 | - [x] ls-files 39 | 40 | ## Porcelain Commands 41 | - [x] init 42 | - [x] add 43 | - [x] unStage 44 | - [x] commit 45 | - [x] tag 46 | - [x] log 47 | - [x] status 48 | - [x] checkout 49 | - [x] branch 50 | - [x] config 51 | 52 | ## Installation 53 | 54 | You don't need to install anything, just download the jar file from the [releases](https://github.com/Badr-1/Git-A-Home-Made-Recipe-With-Kotlin/releases) , and run it with 55 | ```bash 56 | java -jar kit.jar 57 | ``` 58 | and to use it like you use git, you can create a bash script with the following content and add it to your path 59 | ```bash 60 | #!/bin/bash 61 | java -jar /path/to/kit.jar "$@" 62 | ``` 63 | just make sure that you replace `/path/to/kit.jar` with the actual path to the jar file. 64 | 65 | 66 | 67 | ## Screenshots 68 | 69 | ### Init a repo creating a file and checking status 70 | 71 |
72 | 73 |
74 | 75 | ### Adding file to index and configuring user then committing and log to see the commit 76 | 77 |
78 | 79 |
80 | 81 |
82 | 83 |
84 | 85 | ### Create a branch and checkout to it 86 | 87 |
88 | 89 |
90 | 91 | ### Create a tag 92 | 93 |
94 | 95 |
96 | 97 | ### Convert repo to git repo 98 | 99 |
100 | 101 |
102 | 103 | ### Help 104 | 105 |
106 | 107 |
108 | 109 | ## How to contribute 110 | 1. Fork the project 111 | 2. Clone the project 112 | 3. Create a new branch with the name of the feature you're going to implement 113 | 4. Implement the feature 114 | 5. write tests for the feature 115 | 6. commit and push your changes 116 | 7. create a pull request 117 | 118 | And I'll gladly review and merge your changes 🎉 119 | 120 | ## License 121 | [MIT](https://choosealicense.com/licenses/mit/) 122 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /src/main/kotlin/kit/plumbing/GitIndex.kt: -------------------------------------------------------------------------------- 1 | package kit.plumbing 2 | 3 | import kit.utils.* 4 | import java.io.File 5 | import java.nio.ByteBuffer 6 | import java.nio.file.Files 7 | import java.time.Instant 8 | import kotlin.experimental.and 9 | 10 | /** 11 | * Singleton class for managing the Git index file 12 | */ 13 | object GitIndex { 14 | private val entries = mutableListOf() 15 | private lateinit var signature: String 16 | private var version: Int = 2 17 | private var entryCount: Int = 0 18 | private val indexFile = File("${System.getProperty("user.dir")}/.kit/index") 19 | 20 | /** 21 | * gets count of entries in the index file 22 | */ 23 | fun getEntryCount(): Int { 24 | return entryCount 25 | } 26 | 27 | /** 28 | * data class for storing index file entries 29 | */ 30 | data class GitIndexEntry( 31 | var ctimeSeconds: Int, 32 | var ctimeNanoSeconds: Int, 33 | var mtimeSeconds: Int, 34 | var mtimeNanoSeconds: Int, 35 | val dev: Int, 36 | val ino: Int, 37 | val mode: Int, 38 | val uid: Int, 39 | val gid: Int, 40 | var fileSize: Int, 41 | var sha1: String, 42 | val flags: Int, 43 | val path: String, 44 | val padding: Int 45 | ) { 46 | /** 47 | * writes the entry to the index file 48 | */ 49 | fun write() { 50 | indexFile.appendBytes(ByteBuffer.allocate(4).putInt(ctimeSeconds).array()) 51 | indexFile.appendBytes(ByteBuffer.allocate(4).putInt(ctimeNanoSeconds).array()) 52 | indexFile.appendBytes(ByteBuffer.allocate(4).putInt(mtimeSeconds).array()) 53 | indexFile.appendBytes(ByteBuffer.allocate(4).putInt(mtimeNanoSeconds).array()) 54 | indexFile.appendBytes(ByteBuffer.allocate(4).putInt(dev).array()) 55 | indexFile.appendBytes(ByteBuffer.allocate(4).putInt(ino).array()) 56 | indexFile.appendBytes(ByteBuffer.allocate(4).putInt(mode).array()) 57 | indexFile.appendBytes(ByteBuffer.allocate(4).putInt(uid).array()) 58 | indexFile.appendBytes(ByteBuffer.allocate(4).putInt(gid).array()) 59 | indexFile.appendBytes(ByteBuffer.allocate(4).putInt(fileSize).array()) 60 | indexFile.appendBytes(sha1.hexStringToByteArray()) 61 | indexFile.appendBytes(ByteBuffer.allocate(2).putShort(flags.toShort()).array()) 62 | indexFile.appendBytes(path.toByteArray()) 63 | indexFile.appendBytes(ByteArray(padding)) 64 | } 65 | } 66 | 67 | init { 68 | readIndex() 69 | } 70 | 71 | /** 72 | * clear variables after index file is deleted 73 | */ 74 | fun clearIndex() { 75 | entries.clear() 76 | entryCount = 0 77 | } 78 | 79 | /** 80 | * reads the index file and stores the entries in the entries list 81 | */ 82 | fun readIndex() { 83 | if (indexFile.exists()) { 84 | val indexBytes: ByteArray = indexFile.readBytes() 85 | var offset = 0 86 | // The first 12 bytes of the index file are a header 87 | signature = String(indexBytes.copyOfRange(0, 4)) 88 | version = (ByteBuffer.wrap(indexBytes.copyOfRange(4, 8)).int) 89 | entryCount = (ByteBuffer.wrap(indexBytes.copyOfRange(8, 12)).int) 90 | offset += 12 91 | 92 | // The next section of the index file consists of entry metadata 93 | for (i in 0 until entryCount) { 94 | val ctimeSeconds = (ByteBuffer.wrap(indexBytes.copyOfRange(offset, offset + 4)).int) 95 | val ctimeNanoSeconds = (ByteBuffer.wrap(indexBytes.copyOfRange(offset + 4, offset + 8)).int) 96 | val mtimeSeconds = (ByteBuffer.wrap(indexBytes.copyOfRange(offset + 8, offset + 12)).int) 97 | val mtimeNanoSeconds = (ByteBuffer.wrap(indexBytes.copyOfRange(offset + 12, offset + 16)).int) 98 | val dev = (ByteBuffer.wrap(indexBytes.copyOfRange(offset + 16, offset + 20)).int) 99 | val ino = (ByteBuffer.wrap(indexBytes.copyOfRange(offset + 20, offset + 24)).int) 100 | val mode = ByteBuffer.wrap(indexBytes.copyOfRange(offset + 24, offset + 28)).int 101 | val uid = (ByteBuffer.wrap(indexBytes.copyOfRange(offset + 28, offset + 32)).int) 102 | val gid = (ByteBuffer.wrap(indexBytes.copyOfRange(offset + 32, offset + 36)).int) 103 | val fileSize = (ByteBuffer.wrap(indexBytes.copyOfRange(offset + 36, offset + 40)).getInt()) 104 | // read next 20 bytes for sha1 and decode it to hex string and put it in a variable 105 | val sha1 = indexBytes.copyOfRange(offset + 40, offset + 60).joinToString("") { "%02x".format(it) } 106 | val flags = (ByteBuffer.wrap(indexBytes.copyOfRange(offset + 60, offset + 62)).short) 107 | // 1 bit for assume valid 108 | // val assumeValid = flags and 0x8000.toShort() != 0.toShort() 109 | // 1 bit for extended 110 | // val extended = flags and 0x4000.toShort() != 0.toShort() 111 | // 1 bit for stageOne 112 | // val stageOne = flags and 0x2000.toShort() != 0.toShort() 113 | // 1 bit for stageTwo 114 | // val stageTwo = flags and 0x1000.toShort() != 0.toShort() 115 | // val stage = stageOne.toString() + stageTwo.toString() 116 | // 12 bits for name length 117 | val nameLength = flags and 0x0FFF.toShort() 118 | val path = String(indexBytes.copyOfRange(offset + 62, offset + 62 + nameLength)) 119 | offset += 62 + nameLength 120 | 121 | // convert this ((8 - ((62 + nameLength) % 8)) or 8) to int 122 | val padding = ((8 - ((62 + nameLength) % 8)).coerceAtMost(8)) 123 | // treat padding as a binary number and convert it to int 124 | 125 | // read next padding bytes 126 | // val paddingBytes = indexBytes.copyOfRange(offset, offset + padding) 127 | offset += padding 128 | 129 | entries.add( 130 | GitIndexEntry( 131 | ctimeSeconds, 132 | ctimeNanoSeconds, 133 | mtimeSeconds, 134 | mtimeNanoSeconds, 135 | dev, 136 | ino, 137 | mode, 138 | uid, 139 | gid, 140 | fileSize, 141 | sha1, 142 | flags.toInt(), 143 | path, 144 | padding 145 | ) 146 | ) 147 | } 148 | // The final section of the index file consists of the SHA1 of the index file 149 | indexBytes.copyOfRange(offset, offset + 20).joinToString("") { "%02x".format(it) } 150 | } else { 151 | indexFile.createNewFile() 152 | signature = "DIRC" 153 | version = 2 154 | entryCount = 0 155 | indexFile.writeBytes(signature.toByteArray()) 156 | indexFile.appendBytes(ByteBuffer.allocate(4).putInt(version).array()) 157 | indexFile.appendBytes(ByteBuffer.allocate(4).putInt(entryCount).array()) 158 | val sha1 = sha1(indexFile.readBytes()) 159 | indexFile.appendBytes(sha1.hexStringToByteArray()) 160 | entries.clear() 161 | } 162 | } 163 | 164 | /** 165 | * list all files in the index 166 | */ 167 | fun list(): String { 168 | return entries.joinToString("\n") { it.path } 169 | } 170 | 171 | /** 172 | * add a file to the index entries 173 | * @param file the file to add 174 | * @param sha1 the sha1 of the file 175 | * @param cacheInfo the cache info of the file 176 | */ 177 | fun add(file: File, sha1: String, cacheInfo: String) { 178 | // check if the file is already in the index 179 | if (entries.any { it.path == file.relativePath() }) { 180 | // check if the file is modified 181 | val entry = entries.first { it.path == file.relativePath() } 182 | if (entry.sha1 == sha1 && entry.mode == cacheInfo.toInt(8)) { 183 | return 184 | } 185 | remove(file) 186 | } 187 | // write header 188 | indexFile.writeBytes("".toByteArray()) 189 | indexFile.writeBytes(signature.toByteArray()) 190 | indexFile.appendBytes(ByteBuffer.allocate(4).putInt(version).array()) 191 | indexFile.appendBytes(ByteBuffer.allocate(4).putInt(entryCount + 1).array()) 192 | 193 | // add file to entries 194 | entries.add(makeEntry(file, sha1, cacheInfo)) 195 | 196 | // write entries 197 | entries.forEach { entry -> 198 | entry.write() 199 | } 200 | 201 | // write sha1 202 | indexFile.appendBytes(sha1(indexFile.readBytes()).hexStringToByteArray()) 203 | entryCount++ 204 | } 205 | 206 | /** 207 | * remove a file from the index entries 208 | * @param file the file to remove 209 | */ 210 | fun remove(file: File) { 211 | // check if the file is in the index 212 | if (entries.any { it.path == file.relativePath() }) { 213 | // remove the file from the index 214 | entries.removeIf { it.path == file.relativePath() } 215 | // write header 216 | indexFile.writeBytes("".toByteArray()) 217 | indexFile.writeBytes(signature.toByteArray()) 218 | indexFile.appendBytes(ByteBuffer.allocate(4).putInt(version).array()) 219 | indexFile.appendBytes(ByteBuffer.allocate(4).putInt(entryCount - 1).array()) 220 | 221 | // write entries 222 | entries.forEach { entry -> 223 | entry.write() 224 | } 225 | 226 | // write sha1 227 | indexFile.appendBytes(sha1(indexFile.readBytes()).hexStringToByteArray()) 228 | entryCount-- 229 | } 230 | } 231 | 232 | /** 233 | * get index entry by path 234 | * @param path path of the file 235 | * @return index entry 236 | */ 237 | fun get(path: String): GitIndexEntry? { 238 | return entries.firstOrNull { it.path == path } 239 | } 240 | 241 | /** 242 | * get all index entries 243 | * @return list of index entries 244 | */ 245 | fun entries(): List { 246 | return mutableListOf(*entries.toTypedArray()) 247 | } 248 | 249 | /** 250 | * create a new index entry 251 | * @param file file to be added 252 | * @param sha1 sha1 of the file 253 | * @param cacheInfo cache info of the file 254 | * @return index entry 255 | */ 256 | private fun makeEntry(file: File, sha1: String, cacheInfo: String): GitIndexEntry { 257 | val attr = Files.readAttributes(file.toPath(), "unix:*") 258 | val creationTime = Instant.parse("${attr["creationTime"]!!}").epochSecond 259 | val creationNanoTime = Instant.parse("${attr["creationTime"]!!}").nano 260 | val lastModifiedTime = Instant.parse("${attr["lastModifiedTime"]!!}").epochSecond 261 | val lastModifiedNanoTime = Instant.parse("${attr["lastModifiedTime"]!!}").nano 262 | val dev = attr["dev"]!!.toString().toInt() 263 | val ino = attr["ino"]!!.toString().toInt() 264 | val mode = cacheInfo.toInt(8) 265 | val uid = attr["uid"]!!.toString().toInt() 266 | val gid = attr["gid"]!!.toString().toInt() 267 | val fileSize = file.readBytes().size 268 | val name = file.relativePath() 269 | val flags = 0x0000 + name.length 270 | val entrySize = 62 + name.length 271 | val padding = ((8 - ((entrySize) % 8)).coerceAtMost(8)) 272 | return GitIndexEntry( 273 | creationTime.toInt(), 274 | creationNanoTime, 275 | lastModifiedTime.toInt(), 276 | lastModifiedNanoTime, 277 | dev, 278 | ino, 279 | mode, 280 | uid, 281 | gid, 282 | fileSize, 283 | sha1, 284 | flags, 285 | name, 286 | padding 287 | ) 288 | } 289 | } -------------------------------------------------------------------------------- /.idea/workspace.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 |