File watcher now also watched new added directories

This commit is contained in:
Abdelilah El Aissaoui 2022-03-03 20:00:34 +01:00
parent aae80445f9
commit 33eb0f3c8a
2 changed files with 30 additions and 2 deletions

View File

@ -1,9 +1,12 @@
package app.git
import app.extensions.systemSeparator
import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException
import java.nio.file.*
import java.nio.file.StandardWatchEventKinds.*
@ -47,7 +50,7 @@ class FileChangesWatcher @Inject constructor() {
var key: WatchKey
while (watchService.take().also { key = it } != null) {
key.pollEvents()
val events = key.pollEvents()
println("Polled events on dir ${keys[key]}")
@ -59,6 +62,27 @@ class FileChangesWatcher @Inject constructor() {
_changesNotifier.emit(hasGitDirectoryChanged)
// Check if new directories have been added to add them to the watchService
launch(Dispatchers.IO) {
for (event in events) {
if (event.kind() == ENTRY_CREATE) {
try {
val eventFile = File(dir.toAbsolutePath().toString() + systemSeparator + event.context())
if (eventFile.isDirectory) {
val eventPath = eventFile.toPath()
println("New directory $eventFile detected, adding it to watchService")
val watchKey =
eventPath.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY)
keys[watchKey] = eventPath
}
} catch (ex: Exception) {
ex.printStackTrace()
}
}
}
}
key.reset()
}
}

View File

@ -152,6 +152,8 @@ class TabViewModel @Inject constructor(
launch {
fileChangesWatcher.changesNotifier.collect { latestUpdateChangedGitDir ->
if (!tabState.operationRunning) { // Only update if there isn't any process running
println("Detected changes in the repository's directory")
if(latestUpdateChangedGitDir) {
hasGitDirChanged = true
}
@ -181,6 +183,8 @@ class TabViewModel @Inject constructor(
}
lastNotify = currentTimeMillis
} else {
println("Ignoring changed occurred during operation running...")
}
}
}