aboutsummaryrefslogtreecommitdiff
path: root/okio/src/commonMain/kotlin/okio/FileSystem.kt
blob: 8bf42f8a5b9274bb2b7b56ffb3bbfe56daebb7c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*
 * Copyright (C) 2020 Square, Inc.
 *
 * 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
 *
 *      http://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.
 */
package okio

import okio.FileSystem.Companion.SYSTEM
import kotlin.jvm.JvmField

/**
 * Read and write access to a hierarchical collection of files, addressed by [paths][Path]. This
 * is a natural interface to the [current computer's local file system][SYSTEM].
 *
 * Not Just the Local File System
 * ------------------------------
 *
 * Other implementations are possible:
 *
 *  * `FakeFileSystem` is an in-memory file system suitable for testing. Note that this class is
 *    included in the `okio-fakefilesystem` artifact.
 *
 *  * A ZIP file system could provide access to the contents of a `.zip` file.
 *
 *  * A remote file system could access files over the network.
 *
 *  * A [decorating file system][ForwardingFileSystem] could apply monitoring, encryption,
 *    compression, or filtering to another file system implementation.
 *
 * For improved capability and testability, consider structuring your classes to dependency inject
 * a `FileSystem` rather than using [SYSTEM] directly.
 *
 * Limited API
 * -----------
 *
 * This interface is limited in which file system features it supports. Applications that need rich
 * file system features should use another API, possibly alongside this API.
 *
 * This class cannot create special file types like hard links, symlinks, pipes, or mounts. Reading
 * or writing these files works as if they were regular files.
 *
 * It cannot read or write file access control features like the UNIX `chmod` and Windows access
 * control lists. It does honor these controls and will fail with an [IOException] if privileges
 * are insufficient!
 *
 * It cannot lock files, or query which files are locked.
 *
 * It cannot watch the file system for changes.
 *
 * Multiplatform
 * -------------
 *
 * This class supports a matrix of Kotlin platforms (JVM, Kotlin/Native, Kotlin/JS) and operating
 * systems (Linux, macOS, and Windows). It attempts to balance working similarly across platforms
 * with being consistent with the local operating system.
 *
 * This is a blocking API which limits its applicability on concurrent Node.js services. File
 * operations will block the event loop (and all JavaScript execution!) until they complete.
 *
 * It supports the path schemes of both Windows (like `C:\Users`) and UNIX (like `/home`). Note that
 * path resolution rules differ by platform.
 *
 * Differences vs. Java IO APIs
 * ----------------------------
 *
 * The `java.io.File` class is Java's original file system API. The `delete` and `renameTo` methods
 * return false if the operation failed. The `list` method returns null if the file isn't a
 * directory or could not be listed. This class always throws `IOExceptions` when operations don't
 * succeed.
 *
 * The `java.nio.Path` and `java.nio.Files` classes are the entry points of Java's new file system
 * API. Each `Path` instance is scoped to a particular file system, though that is often implicit
 * because the `Paths.get()` function automatically uses the default (ie. system) file system.
 * In Okio's API paths are just identifiers; you must use a specific `FileSystem` object to do
 * I/O with.
 */
@ExperimentalFileSystem
abstract class FileSystem {
  /**
   * Resolves [path] against the current working directory and symlinks in this file system. The
   * returned path identifies the same file as [path], but with an absolute path that does not
   * include any symbolic links.
   *
   * This is similar to `File.getCanonicalFile()` on the JVM and `realpath` on POSIX. Unlike
   * `File.getCanonicalFile()`, this throws if the file doesn't exist.
   *
   * @throws IOException if [path] cannot be resolved. This will occur if the file doesn't exist,
   *     if the current working directory doesn't exist or is inaccessible, or if another failure
   *     occurs while resolving the path.
   */
  @Throws(IOException::class)
  abstract fun canonicalize(path: Path): Path

  /**
   * Returns metadata of the file, directory, or object identified by [path].
   *
   * @throws IOException if [path] does not exist or its metadata cannot be read.
   */
  @Throws(IOException::class)
  fun metadata(path: Path): FileMetadata {
    return metadataOrNull(path) ?: throw FileNotFoundException("no such file: $path")
  }

  /**
   * Returns metadata of the file, directory, or object identified by [path]. This returns null if
   * there is no file at [path].
   *
   * @throws IOException if [path] cannot be accessed due to a connectivity problem, permissions
   *     problem, or other issue.
   */
  @Throws(IOException::class)
  abstract fun metadataOrNull(path: Path): FileMetadata?

  /**
   * Returns true if [path] identifies an object on this file system.
   *
   * @throws IOException if [path] cannot be accessed due to a connectivity problem, permissions
   *     problem, or other issue.
   */
  @Throws(IOException::class)
  fun exists(path: Path): Boolean {
    return metadataOrNull(path) != null
  }

  /**
   * Returns the children of the directory identified by [dir]. The returned list is sorted using
   * natural ordering.
   *
   * @throws IOException if [dir] does not exist, is not a directory, or cannot be read. A directory
   *     cannot be read if the current process doesn't have access to [dir], or if there's a loop of
   *     symbolic links, or if any name is too long.
   */
  @Throws(IOException::class)
  abstract fun list(dir: Path): List<Path>

  /**
   * Returns a source that reads the bytes of [file] from beginning to end.
   *
   * @throws IOException if [file] does not exist, is not a file, or cannot be read. A file cannot
   *     be read if the current process doesn't have access to [file], if there's a loop of symbolic
   *     links, or if any name is too long.
   */
  @Throws(IOException::class)
  abstract fun source(file: Path): Source

  /**
   * Creates a source to read [file], executes [readerAction] to read it, and then closes the
   * source. This is a compact way to read the contents of a file.
   */
  inline fun <T> read(file: Path, readerAction: BufferedSource.() -> T): T {
    return source(file).buffer().use {
      it.readerAction()
    }
  }

  /**
   * Returns a sink that writes bytes to [file] from beginning to end. If [file] already exists it
   * will be replaced with the new data.
   *
   * @throws IOException if [file] cannot be written. A file cannot be written if its enclosing
   *     directory does not exist, if the current process doesn't have access to [file], if there's
   *     a loop of symbolic links, or if any name is too long.
   */
  @Throws(IOException::class)
  abstract fun sink(file: Path): Sink

  /**
   * Creates a sink to write [file], executes [writerAction] to write it, and then closes the sink.
   * This is a compact way to write a file.
   */
  inline fun <T> write(file: Path, writerAction: BufferedSink.() -> T): T {
    return sink(file).buffer().use {
      it.writerAction()
    }
  }

  /**
   * Returns a sink that appends bytes to the end of [file], creating it if it doesn't already
   * exist.
   *
   * @throws IOException if [file] cannot be written. A file cannot be written if its enclosing
   *     directory does not exist, if the current process doesn't have access to [file], if there's
   *     a loop of symbolic links, or if any name is too long.
   */
  @Throws(IOException::class)
  abstract fun appendingSink(file: Path): Sink

  /**
   * Creates a directory at the path identified by [dir].
   *
   * @throws IOException if [dir]'s parent does not exist, is not a directory, or cannot be written.
   *     A directory cannot be created if it already exists, if the current process doesn't have
   *     access, if there's a loop of symbolic links, or if any name is too long.
   */
  @Throws(IOException::class)
  abstract fun createDirectory(dir: Path)

  /**
   * Creates a directory at the path identified by [dir], and any enclosing parent path directories,
   * recursively.
   *
   * @throws IOException if any [metadata] or [createDirectory] operation fails.
   */
  @Throws(IOException::class)
  fun createDirectories(dir: Path) {
    // Compute the sequence of directories to create.
    val directories = ArrayDeque<Path>()
    var path: Path? = dir
    while (path != null && !exists(path)) {
      directories.addFirst(path)
      path = path.parent
    }

    // Create them.
    for (toCreate in directories) {
      createDirectory(toCreate)
    }
  }

  /**
   * Moves [source] to [target] in-place if the underlying file system supports it. If [target]
   * exists, it is first removed. If `source == target`, this operation does nothing. This may be
   * used to move a file or a directory.
   *
   * **Only as Atomic as the Underlying File System Supports**
   *
   * FAT and NTFS file systems cannot atomically move a file over an existing file. If the target
   * file already exists, the move is performed into two steps:
   *
   *  1. Atomically delete the target file.
   *  2. Atomically rename the source file to the target file.
   *
   * The delete step and move step are each atomic but not atomic in aggregate! If this process
   * crashes, the host operating system crashes, or the hardware fails it is possible that the
   * delete step will succeed and the rename will not.
   *
   * **Entire-file or nothing**
   *
   * These are the possible results of this operation:
   *
   *  * This operation returns normally, the source file is absent, and the target file contains the
   *    data previously held by the source file. This is the success case.
   *
   *  * The operation throws an [IOException] and the file system is unchanged. For example, this
   *    occurs if this process lacks permissions to perform the move.
   *
   *  * This operation throws an [IOException], the target file is deleted, but the source file is
   *    unchanged. This is the partial failure case described above and is only possible on
   *    file systems like FAT and NTFS that do not support atomic file replacement. Typically in
   *    such cases this operation won't return at all because the process or operating system has
   *    also crashed.
   *
   * There is no failure mode where the target file holds a subset of the bytes of the source file.
   * If the rename step cannot be performed atomically, this function will throw an [IOException]
   * before attempting a move. Typically this occurs if the source and target files are on different
   * physical volumes.
   *
   * **Non-Atomic Moves**
   *
   * If you need to move files across volumes, use [copy] followed by [delete], and change your
   * application logic to recover should the copy step suffer a partial failure.
   *
   * @throws IOException if the move cannot be performed, or cannot be performed atomically. Moves
   *     fail if the source doesn't exist, if the target is not writable, if the target already
   *     exists and cannot be replaced, or if the move would cause physical or quota limits to be
   *     exceeded. This list of potential problems is not exhaustive.
   */
  @Throws(IOException::class)
  abstract fun atomicMove(source: Path, target: Path)

  /**
   * Copies all of the bytes from the file at [source] to the file at [target]. This does not copy
   * file metadata like last modified time, permissions, or extended attributes.
   *
   * This function is not atomic; a failure may leave [target] in an inconsistent state. For
   * example, [target] may be empty or contain only a prefix of [source].
   *
   * @throws IOException if [source] cannot be read or if [target] cannot be written.
   */
  @Throws(IOException::class)
  open fun copy(source: Path, target: Path) {
    source(source).use { bytesIn ->
      sink(target).buffer().use { bytesOut ->
        bytesOut.writeAll(bytesIn)
      }
    }
  }

  /**
   * Deletes the file or directory at [path].
   *
   * @throws IOException if there is nothing at [path] to delete, or if there is a file or directory
   *     but it could not be deleted. Deletes fail if the current process doesn't have access, if
   *     the file system is readonly, or if [path] is a non-empty directory. This list of potential
   *     problems is not exhaustive.
   */
  @Throws(IOException::class)
  abstract fun delete(path: Path)

  /**
   * Recursively deletes all children of [fileOrDirectory] if it is a directory, then deletes
   * [fileOrDirectory] itself.
   *
   * This function does not defend against race conditions. For example, if child files are created
   * or deleted in [fileOrDirectory] while this function is executing, this may fail with an
   * [IOException].
   *
   * @throws IOException if any [metadata], [list], or [delete] operation fails.
   */
  @Throws(IOException::class)
  open fun deleteRecursively(fileOrDirectory: Path) {
    val stack = ArrayDeque<Path>()
    stack += fileOrDirectory

    while (stack.isNotEmpty()) {
      val toDelete = stack.removeLast()

      val metadata = metadata(toDelete)
      val children = if (metadata.isDirectory) list(toDelete) else listOf()

      if (children.isNotEmpty()) {
        stack += toDelete
        stack += children
      } else {
        delete(toDelete)
      }
    }
  }

  companion object {
    /**
     * The current process's host file system. Use this instance directly, or dependency inject a
     * [FileSystem] to make code testable.
     */
    @JvmField
    val SYSTEM: FileSystem = PLATFORM_FILE_SYSTEM

    /**
     * Returns a writable temporary directory on [SYSTEM].
     *
     * This is platform-specific.
     *
     *  * **JVM and Android**: the path in the `java.io.tmpdir` system property
     *  * **Linux, iOS, and macOS**: the path in the `TMPDIR` environment variable.
     *  * **Windows**: the first non-null of `TEMP`, `TMP`, and `USERPROFILE` environment variables.
     */
    @JvmField
    val SYSTEM_TEMPORARY_DIRECTORY: Path = PLATFORM_TEMPORARY_DIRECTORY
  }
}