Snapshot of the Umamo working tree as it is
Uploaded as-is from /home/litruv/dev/vtsmaker/umamo on 2026-11-03. 1347 files. Includes the uncommitted work in progress in :edit, :runtime, and :ui, and the untracked files under module/edit/src/jvmAndroidMain/. History is not carried over. The source repo is https://github.com/umamoorg/umamo.
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
// :storage — multiplatform app-file foundation: per-OS config/data directories, file IO (okio), and a
|
||||
// native open/save dialog contract. The low-level base :settings (and later the editor UI) build on.
|
||||
// :storage — マルチプラットフォームのアプリ保存基盤:OS 別の設定/データ場所、ファイル IO(okio)、ファイルダイアログ契約。
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.kotlinMultiplatform)
|
||||
alias(libs.plugins.androidKmpLibrary)
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvmToolchain(21)
|
||||
|
||||
jvm()
|
||||
|
||||
android {
|
||||
namespace = "org.umamo.storage"
|
||||
compileSdk = libs.versions.android.compileSdk.get().toInt()
|
||||
minSdk = libs.versions.android.minSdk.get().toInt()
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
commonMain {
|
||||
dependencies {
|
||||
// `api` (not `implementation`): okio's `Path`/`FileSystem` appear in AppStorage's public
|
||||
// surface, so consumers (:settings, apps) see them transitively.
|
||||
api(libs.okio)
|
||||
// `api` again: FileKit's `PlatformFile` is the FilePicker contract's return type, and the
|
||||
// apps call `FileKit.init`, so both must reach consumers transitively. Pulls filekit-core.
|
||||
api(libs.filekitDialogs)
|
||||
// `api` because UmamoLog's retained-log buffer exposes a StateFlow in its public surface, so
|
||||
// consumers (the UI's Logs panel) see kotlinx-coroutines transitively - same rule as okio/FileKit.
|
||||
api(libs.kotlinxCoroutinesCore)
|
||||
}
|
||||
}
|
||||
commonTest {
|
||||
dependencies {
|
||||
implementation(kotlin("test"))
|
||||
// okio's in-memory FileSystem, so OkioAppStorage's tests run with no real disk.
|
||||
implementation(libs.okio.fakefilesystem)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package org.umamo.storage
|
||||
|
||||
import android.content.Context
|
||||
import okio.FileSystem
|
||||
import okio.Path.Companion.toPath
|
||||
|
||||
/**
|
||||
* Builds the Android [AppStorage] from a [Context]: app-private internal storage (`filesDir`), split into
|
||||
* `config/` and `data/` subdirectories. Android sandboxes each app, so there is no XDG-style global split -
|
||||
* [applicationName] is accepted only for API symmetry with `desktopAppStorage`.
|
||||
*
|
||||
* The [FilePicker] is not platform-specific: [FileKitFilePicker] (commonMain) drives the Storage
|
||||
* Access Framework through FileKit. The Android app only needs to call `FileKit.init(activity)` once in its
|
||||
* Activity (it owns the result registry); no separate Android picker implementation is required.
|
||||
*
|
||||
* @param Context context The application context.
|
||||
* @param String applicationName Unused on Android (sandboxed); for symmetry with desktop.
|
||||
* @return AppStorage The Android storage.
|
||||
*/
|
||||
@Suppress("UNUSED_PARAMETER")
|
||||
fun androidAppStorage(context: Context, applicationName: String = "umamo"): AppStorage {
|
||||
val base = context.filesDir.absolutePath.toPath()
|
||||
return OkioAppStorage(FileSystem.SYSTEM, configDirectory = base / "config", dataDirectory = base / "data")
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package org.umamo.storage
|
||||
|
||||
import android.net.Uri
|
||||
import io.github.vinceglb.filekit.PlatformFile
|
||||
import io.github.vinceglb.filekit.write
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Android actual: a Storage Access Framework pick stores a `content://` URI string (there is no real
|
||||
* filesystem path behind it), so it routes back through a Uri; anything else is a plain file path.
|
||||
* Reopening a content URI across process restarts may still be refused until persistable URI
|
||||
* permissions are taken — callers treat a failed open as a soft miss.
|
||||
*
|
||||
* @param String path The stored path or URI string.
|
||||
* @return PlatformFile The reconstructed file handle.
|
||||
*/
|
||||
actual fun platformFileFromSavedPath(path: String): PlatformFile =
|
||||
if (path.startsWith("content://")) {
|
||||
PlatformFile(Uri.parse(path))
|
||||
} else {
|
||||
PlatformFile(File(path))
|
||||
}
|
||||
|
||||
/**
|
||||
* Android actual: a Storage Access Framework uri has no directory to stage a temporary in and cannot be
|
||||
* renamed over, so the bytes are written in place - complete in memory before the write begins.
|
||||
*
|
||||
* @param ByteArray bytes The complete contents.
|
||||
*/
|
||||
actual suspend fun PlatformFile.writeReplacing(bytes: ByteArray) {
|
||||
write(bytes)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package org.umamo.storage
|
||||
|
||||
import okio.FileSystem
|
||||
import okio.Path
|
||||
|
||||
/**
|
||||
* The app's file foundation: where its config/data live (per-OS) and read/write over those locations.
|
||||
* The platform factories (`desktopAppStorage`, `androidAppStorage`) resolve the directories; everything
|
||||
* else is shared. Backed by okio so one API covers desktop and Android - Kotlin's stdlib has no common
|
||||
* `File` type, and `java.io.File` is JVM-only.
|
||||
*/
|
||||
interface AppStorage {
|
||||
/** Per-user config directory (small JSON: settings, keymaps, layout). Parents created on write. */
|
||||
val configDirectory: Path
|
||||
|
||||
/** Per-user data directory (larger app data, caches). */
|
||||
val dataDirectory: Path
|
||||
|
||||
/**
|
||||
* Reads [path] as UTF-8 text.
|
||||
*
|
||||
* @param Path path The file to read.
|
||||
* @return String? The contents, or null if the file does not exist.
|
||||
*/
|
||||
fun readText(path: Path): String?
|
||||
|
||||
/**
|
||||
* Writes [text] to [path] as UTF-8, creating parent directories as needed.
|
||||
*
|
||||
* @param Path path The destination file.
|
||||
* @param String text The contents to write.
|
||||
*/
|
||||
fun writeText(path: Path, text: String)
|
||||
|
||||
/**
|
||||
* @param Path path The path to test.
|
||||
* @return Boolean Whether [path] exists.
|
||||
*/
|
||||
fun exists(path: Path): Boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* okio-backed [AppStorage]: directories come from the platform factory; IO goes through the supplied
|
||||
* [fileSystem] - the real one on a device, or okio's `FakeFileSystem` in tests (so settings logic is
|
||||
* testable with no real disk).
|
||||
*
|
||||
* @property FileSystem fileSystem The filesystem to read/write through.
|
||||
* @property Path configDirectory Resolved config directory.
|
||||
* @property Path dataDirectory Resolved data directory.
|
||||
*/
|
||||
class OkioAppStorage(
|
||||
private val fileSystem: FileSystem,
|
||||
override val configDirectory: Path,
|
||||
override val dataDirectory: Path,
|
||||
) : AppStorage {
|
||||
override fun readText(path: Path): String? =
|
||||
if (fileSystem.exists(path)) {
|
||||
fileSystem.read(path) { readUtf8() }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
override fun writeText(path: Path, text: String) {
|
||||
path.parent?.let { fileSystem.createDirectories(it) }
|
||||
fileSystem.write(path) { writeUtf8(text) }
|
||||
}
|
||||
|
||||
override fun exists(path: Path): Boolean = fileSystem.exists(path)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package org.umamo.storage
|
||||
|
||||
import okio.FileSystem
|
||||
import okio.HashingSource
|
||||
import okio.Path
|
||||
import okio.blackholeSink
|
||||
import okio.buffer
|
||||
|
||||
/**
|
||||
* The content hash of the file at [path], streamed rather than loaded - an artwork file can run to
|
||||
* hundreds of megabytes, and the watcher hashes it on every settled save. The same digest as
|
||||
* :format's contentHashOf (SHA-256 as lowercase hex), which is where the algorithm is named.
|
||||
*
|
||||
* @param FileSystem fileSystem The file system to read through.
|
||||
* @param Path path The file.
|
||||
* @return String? The digest as lowercase hex, or null when the file cannot be read (missing, being
|
||||
* written, or refused).
|
||||
*/
|
||||
fun contentHashOfFile(fileSystem: FileSystem, path: Path): String? =
|
||||
runCatching {
|
||||
HashingSource.sha256(fileSystem.source(path)).use { hashing ->
|
||||
hashing.buffer().use { source -> source.readAll(blackholeSink()) }
|
||||
hashing.hash.hex()
|
||||
}
|
||||
}.getOrNull()
|
||||
@@ -0,0 +1,38 @@
|
||||
package org.umamo.storage
|
||||
|
||||
import io.github.vinceglb.filekit.FileKit
|
||||
import io.github.vinceglb.filekit.PlatformFile
|
||||
import io.github.vinceglb.filekit.dialogs.FileKitType
|
||||
import io.github.vinceglb.filekit.dialogs.openFilePicker
|
||||
import io.github.vinceglb.filekit.dialogs.openFileSaver
|
||||
|
||||
/**
|
||||
* The [FilePicker] over FileKit's native dialogs. FileKit already abstracts each platform's picker (Win32 /
|
||||
* Cocoa / GTK on desktop, Storage Access Framework on Android), so this single commonMain implementation
|
||||
* serves every platform, including Android once the Activity calls `FileKit.init`.
|
||||
*
|
||||
* `FileKit.init` must run once at startup before any call here (desktop: in `main`; Android: in the Activity).
|
||||
*/
|
||||
class FileKitFilePicker : FilePicker {
|
||||
override suspend fun openFile(extensions: List<String>): PlatformFile? =
|
||||
FileKit.openFilePicker(type = fileKitType(extensions))
|
||||
|
||||
override suspend fun saveFile(suggestedName: String, extension: String): PlatformFile? =
|
||||
// `defaultExtension` is the hint FileKit appends to the saved name (the `extension` arg is deprecated).
|
||||
FileKit.openFileSaver(suggestedName = suggestedName, defaultExtension = extension)
|
||||
|
||||
/**
|
||||
* Maps our extension allow-list to a FileKit type filter: a specific [FileKitType.File] when extensions
|
||||
* are given, or the unfiltered "any file" type when the list is empty (an empty filter would otherwise
|
||||
* mean "allow nothing").
|
||||
*
|
||||
* @param List<String> extensions Allowed extensions without the dot; empty = any.
|
||||
* @return FileKitType The matching FileKit type filter.
|
||||
*/
|
||||
private fun fileKitType(extensions: List<String>): FileKitType =
|
||||
if (extensions.isEmpty()) {
|
||||
FileKitType.File()
|
||||
} else {
|
||||
FileKitType.File(extensions)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package org.umamo.storage
|
||||
|
||||
import io.github.vinceglb.filekit.PlatformFile
|
||||
|
||||
/**
|
||||
* A native open/save file dialog - a platform service (not Compose UI), so it belongs in :storage with the
|
||||
* other file concerns. Backed by FileKit ([org.umamo.storage.FileKitFilePicker]), which already speaks each
|
||||
* platform's native dialog, so the single implementation covers desktop and Android alike.
|
||||
*
|
||||
* Returns a FileKit [PlatformFile] rather than an okio `Path`: on Android the Storage Access Framework hands
|
||||
* back a `content://` URI that has no real filesystem path, which a `Path` cannot represent - `PlatformFile`
|
||||
* abstracts that and exposes read/write directly. Suspending so the (potentially async) native flow is
|
||||
* awaited the same way on every platform.
|
||||
*/
|
||||
interface FilePicker {
|
||||
/**
|
||||
* Prompts the user to choose an existing file to open.
|
||||
*
|
||||
* @param List<String> extensions Allowed extensions without the dot (e.g. `["cmo3", "psd"]`); empty = any.
|
||||
* @return PlatformFile? The chosen file, or null if cancelled.
|
||||
*/
|
||||
suspend fun openFile(extensions: List<String>): PlatformFile?
|
||||
|
||||
/**
|
||||
* Prompts the user to choose a destination to save to.
|
||||
*
|
||||
* @param String suggestedName Pre-filled file name without extension (e.g. "MyModel").
|
||||
* @param String extension Target extension without the dot (e.g. "cmo3").
|
||||
* @return PlatformFile? The chosen destination, or null if cancelled.
|
||||
*/
|
||||
suspend fun saveFile(suggestedName: String, extension: String): PlatformFile?
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package org.umamo.storage
|
||||
|
||||
import okio.FileSystem
|
||||
import okio.IOException
|
||||
import okio.Path
|
||||
import kotlin.random.Random
|
||||
|
||||
/**
|
||||
* Writes [bytes] over [target] without ever leaving a half-written file at [target].
|
||||
*
|
||||
* The bytes go to a temporary sibling in the target's directory first, and only a complete temporary is
|
||||
* moved over the target - one rename, which the file system makes atomic. If anything fails before the
|
||||
* move, the target is untouched and the temporary is removed; if the move itself fails, the target is
|
||||
* still whatever it was. A sibling rather than a system temp directory because a rename is atomic only
|
||||
* within one file system.
|
||||
*
|
||||
* A process killed mid-write (a crash, a power cut, a forced quit) cannot run that cleanup, and a
|
||||
* document-sized temporary is left beside the target. The next save of the same file sweeps any such
|
||||
* leftover before writing its own, so it costs one save at most; the prefix is this function's own, so
|
||||
* nothing else is ever touched.
|
||||
*
|
||||
* The file system is a parameter so the rule tests against okio's in-memory file system; the platform
|
||||
* seam hands it the real one.
|
||||
*
|
||||
* @param FileSystem fileSystem The file system holding [target].
|
||||
* @param Path target The file to replace, or create.
|
||||
* @param ByteArray bytes The complete contents to write.
|
||||
* @throws IOException When the temporary cannot be written or the move fails.
|
||||
*/
|
||||
internal fun writeReplacing(fileSystem: FileSystem, target: Path, bytes: ByteArray) {
|
||||
val directory = target.parent ?: throw IOException("$target has no directory to write a temporary in")
|
||||
val temporaryPrefix = ".${target.name}.tmp-"
|
||||
for (sibling in fileSystem.listOrNull(directory).orEmpty()) {
|
||||
if (sibling.name.startsWith(temporaryPrefix)) {
|
||||
try {
|
||||
fileSystem.delete(sibling, mustExist = false)
|
||||
} catch (_: IOException) {
|
||||
// A leftover that will not delete is not a reason to fail the save that found it.
|
||||
}
|
||||
}
|
||||
}
|
||||
val temporary = directory / "$temporaryPrefix${Random.nextLong().toULong().toString(16)}"
|
||||
try {
|
||||
fileSystem.write(temporary) { write(bytes) }
|
||||
fileSystem.atomicMove(temporary, target)
|
||||
} catch (failure: IOException) {
|
||||
fileSystem.delete(temporary, mustExist = false)
|
||||
throw failure
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package org.umamo.storage
|
||||
|
||||
import io.github.vinceglb.filekit.PlatformFile
|
||||
|
||||
/**
|
||||
* Rebuilds a [PlatformFile] from a path string previously stored from `PlatformFile.absolutePath()`
|
||||
* (e.g. the recent-files list). FileKit's `PlatformFile(path)` constructors are per-platform API —
|
||||
* not visible from shared code — and Android must additionally route SAF `content://` strings back
|
||||
* through a Uri, hence the seam.
|
||||
*
|
||||
* 保存済みパス文字列から PlatformFile を再構築する継ぎ目。Android は content:// を Uri 経由で戻す。
|
||||
*
|
||||
* @param String path The stored path or URI string.
|
||||
* @return PlatformFile The reconstructed file handle.
|
||||
*/
|
||||
expect fun platformFileFromSavedPath(path: String): PlatformFile
|
||||
|
||||
/**
|
||||
* Writes [bytes] as this file's complete contents, never leaving a half-written file where it can be
|
||||
* avoided.
|
||||
*
|
||||
* A real path takes the temporary-then-atomic-move route ([writeReplacing]), so the file on disk is either
|
||||
* the old one or the new one. An Android `content://` uri cannot be renamed over, so it is written in
|
||||
* place, and only once the bytes are complete in memory - the one case where a failure mid-write can
|
||||
* leave a partial file.
|
||||
*
|
||||
* @param ByteArray bytes The complete contents.
|
||||
* @throws IOException When the write fails; the caller reports it and marks nothing saved.
|
||||
*/
|
||||
expect suspend fun PlatformFile.writeReplacing(bytes: ByteArray)
|
||||
@@ -0,0 +1,114 @@
|
||||
package org.umamo.storage
|
||||
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
|
||||
/**
|
||||
* The severity of a logged line. Nominal today (the stdout transport prints every level identically),
|
||||
* but retained on each entry so an in-app console can color Warn and Error distinctly.
|
||||
*/
|
||||
enum class LogLevel {
|
||||
Info,
|
||||
Warn,
|
||||
Error,
|
||||
}
|
||||
|
||||
/**
|
||||
* One retained log line: its severity and its already-composed message (for an Error with a cause the
|
||||
* message is the same "message: cause" text the terminal prints, so nothing is lost off the console).
|
||||
*
|
||||
* @property LogLevel level The severity the call site named.
|
||||
* @property String message The final, fully-composed message text.
|
||||
*/
|
||||
data class LogEntry(val level: LogLevel, val message: String)
|
||||
|
||||
/**
|
||||
* The app's minimal diagnostic log. A seam, not a framework: call sites name a severity instead of
|
||||
* hardcoding the transport, so routing (a file via AppStorage, logcat, an in-app console) can change
|
||||
* in one place later. The transport today is stdout with the established "[Umamo]" prefix, plus a
|
||||
* bounded in-memory buffer ([entries]) the editor's Logs panel collects - so a user who launched
|
||||
* without a terminal can still read the output.
|
||||
*
|
||||
* Lives in :storage because it is the bottom-most shared module every target already depends on;
|
||||
* logging is platform plumbing in the same sense as config directories and file IO.
|
||||
*
|
||||
* This is for diagnostics only. Anything the user must see goes through a UI surface (a notice or
|
||||
* a dialog), never only through this log.
|
||||
*/
|
||||
object UmamoLog {
|
||||
/**
|
||||
* The retained log lines, oldest first, capped at [MAX_LOG_ENTRIES] (oldest dropped past the cap).
|
||||
* A StateFlow so the Logs panel recomposes as lines arrive; writes are lock-free and thread-safe,
|
||||
* so any thread (the GL thread, a coroutine dispatcher) may log.
|
||||
*/
|
||||
val entries: StateFlow<List<LogEntry>>
|
||||
get() = mutableEntries.asStateFlow()
|
||||
|
||||
private val mutableEntries = MutableStateFlow<List<LogEntry>>(emptyList())
|
||||
|
||||
/**
|
||||
* Logs a routine status line (startup info, a completed save/export).
|
||||
*
|
||||
* @param String message The already-formatted message.
|
||||
*/
|
||||
fun info(message: String) {
|
||||
println("[Umamo] $message")
|
||||
record(LogLevel.Info, message)
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs an unexpected-but-recovered condition (a rejected file, a refused platform call).
|
||||
*
|
||||
* @param String message The already-formatted message.
|
||||
*/
|
||||
fun warn(message: String) {
|
||||
println("[Umamo] $message")
|
||||
record(LogLevel.Warn, message)
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs a failure worth investigating, with the throwable's message appended when present.
|
||||
*
|
||||
* @param String message The already-formatted message.
|
||||
* @param Throwable? cause The originating failure, or null when there is none.
|
||||
*/
|
||||
fun error(message: String, cause: Throwable? = null) {
|
||||
// Compose once so the terminal and the retained buffer show the cause identically.
|
||||
val composed =
|
||||
if (cause != null) {
|
||||
"$message: ${cause.message}"
|
||||
} else {
|
||||
message
|
||||
}
|
||||
println("[Umamo] $composed")
|
||||
record(LogLevel.Error, composed)
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends one entry to the retained buffer, dropping the oldest lines past the cap. update{} is a
|
||||
* lock-free compare-and-set loop (safe from any thread) and its transform is pure, so a retry under
|
||||
* contention is harmless.
|
||||
*
|
||||
* @param LogLevel level The entry's severity.
|
||||
* @param String message The fully-composed message text.
|
||||
*/
|
||||
private fun record(level: LogLevel, message: String) {
|
||||
mutableEntries.update { existing -> (existing + LogEntry(level, message)).takeLast(MAX_LOG_ENTRIES) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Empties the retained buffer. Test-only: [UmamoLog] is an app-lifetime singleton, so tests reset it
|
||||
* between cases to avoid order coupling. Not a user-facing clear.
|
||||
*/
|
||||
internal fun clear() {
|
||||
mutableEntries.value = emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The most recent log lines kept in memory. A whole session's diagnostics fit comfortably; the log is
|
||||
* low-traffic (startup, GL init, file-IO outcomes), so this is generous headroom, not a tight ring.
|
||||
*/
|
||||
private const val MAX_LOG_ENTRIES = 2000
|
||||
@@ -0,0 +1,20 @@
|
||||
package org.umamo.storage
|
||||
|
||||
import okio.Path.Companion.toPath
|
||||
import okio.fakefilesystem.FakeFileSystem
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNull
|
||||
|
||||
/** A file hashes to the same digest as its bytes, and a missing one to null. */
|
||||
class ContentHashTest {
|
||||
@Test
|
||||
fun aFileHashesToTheSameDigestAsItsBytesAndAMissingOneToNull() {
|
||||
val fileSystem = FakeFileSystem()
|
||||
val path = "/art/a.psd".toPath()
|
||||
fileSystem.createDirectories(path.parent!!)
|
||||
fileSystem.write(path) { write("abc".encodeToByteArray()) }
|
||||
assertEquals("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", contentHashOfFile(fileSystem, path), "the published SHA-256 vector for abc")
|
||||
assertNull(contentHashOfFile(fileSystem, "/art/missing.psd".toPath()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package org.umamo.storage
|
||||
|
||||
import okio.Path.Companion.toPath
|
||||
import okio.fakefilesystem.FakeFileSystem
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
/**
|
||||
* Unit-tests [OkioAppStorage] over okio's in-memory FakeFileSystem - the persistence foundation
|
||||
* settings/keymaps/layout all write through, exercised with no real disk.
|
||||
*/
|
||||
class OkioAppStorageTest {
|
||||
private fun storage(fileSystem: FakeFileSystem): OkioAppStorage =
|
||||
OkioAppStorage(
|
||||
fileSystem = fileSystem,
|
||||
configDirectory = "/config".toPath(),
|
||||
dataDirectory = "/data".toPath(),
|
||||
)
|
||||
|
||||
@Test
|
||||
fun writeThenReadRoundTripsUtf8Text() {
|
||||
val storage = storage(FakeFileSystem())
|
||||
val path = storage.configDirectory / "settings.json"
|
||||
|
||||
storage.writeText(path, "{\"theme\":\"dark\", \"言語\":\"日本語\"}")
|
||||
|
||||
assertEquals("{\"theme\":\"dark\", \"言語\":\"日本語\"}", storage.readText(path))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun writeCreatesMissingParentDirectories() {
|
||||
val fileSystem = FakeFileSystem()
|
||||
val storage = storage(fileSystem)
|
||||
val nested = storage.configDirectory / "keymaps" / "presets" / "custom.json"
|
||||
|
||||
storage.writeText(nested, "{}")
|
||||
|
||||
assertTrue(fileSystem.exists(storage.configDirectory / "keymaps" / "presets"))
|
||||
assertEquals("{}", storage.readText(nested))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun readReturnsNullForAMissingFile() {
|
||||
val storage = storage(FakeFileSystem())
|
||||
|
||||
assertNull(storage.readText(storage.configDirectory / "absent.json"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun existsTracksTheWrittenFile() {
|
||||
val storage = storage(FakeFileSystem())
|
||||
val path = storage.dataDirectory / "recent.json"
|
||||
|
||||
assertFalse(storage.exists(path))
|
||||
storage.writeText(path, "[]")
|
||||
assertTrue(storage.exists(path))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rewritingAFileReplacesItsContents() {
|
||||
val storage = storage(FakeFileSystem())
|
||||
val path = storage.configDirectory / "settings.json"
|
||||
|
||||
storage.writeText(path, "first")
|
||||
storage.writeText(path, "second")
|
||||
|
||||
assertEquals("second", storage.readText(path))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package org.umamo.storage
|
||||
|
||||
import kotlin.test.BeforeTest
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
/**
|
||||
* Unit-tests [UmamoLog]'s retained buffer - the in-memory log the editor's Logs panel reads. Resets the
|
||||
* buffer before each case because UmamoLog is an app-lifetime singleton whose state would otherwise leak
|
||||
* between tests.
|
||||
*/
|
||||
class UmamoLogTest {
|
||||
@BeforeTest
|
||||
fun reset() {
|
||||
UmamoLog.clear()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun infoRecordsAnInfoEntry() {
|
||||
UmamoLog.info("started")
|
||||
|
||||
val entry = UmamoLog.entries.value.single()
|
||||
assertEquals(LogLevel.Info, entry.level)
|
||||
assertEquals("started", entry.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun warnRecordsAWarnEntry() {
|
||||
UmamoLog.warn("odd")
|
||||
|
||||
assertEquals(LogLevel.Warn, UmamoLog.entries.value.single().level)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun errorWithCauseRecordsTheComposedMessage() {
|
||||
UmamoLog.error("could not open", RuntimeException("missing"))
|
||||
|
||||
val entry = UmamoLog.entries.value.single()
|
||||
assertEquals(LogLevel.Error, entry.level)
|
||||
// The cause is folded into the message exactly as the terminal prints it, so the panel keeps it.
|
||||
assertEquals("could not open: missing", entry.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun errorWithoutCauseRecordsTheBareMessage() {
|
||||
UmamoLog.error("plain failure")
|
||||
|
||||
assertEquals("plain failure", UmamoLog.entries.value.single().message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bufferCapsAtTheMaximumDroppingOldest() {
|
||||
// Append past the documented cap (MAX_LOG_ENTRIES = 2000); the oldest lines fall off the front.
|
||||
val cap = 2000
|
||||
val overflow = 50
|
||||
for (lineIndex in 0 until cap + overflow) {
|
||||
UmamoLog.info("line $lineIndex")
|
||||
}
|
||||
|
||||
val entries = UmamoLog.entries.value
|
||||
assertEquals(cap, entries.size)
|
||||
// The first `overflow` lines were dropped: the window now starts at `overflow` and ends at the last.
|
||||
assertEquals("line $overflow", entries.first().message)
|
||||
assertEquals("line ${cap + overflow - 1}", entries.last().message)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package org.umamo.storage
|
||||
|
||||
import okio.Buffer
|
||||
import okio.ForwardingFileSystem
|
||||
import okio.ForwardingSink
|
||||
import okio.IOException
|
||||
import okio.Path
|
||||
import okio.Path.Companion.toPath
|
||||
import okio.Sink
|
||||
import okio.fakefilesystem.FakeFileSystem
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertContentEquals
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFailsWith
|
||||
import kotlin.test.assertFalse
|
||||
|
||||
/**
|
||||
* Pins the one promise a save makes about the file on disk: it is either the old file or the new one,
|
||||
* never something in between, and no temporary is left behind either way.
|
||||
*/
|
||||
class WriteReplacingTest {
|
||||
private val directory = "/documents".toPath()
|
||||
|
||||
/**
|
||||
* A file system whose [directory] exists.
|
||||
*
|
||||
* @return FakeFileSystem The file system.
|
||||
*/
|
||||
private fun fileSystem(): FakeFileSystem = FakeFileSystem().also { fileSystem -> fileSystem.createDirectories(directory) }
|
||||
|
||||
@Test
|
||||
fun replacesAnExistingFileAndLeavesNoTemporary() {
|
||||
val fileSystem = fileSystem()
|
||||
val target = directory / "rig.uma"
|
||||
fileSystem.write(target) { write(byteArrayOf(1, 2, 3)) }
|
||||
|
||||
writeReplacing(fileSystem, target, byteArrayOf(9, 8, 7, 6))
|
||||
|
||||
assertContentEquals(byteArrayOf(9, 8, 7, 6), fileSystem.read(target) { readByteArray() })
|
||||
assertEquals(listOf(target), fileSystem.list(directory), "nothing but the target remains")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun createsAFileThatDidNotExist() {
|
||||
val fileSystem = fileSystem()
|
||||
val target = directory / "new.uma"
|
||||
|
||||
writeReplacing(fileSystem, target, byteArrayOf(4, 2))
|
||||
|
||||
assertContentEquals(byteArrayOf(4, 2), fileSystem.read(target) { readByteArray() })
|
||||
assertEquals(listOf(target), fileSystem.list(directory))
|
||||
}
|
||||
|
||||
/**
|
||||
* A process killed mid-save leaves its temporary behind; the next save of that file sweeps it, and
|
||||
* touches nothing that is not its own.
|
||||
*/
|
||||
@Test
|
||||
fun aLeftoverTemporaryIsSweptByTheNextSaveOfThatFile() {
|
||||
val fileSystem = fileSystem()
|
||||
val target = directory / "rig.uma"
|
||||
val leftover = directory / ".rig.uma.tmp-deadbeef"
|
||||
val anothersTemporary = directory / ".other.uma.tmp-cafe"
|
||||
val lookAlike = directory / "rig.uma.tmp-notes"
|
||||
for (path in listOf(leftover, anothersTemporary, lookAlike)) {
|
||||
fileSystem.write(path) { write(byteArrayOf(0)) }
|
||||
}
|
||||
|
||||
writeReplacing(fileSystem, target, byteArrayOf(5, 5))
|
||||
|
||||
assertEquals(listOf(anothersTemporary, target, lookAlike).sortedBy { path -> path.name }, fileSystem.list(directory).sortedBy { path -> path.name }, "only this file's own leftover went")
|
||||
assertContentEquals(byteArrayOf(5, 5), fileSystem.read(target) { readByteArray() })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFailedWriteLeavesTheOldFileAndNoTemporary() {
|
||||
val disk = fileSystem()
|
||||
val target = directory / "rig.uma"
|
||||
disk.write(target) { write(byteArrayOf(1, 2, 3)) }
|
||||
// A disk that fails every write mid-stream: the temporary is opened, the bytes never land.
|
||||
val failing =
|
||||
object : ForwardingFileSystem(disk) {
|
||||
override fun sink(file: Path, mustCreate: Boolean): Sink {
|
||||
val sink = super.sink(file, mustCreate)
|
||||
return object : ForwardingSink(sink) {
|
||||
override fun write(source: Buffer, byteCount: Long): Unit = throw IOException("no space left on device")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assertFailsWith<IOException> { writeReplacing(failing, target, byteArrayOf(9, 9, 9)) }
|
||||
|
||||
assertContentEquals(byteArrayOf(1, 2, 3), disk.read(target) { readByteArray() }, "the old file is intact")
|
||||
assertFalse(disk.list(directory).any { path -> path.name.contains(".tmp-") }, "no temporary is left behind")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package org.umamo.storage
|
||||
|
||||
import okio.FileSystem
|
||||
import okio.Path
|
||||
import okio.Path.Companion.toPath
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Builds the desktop [AppStorage], resolving per-OS config/data directories under [applicationName]:
|
||||
* Linux follows XDG (`~/.config`, `~/.local/share`), macOS uses `~/Library/Application Support`, Windows
|
||||
* uses `%APPDATA%` / `%LOCALAPPDATA%`. IO goes through the real filesystem (`FileSystem.SYSTEM`).
|
||||
*
|
||||
* @param String applicationName The app's directory name (e.g. "umamo").
|
||||
* @return AppStorage The desktop storage.
|
||||
*/
|
||||
fun desktopAppStorage(applicationName: String): AppStorage =
|
||||
OkioAppStorage(
|
||||
FileSystem.SYSTEM,
|
||||
configDirectory = desktopBaseDirectory(config = true).toOkioPath() / applicationName,
|
||||
dataDirectory = desktopBaseDirectory(config = false).toOkioPath() / applicationName,
|
||||
)
|
||||
|
||||
/**
|
||||
* Resolves the OS's base config or data directory (without the app name).
|
||||
*
|
||||
* @param Boolean config True for the config base, false for the data base.
|
||||
* @return File The base directory.
|
||||
*/
|
||||
private fun desktopBaseDirectory(config: Boolean): File {
|
||||
val home = System.getProperty("user.home") ?: "."
|
||||
val os = System.getProperty("os.name").orEmpty().lowercase()
|
||||
return when {
|
||||
os.contains("win") -> {
|
||||
val variable = if (config) "APPDATA" else "LOCALAPPDATA"
|
||||
val fallback = if (config) "$home\\AppData\\Roaming" else "$home\\AppData\\Local"
|
||||
File(System.getenv(variable) ?: fallback)
|
||||
}
|
||||
os.contains("mac") || os.contains("darwin") -> File("$home/Library/Application Support")
|
||||
else -> {
|
||||
val variable = if (config) "XDG_CONFIG_HOME" else "XDG_DATA_HOME"
|
||||
val fallback = if (config) "$home/.config" else "$home/.local/share"
|
||||
File(System.getenv(variable)?.takeIf { it.isNotBlank() } ?: fallback)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Converts a `java.io.File` to an okio [Path] via its absolute path. */
|
||||
private fun File.toOkioPath(): Path = absolutePath.toPath()
|
||||
@@ -0,0 +1,27 @@
|
||||
package org.umamo.storage
|
||||
|
||||
import io.github.vinceglb.filekit.PlatformFile
|
||||
import io.github.vinceglb.filekit.absolutePath
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import okio.FileSystem
|
||||
import okio.Path.Companion.toPath
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Desktop actual: a stored path is an ordinary filesystem path.
|
||||
*
|
||||
* @param String path The stored path.
|
||||
* @return PlatformFile The reconstructed file handle.
|
||||
*/
|
||||
actual fun platformFileFromSavedPath(path: String): PlatformFile = PlatformFile(File(path))
|
||||
|
||||
/**
|
||||
* Desktop actual: a temporary sibling moved atomically over the target, off the caller's thread.
|
||||
*
|
||||
* @param ByteArray bytes The complete contents.
|
||||
*/
|
||||
actual suspend fun PlatformFile.writeReplacing(bytes: ByteArray) {
|
||||
val target = absolutePath().toPath()
|
||||
withContext(Dispatchers.IO) { writeReplacing(FileSystem.SYSTEM, target, bytes) }
|
||||
}
|
||||
Reference in New Issue
Block a user