commit e99b3c45762dbf2fed23a21a8255cef645cfaf1c Author: Brage Skjønborg Date: Sun Oct 11 19:56:26 2026 +0200 Init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..912d438 --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/** +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Kotlin ### +.kotlin + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..9a2c437 --- /dev/null +++ b/README.md @@ -0,0 +1,48 @@ +# IFile + +A small Kotlin/JVM library that puts file operations behind the `IFile` interface. `UseFile` is the real filesystem implementation. `FakeFile` is included as an alternate `IFile` implementation for tests that want to override the real filesystem without touching disk. + +## Use + +```kotlin +dependencies { + implementation("no.iktdev.library:files:1.0.0") +} +``` + +Add the Reposilite releases repository to the consuming project's dependency repositories. Use the snapshots repository when consuming a `-SNAPSHOT` version. + +Hashing is part of `IFile`; both helpers return the included `FileHash` type, so consumers do not need a separate hashing dependency or imports: + +```kotlin +val sha256: FileHash = IFile("video.mkv").toSha256() +val xxHash: FileHash = IFile("video.mkv").toXxHash() +``` + +Tests can set the existing factory to use the fake implementation: + +```kotlin +@BeforeEach +fun setUp() { + FakeFile.wipe() + IFile.factory = { path -> FakeFile(path) } +} +``` + +`FakeFile` is intentionally a test implementation, not a full emulation of every platform filesystem behavior. `toJavaFile()` is unsupported by the fake. + +## Publish + +Publish locally with: + +```shell +./gradlew publishToMavenLocal +``` + +Publish to Reposilite with: + +```shell +REPOSILITE_USERNAME=... REPOSILITE_PASSWORD=... ./gradlew publish +``` + +Set `releaseVersion` or `RELEASE_VERSION` for a release version. The default is `1.0.0-SNAPSHOT`; repository URLs can be overridden with `REPOSILITE_SNAPSHOT_URL` and `REPOSILITE_RELEASE_URL`. diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..e2a5775 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,140 @@ +import java.io.ByteArrayOutputStream +import org.gradle.api.tasks.bundling.Jar +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +plugins { + kotlin("jvm") version "2.3.21" + `java-library` + `maven-publish` +} + +val groupId = "no.iktdev.library" +val artifactName = "files" +val fallbackVersion = "1.0.0-SNAPSHOT" + +group = groupId +version = resolveProjectVersion() + +repositories { + mavenCentral() +} + +dependencies { + implementation("org.lz4:lz4-java:1.8.0") + testImplementation(kotlin("test")) +} + +kotlin { + jvmToolchain(21) + compilerOptions { + jvmTarget.set(JvmTarget.JVM_21) + } +} + +java { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 + withSourcesJar() + withJavadocJar() +} + +tasks.test { + useJUnitPlatform() +} + +tasks.withType().configureEach { + manifest { + attributes( + mapOf( + "Implementation-Title" to artifactName, + "Implementation-Version" to project.version.toString(), + "Implementation-Vendor" to "no.iktdev" + ) + ) + } +} + +val snapshotRepositoryUrl = providers.environmentVariable("REPOSILITE_SNAPSHOT_URL") + .orElse("https://reposilite.iktdev.no/snapshots").get() +val releaseRepositoryUrl = providers.environmentVariable("REPOSILITE_RELEASE_URL") + .orElse("https://reposilite.iktdev.no/releases").get() +val publicationRepositoryUrl = if (version.toString().endsWith("-SNAPSHOT")) { + snapshotRepositoryUrl +} else { + releaseRepositoryUrl +} + +publishing { + publications { + create("reposilite") { + groupId = groupId + artifactId = artifactName + version = project.version.toString() + from(components["java"]) + + pom { + name.set(artifactName) + description.set("Kotlin file abstraction with java.io.File and test-friendly implementations") + url.set("https://reposilite.iktdev.no") + } + } + } + + repositories { + mavenLocal() + maven { + name = "reposilite" + url = uri(publicationRepositoryUrl) + credentials { + username = providers.environmentVariable("REPOSILITE_USERNAME") + .orElse(providers.environmentVariable("reposiliteUsername")).orNull + password = providers.environmentVariable("REPOSILITE_PASSWORD") + .orElse(providers.environmentVariable("reposilitePassword")).orNull + } + } + } +} + +fun resolveProjectVersion(): String { + providers.gradleProperty("releaseVersion").orNull?.let { return normalizeTagVersion(it) } + providers.environmentVariable("RELEASE_VERSION").orNull?.let { return normalizeTagVersion(it) } + + val ref = sequenceOf("GITHUB_REF", "GITEA_REF", "CI_COMMIT_TAG") + .mapNotNull { providers.environmentVariable(it).orNull } + .firstOrNull { it.isNotBlank() } + if (ref?.startsWith("refs/tags/") == true) { + return normalizeTagVersion(ref.removePrefix("refs/tags/")) + } + + val latestTag = gitOutput("describe", "--tags", "--abbrev=0") + return latestTag?.let(::nextSnapshotVersion) ?: fallbackVersion +} + +fun normalizeTagVersion(tag: String): String { + val normalized = tag.trim().removePrefix("v") + require(Regex("\\d+(?:\\.\\d+)+(?:[-+][0-9A-Za-z.-]+)?").matches(normalized)) { + "Release tag '$tag' must be a numeric version such as v1.9 or v1.2.3" + } + return normalized +} + +fun nextSnapshotVersion(tag: String): String { + val match = Regex("^(?:v)?(\\d+(?:\\.\\d+)+)(?:[-+].*)?$").matchEntire(tag.trim()) + ?: return fallbackVersion + val parts = match.groupValues[1].split('.').toMutableList() + val last = parts.last().toIntOrNull() ?: return fallbackVersion + parts[parts.lastIndex] = (last + 1).toString() + return "${parts.joinToString(".")}-SNAPSHOT" +} + +fun gitOutput(vararg arguments: String): String? = try { + val output = ByteArrayOutputStream() + val result = providers.exec { + commandLine("git", *arguments) + standardOutput = output + isIgnoreExitValue = true + }.result.get() + output.toString().trim().takeIf { result.exitValue == 0 && it.isNotBlank() } +} catch (_: Exception) { + null +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..7fc6f1f --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 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..1b80468 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sun Oct 11 19:39:57 CEST 2026 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.0-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original 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 POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${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 "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# 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" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /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..0c8fc1b --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,12 @@ +pluginManagement { + repositories { + gradlePluginPortal() + mavenCentral() + } +} + +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" +} + +rootProject.name = "IFile" diff --git a/src/main/kotlin/no/iktdev/files/FakeFile.kt b/src/main/kotlin/no/iktdev/files/FakeFile.kt new file mode 100644 index 0000000..b3fe34d --- /dev/null +++ b/src/main/kotlin/no/iktdev/files/FakeFile.kt @@ -0,0 +1,358 @@ +package no.iktdev.files + +import java.io.File +import java.io.InputStream +import java.io.OutputStream +import java.io.PrintWriter +import java.nio.file.FileAlreadyExistsException +import java.nio.file.FileSystemException +import java.nio.file.Paths + +class FakeFile( + override var path: String, + private var exists: Boolean = true, + private var size: Long = 0, + private var directory: Boolean = false, + private var content: String = "", + private var modified: Long = System.currentTimeMillis(), + private var writable: Boolean = true +) : IFile { + + init { + if (!directory) { + directory = !path.substringAfterLast('/').contains('.') + } + fileRegistry.putIfAbsent(path, this) + } + + + companion object { + val fileRegistry: MutableMap = mutableMapOf() + + fun wipe() = fileRegistry.clear() + + fun getOrCreate(path: String): FakeFile = + fileRegistry.getOrPut(path) { + FakeFile(path) + } + } + + /** Always return the canonical instance for this path */ + private fun ref(): FakeFile = fileRegistry[path] ?: this + + override val name: String + get() = path.substringAfterLast('/') + + override val parent: String? + get() = path.substringBeforeLast('/', "").ifEmpty { null } + + override val absolutePath: String + get() = path + + override val nameWithoutExtension: String + get() = name.substringBeforeLast('.', name) + + override val parentFile: IFile + get() = parent?.let { IFile(it) } ?: FakeFile("") + + // --- State accessors always use registry instance --- + override fun exists(): Boolean = ref().exists + fun changeExist(exists: Boolean) { + val r = ref() + r.exists = exists + } + override fun isFile(): Boolean = !ref().directory + override fun isDirectory(): Boolean = ref().directory + override fun length(): Long = ref().size + override fun readText(): String = ref().content + override fun lastModified(): Long = ref().modified + override fun canRead(): Boolean { + return true + } + + override fun canWrite(): Boolean { + return true + } + + override fun writeText(text: String) { + val r = ref() + r.exists = true + r.content = text + r.size = text.toByteArray().size.toLong() + r.modified = System.currentTimeMillis() + } + + override fun appendLine(text: String) { + val r = ref() + r.exists = true + r.content += "$text\n" + r.size = r.content.toByteArray().size.toLong() + r.modified = System.currentTimeMillis() + } + + fun setDirectory() { + ref().directory = true + } + + fun setFile() { + ref().directory = false + } + + override fun mkdir(): Boolean { + val r = ref() + r.exists = true + r.directory = true + return true + } + + override fun setWritable(state: Boolean): Boolean { + val r = ref() + return r.setWritable(state) + } + + override fun mkdirs(): Boolean { + return mkdir() + } + + override fun delete(): Boolean { + val r = ref() + r.exists = false + r.content = "" + r.size = 0 + return true + } + + override fun deleteRecursively(): Boolean { + val prefix = absolutePath + fileRegistry.values + .filter { it.absolutePath.startsWith(prefix) } + .forEach { + it.exists = false + it.content = "" + it.size = 0 + } + delete() + return true + } + + override fun deleteAllChildren(): Boolean { + val children = listFiles() + var ok = true + + for (child in children) { + val f = child as FakeFile + + if (f.isDirectory()) { + if (!f.deleteRecursively()) ok = false + } else { + if (!f.delete()) ok = false + } + } + + return ok + } + + override fun listFiles(): List { + val prefix = if (absolutePath.endsWith("/")) absolutePath else "$absolutePath/" + return fileRegistry.values + .filter { it.absolutePath.startsWith(prefix) } + .filter { child -> + // relative path after root + val rel = child.absolutePath.removePrefix(prefix) + // direct child has no further slashes + !rel.contains('/') + } + } + + + override fun walk(): Sequence = + fileRegistry.values + .filter { it.absolutePath.startsWith(absolutePath) } + .asSequence() + + override fun printWriter(): PrintWriter = + object : PrintWriter(object : java.io.Writer() { + override fun write(str: String) { + if (str.isEmpty()) return + val r = ref() + r.exists = true + r.content += str + r.size = r.content.toByteArray().size.toLong() + r.modified = System.currentTimeMillis() + } + + override fun write(cbuf: CharArray?, off: Int, len: Int) { + if (cbuf != null && len > 0) write(String(cbuf, off, len)) + } + + override fun write(c: Int) = write(c.toChar().toString()) + override fun flush() {} + override fun close() {} + }) {} + + override fun writeBytes(bytes: ByteArray) { + val r = ref() + r.exists = true + r.directory = false + r.size = bytes.size.toLong() + r.content = String(bytes) // lagres som binær data i string-form + r.modified = System.currentTimeMillis() + } + + + override fun toJavaFile(): File = + throw UnsupportedOperationException("FakeFile does not support toJavaFile()") + + override fun using(vararg paths: String): IFile { + val newPath = Paths.get(absolutePath, *paths).normalize().toString() + return getOrCreate(newPath) + } + + override fun setLastModified(time: Long) { + this.modified = time + } + + override fun renameTo(dest: IFile): Boolean { + val src = ref() + if (!src.exists) return false + + val oldPath = src.path + val destPath = dest.absolutePath + + // Remove any existing dest + fileRegistry.remove(destPath) + + // Move registry entry + fileRegistry[destPath] = src + src.path = destPath + + // Mark old path as deleted (but do NOT modify src) + fileRegistry[oldPath] = FakeFile(oldPath, exists = false, content = "", size = 0) + + return true + } + + override fun openInputStream(): InputStream { + val r = ref() + val bytes = r.content.toByteArray() + return object : InputStream() { + var pos = 0 + + override fun read(): Int { + return if (pos < bytes.size) { + bytes[pos++].toInt() and 0xFF + } else { + -1 + } + } + + override fun read(b: ByteArray, off: Int, len: Int): Int { + if (pos >= bytes.size) return -1 + val toCopy = minOf(len, bytes.size - pos) + System.arraycopy(bytes, pos, b, off, toCopy) + pos += toCopy + return toCopy + } + } + } + + override fun openOutputStream(): OutputStream { + val r = ref() + r.exists = true + + return object : OutputStream() { + private val buffer = StringBuilder() + + override fun write(b: Int) { + buffer.append(b.toChar()) + } + + override fun write(b: ByteArray, off: Int, len: Int) { + buffer.append(String(b, off, len)) + } + + override fun flush() { + val newContent = buffer.toString() + r.content += newContent + r.size = r.content.toByteArray().size.toLong() + r.modified = System.currentTimeMillis() + } + + override fun close() { + flush() + } + } + } + + override fun copyTo(dest: IFile, overwrite: Boolean, bufferSize: Int): IFile { + if (!this.exists()) { + throw RuntimeException("${this.absolutePath} The source file doesn't exist.") + } + + if (dest.exists()) { + if (!overwrite) + throw FileAlreadyExistsException( + this.absolutePath, + dest.absolutePath, + "The destination file already exists." + ) + else if (!dest.delete()) + throw FileAlreadyExistsException( + this.absolutePath, + dest.absolutePath, + "Tried to overwrite the destination, but failed to delete it." + ) + } + + if (this.isDirectory()) { + if (!dest.mkdirs()) + throw FileSystemException(this.absolutePath, dest.absolutePath, "Failed to create target directory.") + } else { + dest.parentFile.mkdirs() + + this.openInputStream().use { input -> + dest.openOutputStream().use { output -> + val buffer = ByteArray(bufferSize) + var bytesRead: Int + while (input.read(buffer).also { bytesRead = it } != -1) { + output.write(buffer, 0, bytesRead) + } + } + } + } + + return dest + } + + override fun startsWith(other: IFile): Boolean { + return this.absolutePath.startsWith(other.absolutePath) + } + + + override fun equals(other: Any?): Boolean { + return if (other is FakeFile) { + this.absolutePath == other.absolutePath + } else if (other is IFile) { + other is IFile && this.absolutePath == other.absolutePath + } else { + super.equals(other) + } + } + + override fun hashCode(): Int { + var result = exists.hashCode() + result = 31 * result + size.hashCode() + result = 31 * result + directory.hashCode() + result = 31 * result + modified.hashCode() + result = 31 * result + writable.hashCode() + result = 31 * result + path.hashCode() + result = 31 * result + content.hashCode() + result = 31 * result + name.hashCode() + result = 31 * result + (parent?.hashCode() ?: 0) + result = 31 * result + absolutePath.hashCode() + result = 31 * result + nameWithoutExtension.hashCode() + result = 31 * result + parentFile.hashCode() + return result + } + +} diff --git a/src/main/kotlin/no/iktdev/files/FileHash.kt b/src/main/kotlin/no/iktdev/files/FileHash.kt new file mode 100644 index 0000000..3b7c312 --- /dev/null +++ b/src/main/kotlin/no/iktdev/files/FileHash.kt @@ -0,0 +1,9 @@ +package no.iktdev.files + +data class FileHash(val hash: String, val method: FileHashType) { +} + +enum class FileHashType { + SHA256, + XX64Hash +} \ No newline at end of file diff --git a/src/main/kotlin/no/iktdev/files/IFile.kt b/src/main/kotlin/no/iktdev/files/IFile.kt new file mode 100644 index 0000000..a865063 --- /dev/null +++ b/src/main/kotlin/no/iktdev/files/IFile.kt @@ -0,0 +1,146 @@ +package no.iktdev.files + +import net.jpountz.xxhash.XXHashFactory +import java.io.File +import java.io.InputStream +import java.io.OutputStream +import java.io.PrintWriter +import java.nio.file.FileSystemException +import java.nio.file.Path +import java.nio.file.Paths +import java.security.MessageDigest + +interface IFile { + val path: String + val name: String + val parent: String? + val parentFile: IFile + val absolutePath: String + + val nameWithoutExtension: String + + fun exists(): Boolean + fun isFile(): Boolean + fun isDirectory(): Boolean + fun length(): Long + fun delete(): Boolean + + fun canRead(): Boolean + fun canWrite(): Boolean + + fun listFiles(): List + + fun listFiles(filter: (parent: IFile, name: String) -> Boolean): List { + return this.listFiles() + .filter { child -> filter(this, child.name) } + } + + fun toPath(): Path = Paths.get(this.absolutePath) + + fun toJavaFile(): File + + fun readText(): String + + fun writeText(text: String) + fun appendLine(text: String) + + fun mkdirs(): Boolean + fun mkdir(): Boolean + + fun setWritable(state: Boolean): Boolean + + companion object { + // Default factory – can be overridden in tests + var factory: (String) -> IFile = { UseFile(it) } + + operator fun invoke(path: String): IFile = factory(path) + } + + fun using(vararg paths: String): IFile = + IFile(paths.fold(Paths.get(path), Path::resolve).toString()) + + fun extension(): String = + name.substringAfterLast('.', "") + + fun walk(): Sequence + fun lastModified(): Long + fun printWriter(): PrintWriter + + fun deleteRecursively(): Boolean + fun deleteAllChildren(): Boolean + + fun resolve(child: String): IFile { + return IFile(Paths.get(this.path).resolve(child).toString()) + } + + fun renameTo(dest: IFile): Boolean + + fun notExist(): Boolean { + return !exists() + } + + fun copyTo(dest: IFile, overwrite: Boolean = false, bufferSize: Int = DEFAULT_BUFFER_SIZE): IFile + + fun openInputStream(): InputStream + fun openOutputStream(): OutputStream + fun writeBytes(bytes: ByteArray) + fun setLastModified(time: Long) + fun startsWith(other: IFile): Boolean + + fun toSha256(): FileHash { + val digest = MessageDigest.getInstance("SHA-256") + this.openInputStream().use { input -> + val buffer = ByteArray(1024 * 1024) // 1 MB buffer + var bytesRead: Int + while (input.read(buffer).also { bytesRead = it } != -1) { + digest.update(buffer, 0, bytesRead) + } + } + return FileHash( + digest.digest().joinToString("") { "%02x".format(it) }, + FileHashType.SHA256 + ) + } + + fun toXxHash(): FileHash { + val factory = XXHashFactory.nativeInstance() + + // Merk: XXH3 er enklest å bruke på hele bytes, + // men for strømming bruker vi en 'streaming' hasher: + val streamHasher = factory.newStreamingHash64(0) // 0 er seed + + this.openInputStream().use { input -> + val buffer = ByteArray(1024 * 1024) + var bytesRead: Int + while (input.read(buffer).also { bytesRead = it } != -1) { + streamHasher.update(buffer, 0, bytesRead) + } + } + + // Returnerer som hex-streng + return FileHash(java.lang.Long.toHexString(streamHasher.value), FileHashType.XX64Hash) + } +} + +/** + * Sørger for at foreldremappen til denne filen eksisterer. + * Håndterer race conditions under flertrådet kjøring og returnerer referansen til mappen. + * + * @throws FileSystemException hvis mappen ikke kunne opprettes eller foreldrestien er ugyldig. + */ +fun IFile.ensureParentDirsExist(): IFile { + val parentDir = this.parentFile + ?: throw FileSystemException("Could not resolve parent directory for path: ${this.absolutePath}") + + if (!parentDir.exists()) { + // Hvis mkdirs() returnerer false, kan en annen tråd ha opprettet den akkurat nå + if (!parentDir.mkdirs()) { + // Dobbelsjekk om den ble opprettet i mellomtiden + if (!parentDir.exists()) { + throw FileSystemException("Failed to create directory: ${parentDir.absolutePath}") + } + } + } + + return parentDir +} \ No newline at end of file diff --git a/src/main/kotlin/no/iktdev/files/UseFile.kt b/src/main/kotlin/no/iktdev/files/UseFile.kt new file mode 100644 index 0000000..94a6447 --- /dev/null +++ b/src/main/kotlin/no/iktdev/files/UseFile.kt @@ -0,0 +1,141 @@ +package no.iktdev.files + +import java.io.File +import java.io.FileOutputStream +import java.io.InputStream +import java.io.OutputStream +import java.io.PrintWriter +import java.security.MessageDigest + +class UseFile(path: String) : IFile { + + private val file = File(path) + + override val path: String + get() = file.path + + override val name: String + get() = file.name + + override val nameWithoutExtension: String + get() = name.substringBeforeLast('.', missingDelimiterValue = "") + + override val parent: String? + get() = file.parent + + override val absolutePath: String + get() = file.absolutePath + + override val parentFile: IFile + get() = IFile(parent!!) + + override fun exists(): Boolean = + file.exists() + + override fun isFile(): Boolean = + file.isFile + + override fun isDirectory(): Boolean = + file.isDirectory + + override fun length(): Long = + file.length() + + override fun delete(): Boolean = + file.delete() + + override fun listFiles(): List = + file.listFiles()?.map { UseFile(it.path) } ?: emptyList() + + override fun toJavaFile(): File = + file + + override fun readText(): String { + return file.readText() + } + + override fun writeText(text: String) { + return file.writeText(text) + } + + override fun appendLine(text: String) { + file.parentFile.mkdirs() + FileOutputStream(file, true).bufferedWriter(Charsets.UTF_8).use { + it.appendLine(text) + } + } + + override fun mkdirs(): Boolean { + return file.mkdirs() + } + + override fun mkdir(): Boolean { + return file.mkdir() + } + + override fun walk(): Sequence = + file.walk().map { UseFile(it.path) } + + + override fun lastModified(): Long { + return file.lastModified() + } + + override fun printWriter(): PrintWriter { + return file.printWriter() + } + + override fun deleteRecursively(): Boolean { + return file.deleteRecursively() + } + + override fun deleteAllChildren(): Boolean { + val children = file.listFiles() ?: return true + + var ok = true + + for (child in children) { + if (child.isDirectory()) { + if (!child.deleteRecursively()) ok = false + } else { + if (!child.delete()) ok = false + } + } + + return ok + } + + + override fun renameTo(dest: IFile): Boolean { + return file.renameTo(dest.toJavaFile()) + } + + override fun setWritable(state: Boolean): Boolean { + return file.setWritable(state) + } + + override fun canRead() = file.canRead() + override fun canWrite() = file.canWrite() + + override fun copyTo(dest: IFile, overwrite: Boolean, bufferSize: Int): IFile { + file.copyTo(dest.toJavaFile(), overwrite, bufferSize) + return dest + } + + override fun openInputStream(): InputStream = file.inputStream() + override fun openOutputStream(): OutputStream = file.outputStream() + override fun writeBytes(bytes: ByteArray) { + file.writeBytes(bytes) + } + + override fun setLastModified(time: Long) { + file.setLastModified(time) + } + + override fun startsWith(other: IFile): Boolean { + return file.startsWith(other.toJavaFile()) + } + + + +}