commit 7196b1b8e596935d349b508b0a0c43552dbfd168 Author: Abdelilah El Aissaoui Date: Fri Sep 24 14:25:17 2021 +0200 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a32b165 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +*.iml +.gradle +/local.properties +/.idea +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +build/ +/captures +.externalNativeBuild +.cxx diff --git a/README.md b/README.md new file mode 100644 index 0000000..244bed0 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# Gitnuro diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..0f6ff17 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,41 @@ +import org.jetbrains.compose.compose +import org.jetbrains.compose.desktop.application.dsl.TargetFormat +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +plugins { + // __KOTLIN_COMPOSE_VERSION__ + kotlin("jvm") version "1.5.21" + // __LATEST_COMPOSE_RELEASE_VERSION__ + id("org.jetbrains.compose") version "1.0.0-alpha1" +} + +group = "me.user" +version = "1.0" + +repositories { + mavenCentral() + google() + maven { url = uri("https://maven.pkg.jetbrains.space/public/p/compose/dev") } +} + +dependencies { + implementation(compose.desktop.currentOs) + implementation("org.eclipse.jgit:org.eclipse.jgit:5.13.0.202109080827-r") +} + +tasks.withType() { + kotlinOptions.jvmTarget = "11" + kotlinOptions.allWarningsAsErrors = true + kotlinOptions.freeCompilerArgs += "-Xopt-in=kotlin.RequiresOptIn" +} + +compose.desktop { + application { + mainClass = "org.jetbrains.compose.demo.falling.MainKt" + nativeDistributions { + targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb) + packageName = "Gitnuro" + packageVersion = "1.0.0-preview01" + } + } +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..29e08e8 --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7454180 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..69a9715 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..744e882 --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MSYS* | MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100755 index 0000000..ac1b06f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..cf76467 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,9 @@ +pluginManagement { + repositories { + gradlePluginPortal() + mavenCentral() + maven { url = uri("https://maven.pkg.jetbrains.space/public/p/compose/dev") } + } + +} +rootProject.name = "Gitnuro" \ No newline at end of file diff --git a/src/main/kotlin/aeab13/github/com/GPreferences.kt b/src/main/kotlin/aeab13/github/com/GPreferences.kt new file mode 100644 index 0000000..8dfdb05 --- /dev/null +++ b/src/main/kotlin/aeab13/github/com/GPreferences.kt @@ -0,0 +1,17 @@ +package aeab13.github.com + +import java.util.prefs.Preferences + +private const val PREFERENCES_NAME = "GitnuroConfig" + +private const val PREF_LAST_OPENED_REPOSITORY_PATH = "lastOpenedRepositoryPath" + +class GPreferences { + private val preferences: Preferences = Preferences.userRoot().node(PREFERENCES_NAME) + + var latestOpenedRepositoryPath: String + get() = preferences.get(PREF_LAST_OPENED_REPOSITORY_PATH, "") + set(value) { + preferences.put(PREF_LAST_OPENED_REPOSITORY_PATH, value) + } +} \ No newline at end of file diff --git a/src/main/kotlin/aeab13/github/com/RepositorySelected.kt b/src/main/kotlin/aeab13/github/com/RepositorySelected.kt new file mode 100644 index 0000000..da16028 --- /dev/null +++ b/src/main/kotlin/aeab13/github/com/RepositorySelected.kt @@ -0,0 +1,344 @@ +package aeab13.github.com + +import aeab13.github.com.extensions.filePath +import aeab13.github.com.extensions.icon +import aeab13.github.com.git.LogStatus +import aeab13.github.com.theme.backgroundColor +import aeab13.github.com.theme.primaryTextColor +import aeab13.github.com.theme.secondaryTextColor +import androidx.compose.animation.Crossfade +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import org.eclipse.jgit.api.Git +import org.eclipse.jgit.diff.DiffEntry +import org.eclipse.jgit.diff.DiffFormatter +import org.eclipse.jgit.lib.Repository +import org.eclipse.jgit.revwalk.RevCommit +import org.eclipse.jgit.revwalk.RevTree +import org.eclipse.jgit.revwalk.RevWalk +import org.eclipse.jgit.treewalk.AbstractTreeIterator +import org.eclipse.jgit.treewalk.CanonicalTreeParser +import java.io.ByteArrayOutputStream +import java.io.IOException + +@Composable +fun RepositorySelected(gitManager: GitManager, repository: Repository) { + var selectedRevCommit by remember { + mutableStateOf>?>(null) + } + + var diffSelected by remember { + mutableStateOf(null) + } + var uncommitedChangesSelected by remember { + mutableStateOf(false) + } + + val selectedIndexCommitLog = remember { mutableStateOf(-1) } + + Row { + Box( + modifier = Modifier + .weight(0.7f) + .fillMaxHeight() + ) { + Crossfade(targetState = diffSelected) { diffEntry -> + when (diffEntry) { + null -> { + Log( + gitManager = gitManager, + selectedIndex = selectedIndexCommitLog, + onRevCommitSelected = { commit -> + uncommitedChangesSelected = false + + val parent = if (commit.parentCount == 0) { + null + } else + commit.parents.first() + + val oldTreeParser = + prepareTreeParser(repository, parent!!) //TODO Will crash with first commit + val newTreeParser = prepareTreeParser(repository, commit) + Git(repository).use { git -> + val diffs = git.diff() + .setNewTree(newTreeParser) + .setOldTree(oldTreeParser) + .call() + + selectedRevCommit = commit to diffs + } + }, + onUncommitedChangesSelected = { + uncommitedChangesSelected = true + gitManager.updateStatus() + } + ) + } + else -> { + DiffView(gitManager = gitManager, diffEntry = diffEntry, onCloseDiffView = { diffSelected = null }) + } + } + } + + } + Box( + modifier = Modifier + .weight(0.3f) + .fillMaxHeight() + ) { + if (uncommitedChangesSelected) { + UncommitedChanges( + gitManager = gitManager, + onDiffEntrySelected = { diffEntry -> + println(diffEntry.filePath) + diffSelected = diffEntry + } + ) + } else { + selectedRevCommit?.let { + CommitChanges( + commitDiff = it, + onDiffSelected = { diffEntry -> + diffSelected = diffEntry + } + ) + } + } + } + } +} + +@Composable +fun DiffView(gitManager: GitManager, diffEntry: DiffEntry, onCloseDiffView: () -> Unit) { + val text = remember(diffEntry) { + gitManager.diffFormat(diffEntry) + } + + Column { + Button( + modifier = Modifier + .padding(vertical = 16.dp, horizontal = 16.dp) + .align(Alignment.End), + onClick = onCloseDiffView, + ) { + Text("Close") + } + val textLines = text.split("\n", "\r\n") + LazyColumn(modifier = Modifier.fillMaxSize()) { + items(textLines) { line -> + val color = if (line.startsWith("+")) { + Color(0xFF094f00) + } else if (line.startsWith("-")) { + Color(0xFF4f0000) + } else { + MaterialTheme.colors.primaryTextColor + } + SelectionContainer { + Text( + text = line, + color = color, + maxLines = 1, + fontFamily = FontFamily.Monospace, + ) + } + } + } + + } +} + + +@Throws(IOException::class) +fun prepareTreeParser(repository: Repository, commit: RevCommit): AbstractTreeIterator? { + // from the commit we can build the tree which allows us to construct the TreeParser + RevWalk(repository).use { walk -> + val tree: RevTree = walk.parseTree(commit.tree.id) + val treeParser = CanonicalTreeParser() + repository.newObjectReader().use { reader -> treeParser.reset(reader, tree.id) } + walk.dispose() + return treeParser + } +} + +@Composable +fun CommitChanges(commitDiff: Pair>, onDiffSelected: (DiffEntry) -> Unit) { + val commit = commitDiff.first + val diff = commitDiff.second + + Column( + modifier = Modifier + .fillMaxSize(), + ) { + Text(commit.fullMessage) + Text(commit.commitTime.toString()) + + CommitLogChanges(diff, onDiffSelected = onDiffSelected) + } +} + +@Composable +fun Log( + gitManager: GitManager, + onRevCommitSelected: (RevCommit) -> Unit, + onUncommitedChangesSelected: () -> Unit, + selectedIndex: MutableState = remember { mutableStateOf(-1) } +) { + + val logStatusState = gitManager.logStatus.collectAsState() + val logStatus = logStatusState.value + + val selectedUncommited = remember { mutableStateOf(false) } + + val log = if (logStatus is LogStatus.Loaded) { + logStatus.commits + } else + listOf() + + + LazyColumn( + modifier = Modifier + .background(backgroundColor) + .fillMaxSize() + ) { + if (gitManager.hasUncommitedChanges()) + item { + val textColor = if (selectedUncommited.value) { + MaterialTheme.colors.primary + } else + MaterialTheme.colors.primaryTextColor + + Column( + modifier = Modifier + .height(64.dp) + .fillMaxWidth() + .clickable { + selectedIndex.value = -1 + selectedUncommited.value = true + onUncommitedChangesSelected() + }, + verticalArrangement = Arrangement.Center, + ) { + Spacer(modifier = Modifier.weight(2f)) + + Text( + text = "Uncommited changes", + fontWeight = FontWeight.Bold, + modifier = Modifier.padding(start = 16.dp), + color = textColor, + ) + Text( + text = "You", + modifier = Modifier.padding(start = 16.dp), + color = MaterialTheme.colors.secondaryTextColor, + ) + Spacer(modifier = Modifier.weight(2f)) + + Divider() + } + } + + itemsIndexed(items = log) { index, item -> + val textColor = if (selectedIndex.value == index) { + MaterialTheme.colors.primary + } else + MaterialTheme.colors.primaryTextColor + + Column( + modifier = Modifier + .height(64.dp) + .fillMaxWidth() + .clickable { + selectedIndex.value = index + selectedUncommited.value = false + onRevCommitSelected(item) + }, + verticalArrangement = Arrangement.Center, + ) { + Spacer(modifier = Modifier.weight(2f)) + + Text( + text = item.shortMessage, + modifier = Modifier.padding(start = 16.dp), + color = textColor, + ) + Text( + text = item.authorIdent.name, + modifier = Modifier.padding(start = 16.dp), + color = MaterialTheme.colors.secondaryTextColor, + ) + Spacer(modifier = Modifier.weight(2f)) + + Divider() + } + } + } +} + +@Composable +fun CommitLogChanges(diffEntries: List, onDiffSelected: (DiffEntry) -> Unit) { + val selectedIndex = remember(diffEntries) { mutableStateOf(-1) } + + LazyColumn( + modifier = Modifier + .background(backgroundColor) + .fillMaxSize() + ) { + itemsIndexed(items = diffEntries) { index, diffEntry -> + val textColor = if (selectedIndex.value == index) { + MaterialTheme.colors.primary + } else + MaterialTheme.colors.primaryTextColor + + Column( + modifier = Modifier + .height(56.dp) + .fillMaxWidth() + .clickable { + selectedIndex.value = index + onDiffSelected(diffEntry) + }, + verticalArrangement = Arrangement.Center, + ) { + Spacer(modifier = Modifier.weight(2f)) + + + Row { + Icon( + modifier = Modifier + .padding(start = 16.dp) + .size(24.dp), + imageVector = diffEntry.icon, + contentDescription = null, + tint = MaterialTheme.colors.primary, + ) + + Text( + text = diffEntry.filePath, + modifier = Modifier.padding(horizontal = 16.dp), + color = textColor, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + + Spacer(modifier = Modifier.weight(2f)) + + Divider() + } + } + } +} diff --git a/src/main/kotlin/aeab13/github/com/UncommitedChanges.kt b/src/main/kotlin/aeab13/github/com/UncommitedChanges.kt new file mode 100644 index 0000000..6f02419 --- /dev/null +++ b/src/main/kotlin/aeab13/github/com/UncommitedChanges.kt @@ -0,0 +1,156 @@ +package aeab13.github.com + +import aeab13.github.com.extensions.filePath +import aeab13.github.com.extensions.icon +import aeab13.github.com.git.StageStatus +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.* +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Close +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import org.eclipse.jgit.diff.DiffEntry + +@Composable +fun UncommitedChanges( + gitManager: GitManager, + onDiffEntrySelected: (DiffEntry) -> Unit, +) { + val stageStatusState = gitManager.stageStatus.collectAsState() + val stageStatus = stageStatusState.value + + val (staged, unstaged) = if (stageStatus is StageStatus.Loaded) { + stageStatus.staged to stageStatus.unstaged + } else { + listOf() to listOf() // return 2 empty lists if still loading + } + + var commitMessage by remember { mutableStateOf("") } + + Column { + if (stageStatus is StageStatus.Loading) { + LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) + } + + Text("Staged", fontWeight = FontWeight.Bold) + + LazyColumn(modifier = Modifier.weight(5f)) { + itemsIndexed(staged) { index, diffEntry -> + FileEntry( + diffEntry = diffEntry, + icon = Icons.Default.Close, + onClick = { + onDiffEntrySelected(diffEntry) + }, + onButtonClick = { + gitManager.unstage(diffEntry) + } + ) + + if (index < staged.size - 1) { + Divider(modifier = Modifier.fillMaxWidth()) + } + } + } + Divider(modifier = Modifier.fillMaxWidth()) + + Text("Unstaged", fontWeight = FontWeight.Bold) + + LazyColumn(modifier = Modifier.weight(5f)) { + itemsIndexed(unstaged) { index, diffEntry -> + FileEntry( + diffEntry = diffEntry, + icon = Icons.Default.Add, + onClick = { + onDiffEntrySelected(diffEntry) + }, + onButtonClick = { + gitManager.stage(diffEntry) + } + ) + + if (index < unstaged.size - 1) { + Divider(modifier = Modifier.fillMaxWidth()) + } + } + } + + Column( + modifier = Modifier + .height(192.dp) + .fillMaxWidth() + ) { + TextField( + modifier = Modifier + .fillMaxWidth() + .weight(weight = 1f, fill = true), + value = commitMessage, + onValueChange = { commitMessage = it } + ) + + Button( + modifier = Modifier + .fillMaxWidth(), + onClick = { + gitManager.commit(commitMessage) + }, + enabled = commitMessage.isNotEmpty() + ) { + Text("Commit") + } + } + } +} + +@Composable +private fun FileEntry(diffEntry: DiffEntry, icon: ImageVector, onClick: () -> Unit, onButtonClick: () -> Unit) { + Row( + modifier = Modifier + .height(56.dp) + .fillMaxWidth() + .clickable(onClick = onClick), + verticalAlignment = Alignment.CenterVertically, + ) { + + Icon( + imageVector = diffEntry.icon, + contentDescription = null, + modifier = Modifier + .padding(horizontal = 16.dp) + .size(24.dp), + tint = MaterialTheme.colors.primary, + ) + + Text( + text = diffEntry.filePath, + modifier = Modifier.weight(1f, fill = true), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + + IconButton( + onClick = onButtonClick, + modifier = Modifier + .padding(horizontal = 16.dp) + .size(32.dp) + .border(1.dp, MaterialTheme.colors.primary, RoundedCornerShape(10.dp)) + ) { + Icon( + imageVector = icon, + contentDescription = null, + tint = MaterialTheme.colors.primary, + ) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/aeab13/github/com/extensions/DiffEntryExtensions.kt b/src/main/kotlin/aeab13/github/com/extensions/DiffEntryExtensions.kt new file mode 100644 index 0000000..d31ed7b --- /dev/null +++ b/src/main/kotlin/aeab13/github/com/extensions/DiffEntryExtensions.kt @@ -0,0 +1,29 @@ +package aeab13.github.com.extensions + +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.ui.graphics.vector.ImageVector +import org.eclipse.jgit.diff.DiffEntry + +val DiffEntry.filePath: String + get() { + return if (this.changeType == DiffEntry.ChangeType.DELETE) { + this.oldPath + } else + this.newPath + } + +val DiffEntry.icon: ImageVector + get() { + return when (this.changeType) { + DiffEntry.ChangeType.ADD -> Icons.Default.Add + DiffEntry.ChangeType.MODIFY -> Icons.Default.Edit + DiffEntry.ChangeType.DELETE -> Icons.Default.Delete + DiffEntry.ChangeType.COPY -> Icons.Default.Add + DiffEntry.ChangeType.RENAME -> Icons.Default.Refresh + else -> throw NotImplementedError("Unexpected ChangeType") + } + } \ No newline at end of file diff --git a/src/main/kotlin/aeab13/github/com/git/GitManager.kt b/src/main/kotlin/aeab13/github/com/git/GitManager.kt new file mode 100644 index 0000000..a5f75ef --- /dev/null +++ b/src/main/kotlin/aeab13/github/com/git/GitManager.kt @@ -0,0 +1,158 @@ +package aeab13.github.com + +import aeab13.github.com.git.LogManager +import aeab13.github.com.git.LogStatus +import aeab13.github.com.git.StageStatus +import aeab13.github.com.git.StatusManager +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.launch +import org.eclipse.jgit.api.Git +import org.eclipse.jgit.diff.DiffEntry +import org.eclipse.jgit.diff.DiffFormatter +import org.eclipse.jgit.dircache.DirCacheIterator +import org.eclipse.jgit.lib.Constants.HEAD +import org.eclipse.jgit.lib.ObjectId +import org.eclipse.jgit.lib.Repository +import org.eclipse.jgit.storage.file.FileRepositoryBuilder +import org.eclipse.jgit.treewalk.CanonicalTreeParser +import org.eclipse.jgit.treewalk.FileTreeIterator +import org.eclipse.jgit.treewalk.filter.TreeFilter +import java.io.ByteArrayOutputStream +import java.io.File + + +class GitManager { + private val preferences = GPreferences() + private val statusManager = StatusManager() + private val logManager = LogManager() + + private val managerScope = CoroutineScope(SupervisorJob()) + + private val _repositorySelectionStatus = MutableStateFlow(RepositorySelectionStatus.None) + val repositorySelectionStatus: StateFlow + get() = _repositorySelectionStatus + + private val _processing = MutableStateFlow(false) + val processing: StateFlow + get() = _processing + + val stageStatus: StateFlow + get() = statusManager.stageStatus + + val logStatus: StateFlow + get() = logManager.logStatus + + val latestDirectoryOpened: File? + get() = File(preferences.latestOpenedRepositoryPath).parentFile + + private var git: Git? = null + + var lastTimeStatusChanged: Long = 0 // TODO Add file watcher to the repository + private set + + val safeGit: Git + get() { + val git = this.git + if (git == null) { + _repositorySelectionStatus.value = RepositorySelectionStatus.None + throw CancellationException() + } else + return git + } + + init { + val latestOpenedRepositoryPath = preferences.latestOpenedRepositoryPath + if (latestOpenedRepositoryPath.isNotEmpty()) { + openRepository(File(latestOpenedRepositoryPath)) + } + } + + fun openRepository(directory: File) { + val gitDirectory = if (directory.name == ".git") { + directory + } else { + val gitDir = File(directory, ".git") + if (gitDir.exists() && gitDir.isDirectory) { + gitDir + } else + directory + + } + + val builder = FileRepositoryBuilder() + val repository: Repository = builder.setGitDir(gitDirectory) + .readEnvironment() // scan environment GIT_* variables + .findGitDir() // scan up the file system tree + .build() + + try { + repository.workTree // test if repository is valid + preferences.latestOpenedRepositoryPath = gitDirectory.path + _repositorySelectionStatus.value = RepositorySelectionStatus.Open(repository) + git = Git(repository) + + loadLog() + } catch (ex: Exception) { + ex.printStackTrace() + } + } + + fun loadLog() = managerScope.launch { + logManager.loadLog(safeGit) + } + + fun loadStatus() = managerScope.launch { + statusManager.loadStatus(safeGit) + } + + fun updateStatus() { + lastTimeStatusChanged = System.currentTimeMillis() + loadStatus() + } + + fun stage(diffEntry: DiffEntry) = managerScope.launch { + statusManager.stage(safeGit, diffEntry) + } + + fun unstage(diffEntry: DiffEntry) = managerScope.launch { + statusManager.unstage(safeGit, diffEntry) + } + + fun commit(message: String) = managerScope.launch { + statusManager.commit(safeGit, message) + logManager.loadLog(safeGit) + } + + fun hasUncommitedChanges(): Boolean = statusManager.hasUncommitedChanges(safeGit) + + fun diffFormat(diffEntry: DiffEntry): String { + val byteArrayOutputStream = ByteArrayOutputStream() + + DiffFormatter(byteArrayOutputStream).use { formatter -> + val repo = safeGit.repository + formatter.setRepository(repo) + + val oldTree = DirCacheIterator(repo.readDirCache()) + val newTree = FileTreeIterator(repo) + + println(diffEntry) + formatter.scan(oldTree, newTree) +// formatter.format(oldTree, newTree) + formatter.format(diffEntry) + formatter.flush() + } + + return byteArrayOutputStream.toString(Charsets.UTF_8) + } +} + + +sealed class RepositorySelectionStatus { + object None : RepositorySelectionStatus() + object Loading : RepositorySelectionStatus() + data class Open(val repository: Repository) : RepositorySelectionStatus() +} \ No newline at end of file diff --git a/src/main/kotlin/aeab13/github/com/git/LogManager.kt b/src/main/kotlin/aeab13/github/com/git/LogManager.kt new file mode 100644 index 0000000..0dd6f8a --- /dev/null +++ b/src/main/kotlin/aeab13/github/com/git/LogManager.kt @@ -0,0 +1,31 @@ +package aeab13.github.com.git + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.withContext +import org.eclipse.jgit.api.Git +import org.eclipse.jgit.revwalk.RevCommit + +class LogManager { + private val _logStatus = MutableStateFlow(LogStatus.Loaded(listOf())) + + val logStatus: StateFlow + get() = _logStatus + + suspend fun loadLog(git: Git) = withContext(Dispatchers.IO) { + _logStatus.value = LogStatus.Loading + + val log: Iterable = git.log().call() + + ensureActive() + + _logStatus.value = LogStatus.Loaded(log.toList()) + } +} + +sealed class LogStatus { + object Loading : LogStatus() + data class Loaded(val commits: List) : LogStatus() +} \ No newline at end of file diff --git a/src/main/kotlin/aeab13/github/com/git/StatusManager.kt b/src/main/kotlin/aeab13/github/com/git/StatusManager.kt new file mode 100644 index 0000000..343fd96 --- /dev/null +++ b/src/main/kotlin/aeab13/github/com/git/StatusManager.kt @@ -0,0 +1,72 @@ +package aeab13.github.com.git + +import aeab13.github.com.extensions.filePath +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.withContext +import org.eclipse.jgit.api.Git +import org.eclipse.jgit.diff.DiffEntry + +class StatusManager { + private val _stageStatus = MutableStateFlow(StageStatus.Loaded(listOf(), listOf())) + + val stageStatus: StateFlow + get() = _stageStatus + + fun hasUncommitedChanges(git: Git): Boolean { + return git + .status() + .call() + .hasUncommittedChanges() + } + + suspend fun loadStatus(git: Git) = withContext(Dispatchers.IO) { + _stageStatus.value = StageStatus.Loading + + val staged = git + .diff() + .setCached(true) + .call() + + ensureActive() + + val unstaged = git + .diff() + .call() + + ensureActive() + + _stageStatus.value = StageStatus.Loaded(staged, unstaged) + } + + suspend fun stage(git: Git, diffEntry: DiffEntry) = withContext(Dispatchers.IO) { + git.add() + .addFilepattern(diffEntry.filePath) + .call() + + loadStatus(git) + } + + suspend fun unstage(git: Git, diffEntry: DiffEntry) = withContext(Dispatchers.IO) { + git.reset() + .addPath(diffEntry.filePath) + .call() + + loadStatus(git) + } + + suspend fun commit(git: Git, message: String) = withContext(Dispatchers.IO) { + git.commit() + .setMessage(message) + .call() + + loadStatus(git) + } +} + +sealed class StageStatus { + object Loading : StageStatus() + data class Loaded(val staged: List, val unstaged: List) : StageStatus() +} \ No newline at end of file diff --git a/src/main/kotlin/aeab13/github/com/main.kt b/src/main/kotlin/aeab13/github/com/main.kt new file mode 100644 index 0000000..7173efd --- /dev/null +++ b/src/main/kotlin/aeab13/github/com/main.kt @@ -0,0 +1,115 @@ +import aeab13.github.com.GitManager +import aeab13.github.com.RepositorySelected +import aeab13.github.com.RepositorySelectionStatus +import aeab13.github.com.theme.GitnuroTheme +import androidx.compose.animation.Crossfade +import androidx.compose.foundation.layout.* +import androidx.compose.material.Button +import androidx.compose.material.Icon +import androidx.compose.material.OutlinedButton +import androidx.compose.material.Text +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Window +import androidx.compose.ui.window.application +import javax.swing.JFileChooser + + +@OptIn(ExperimentalComposeUiApi::class) +fun main() = application { + var isOpen by remember { mutableStateOf(true) } + val gitManager = GitManager() + if (isOpen) { + Window( + title = "Gitnuro", + onCloseRequest = { + isOpen = false + }, + + ) { + GitnuroTheme { + Gitnuro(gitManager) + } + } + } +} + +@Composable +fun Gitnuro(gitManager: GitManager) { + val repositorySelectionStatus by gitManager.repositorySelectionStatus.collectAsState() + + Column { + GMenu( + onRepositoryOpen = { + val latestDirectoryOpened = gitManager.latestDirectoryOpened + + val f = if(latestDirectoryOpened == null) + JFileChooser() + else + JFileChooser(latestDirectoryOpened) + + f.fileSelectionMode = JFileChooser.DIRECTORIES_ONLY + f.showSaveDialog(null) + + if (f.selectedFile != null) + gitManager.openRepository(f.selectedFile) + } + ) + + Crossfade(targetState = repositorySelectionStatus) { + + @Suppress("UnnecessaryVariable") // Don't inline it because smart cast won't work + when (val status = repositorySelectionStatus) { + RepositorySelectionStatus.None -> { + NoneRepository() + } + RepositorySelectionStatus.Loading -> { + LoadingRepository() + } + is RepositorySelectionStatus.Open -> { + RepositorySelected(gitManager = gitManager, repository = status.repository) + } + } + } + } + + +} + +@Composable +fun LoadingRepository() { + Box { } + +} + +@Composable +fun NoneRepository() { + Box( + contentAlignment = Alignment.Center + ) { + Text("Open a repository to start using Gitnuro") + } +} + +@Composable +fun GMenu(onRepositoryOpen: () -> Unit) { + Row( + modifier = Modifier + .padding(vertical = 16.dp) + .fillMaxWidth(), + horizontalArrangement = Arrangement.Center, + ) { + OutlinedButton( +// modifier = Modifier.size(64.dp), + onClick = onRepositoryOpen + ) { + Text("Open") +// Icon(Icons.Default.Add, contentDescription = "Open repository") + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/aeab13/github/com/theme/Color.kt b/src/main/kotlin/aeab13/github/com/theme/Color.kt new file mode 100644 index 0000000..4d38d2d --- /dev/null +++ b/src/main/kotlin/aeab13/github/com/theme/Color.kt @@ -0,0 +1,17 @@ +package aeab13.github.com.theme + +import androidx.compose.ui.graphics.Color + +val primaryLight = Color(0xFF9FD1FF) +val primary = Color(0xFF0070D8) +val primaryDark = Color(0xFF014F97) +val secondary = Color(0xFFAB02E9) +val mainText = Color(0xFF202124) +val mainTextDark = Color(0xFFFFFFFF) +val secondaryText = Color(0xFF8F8F8F) +val secondaryTextDark = Color(0xFFCCCBCB) +val errorColor = Color(0xFFFA4B4B) +val primaryGrayLight = Color(0xFF464646) +val accentGrayLight = Color(0xFFCCCCCC) + +val backgroundColor = Color(0xFFf9f9f9) \ No newline at end of file diff --git a/src/main/kotlin/aeab13/github/com/theme/Theme.kt b/src/main/kotlin/aeab13/github/com/theme/Theme.kt new file mode 100644 index 0000000..a1b96e1 --- /dev/null +++ b/src/main/kotlin/aeab13/github/com/theme/Theme.kt @@ -0,0 +1,57 @@ +package aeab13.github.com.theme + +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material.* +import androidx.compose.runtime.Composable +import androidx.compose.ui.graphics.Color + +private val DarkColorPalette = darkColors( + primary = primaryLight, + primaryVariant = primaryDark, + secondary = secondary +) + +private val LightColorPalette = lightColors( + primary = primary, + primaryVariant = primaryDark, + secondary = secondary, + background = backgroundColor, + error = errorColor + /* Other default colors to override + + */ +) + +@Composable +fun GitnuroTheme(darkTheme: Boolean = false, content: @Composable() () -> Unit) { + val colors = if (darkTheme) { + DarkColorPalette + } else { + LightColorPalette + } + + MaterialTheme( + colors = colors, + content = content, + ) +} + +@get:Composable +val Colors.primaryTextColor: Color + get() = if(isLight) mainText else mainTextDark + +@get:Composable +val Colors.secondaryTextColor: Color + get() = if(isLight) secondaryText else secondaryTextDark + +@get:Composable +val Colors.accent: Color + get() = primaryLight + +@get:Composable +val Colors.primaryGray: Color + get() = primaryGrayLight + +@get:Composable +val Colors.accentGray: Color + get() = accentGrayLight