kotlinx-io icon indicating copy to clipboard operation
kotlinx-io copied to clipboard

Add SystemFileSystem.copy()

Open StefanOltmann opened this issue 2 years ago • 4 comments
trafficstars

I wonder why there isn't a convenient copy method.

I would have expected that in SystemFileSystem.

For now I wrote a handy extension function to Path:

@OptIn(ExperimentalStdlibApi::class)
fun Path.copyTo(destination: Path) {

    require(SystemFileSystem.exists(this)) { "$this does not exist." }

    val metadata = SystemFileSystem.metadataOrNull(this)

    requireNotNull(metadata) { "Failed to read metadata of $this" }
    require(metadata.isRegularFile) { "Source $this must be a regular file." }

    SystemFileSystem.source(this).buffered().use { rawSource ->
        SystemFileSystem.sink(destination).buffered().use { sink ->
            sink.write(rawSource, metadata.size)
        }
    }
}

Do I miss something? Is copying hard? There must be a reason it's not there yet.

StefanOltmann avatar Nov 09 '23 12:11 StefanOltmann

As written this doesn't work for file systems other than the system one, and doesn't work when the paths are on separate file systems (e.g., copying out of a zip).

JakeWharton avatar Nov 09 '23 15:11 JakeWharton

@JakeWharton Okay, I understand now. It should be specifically implemented as part of SystemFileSystem rather than as a general feature.

If the separate file systems don't function properly when used in the lengthy manner (as in the code snippet above), it's acceptable for them to fail in the shorter written way.

I maintain the view that having a shortcut for copying would be beneficial.

StefanOltmann avatar Nov 09 '23 18:11 StefanOltmann

Writing the signature as

fun copy(srcFs: FileSystem, src: Path, dstFs: FileSystem, dst: Path)

Is more what I meant. This function works across file systems. You could also default the destination file system to the source file system with an argument rearrangement.

Nothing about copying is specific to SystemFileSystem, and having it only available there would be unnecessarily restrictive. The only reason to make such a function directly on a file system subtype would be if you were going to use actual copy commands which avoid copying the content through memory.

JakeWharton avatar Nov 09 '23 18:11 JakeWharton

Both options sound good to me. 🙂

Utilizing native copy commands on the same file system to avoid GC would be great.

StefanOltmann avatar Nov 09 '23 18:11 StefanOltmann