/
FileTreeWalk.kt
281 lines (237 loc) · 10.3 KB
/
FileTreeWalk.kt
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
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:JvmMultifileClass
@file:JvmName("FilesKt")
package kotlin.io
import kotlin.*
import java.io.File
import java.io.IOException
import java.util.Stack
/**
* An enumeration to describe possible walk directions.
* There are two of them: beginning from parents, ending with children,
* and beginning from children, ending with parents. Both use depth-first search.
*/
public enum class FileWalkDirection {
/** Depth-first search, directory is visited BEFORE its files */
TOP_DOWN,
/** Depth-first search, directory is visited AFTER its files */
BOTTOM_UP
// Do we want also breadth-first search?
}
/**
* This class is intended to implement different file traversal methods.
* It allows to iterate through all files inside a given directory.
*
* Use [File.walk], [File.walkTopDown] or [File.walkBottomUp] extension functions to instantiate a `FileTreeWalk` instance.
* If the file path given is just a file, walker iterates only it.
* If the file path given does not exist, walker iterates nothing, i.e. it's equivalent to an empty sequence.
*/
public class FileTreeWalk private constructor(
private val start: File,
private val direction: FileWalkDirection = FileWalkDirection.TOP_DOWN,
private val onEnter: ((File) -> Boolean)?,
private val onLeave: ((File) -> Unit)?,
private val onFail: ((f: File, e: IOException) -> Unit)?,
private val maxDepth: Int = Int.MAX_VALUE
) : Sequence<File> {
internal constructor(start: File, direction: FileWalkDirection = FileWalkDirection.TOP_DOWN) : this(start, direction, null, null, null)
/** Returns an iterator walking through files. */
override public fun iterator(): Iterator<File> = FileTreeWalkIterator()
/** Abstract class that encapsulates file visiting in some order, beginning from a given [root] */
private abstract class WalkState(val root: File) {
/** Call of this function proceeds to a next file for visiting and returns it */
abstract public fun step(): File?
}
/** Abstract class that encapsulates directory visiting in some order, beginning from a given [rootDir] */
private abstract class DirectoryState(rootDir: File) : WalkState(rootDir) {
init {
if (_Assertions.ENABLED)
assert(rootDir.isDirectory) { "rootDir must be verified to be directory beforehand." }
}
}
private inner class FileTreeWalkIterator : AbstractIterator<File>() {
// Stack of directory states, beginning from the start directory
private val state = Stack<WalkState>()
init {
if (start.isDirectory) {
state.push(directoryState(start))
} else if (start.isFile) {
state.push(SingleFileState(start))
} else {
done()
}
}
override fun computeNext() {
val nextFile = gotoNext()
if (nextFile != null)
setNext(nextFile)
else
done()
}
private fun directoryState(root: File): DirectoryState {
return when (direction) {
FileWalkDirection.TOP_DOWN -> TopDownDirectoryState(root)
FileWalkDirection.BOTTOM_UP -> BottomUpDirectoryState(root)
}
}
tailrec private fun gotoNext(): File? {
if (state.empty()) {
// There is nothing in the state
return null
}
// Take next file from the top of the stack
val topState = state.peek()!!
val file = topState.step()
if (file == null) {
// There is nothing more on the top of the stack, go back
state.pop()
return gotoNext()
} else {
// Check that file/directory matches the filter
if (file == topState.root || !file.isDirectory || state.size >= maxDepth) {
// Proceed to a root directory or a simple file
return file
} else {
// Proceed to a sub-directory
state.push(directoryState(file))
return gotoNext()
}
}
}
/** Visiting in bottom-up order */
private inner class BottomUpDirectoryState(rootDir: File) : DirectoryState(rootDir) {
private var rootVisited = false
private var fileList: Array<File>? = null
private var fileIndex = 0
private var failed = false
/** First all children, then root directory */
override public fun step(): File? {
if (!failed && fileList == null) {
if (onEnter?.invoke(root) == false) {
return null
}
fileList = root.listFiles()
if (fileList == null) {
onFail?.invoke(root, AccessDeniedException(file = root, reason = "Cannot list files in a directory"))
failed = true
}
}
if (fileList != null && fileIndex < fileList!!.size) {
// First visit all files
return fileList!![fileIndex++]
} else if (!rootVisited) {
// Then visit root
rootVisited = true
return root
} else {
// That's all
onLeave?.invoke(root)
return null
}
}
}
/** Visiting in top-down order */
private inner class TopDownDirectoryState(rootDir: File) : DirectoryState(rootDir) {
private var rootVisited = false
private var fileList: Array<File>? = null
private var fileIndex = 0
/** First root directory, then all children */
override public fun step(): File? {
if (!rootVisited) {
// First visit root
if (onEnter?.invoke(root) == false) {
return null
}
rootVisited = true
return root
} else if (fileList == null || fileIndex < fileList!!.size) {
if (fileList == null) {
// Then read an array of files, if any
fileList = root.listFiles()
if (fileList == null) {
onFail?.invoke(root, AccessDeniedException(file = root, reason = "Cannot list files in a directory"))
}
if (fileList == null || fileList!!.size == 0) {
onLeave?.invoke(root)
return null
}
}
// Then visit all files
return fileList!![fileIndex++]
} else {
// That's all
onLeave?.invoke(root)
return null
}
}
}
private inner class SingleFileState(rootFile: File) : WalkState(rootFile) {
private var visited: Boolean = false
init {
if (_Assertions.ENABLED)
assert(rootFile.isFile) { "rootFile must be verified to be file beforehand." }
}
override fun step(): File? {
if (visited) return null
visited = true
return root
}
}
}
/**
* Sets a predicate [function], that is called on any entered directory before its files are visited
* and before it is visited itself.
*
* If the [function] returns `false` the directory is not entered and neither it nor its files are visited.
*/
public fun onEnter(function: (File) -> Boolean): FileTreeWalk {
return FileTreeWalk(start, direction, onEnter = function, onLeave = onLeave, onFail = onFail, maxDepth = maxDepth)
}
/**
* Sets a callback [function], that is called on any left directory after its files are visited and after it is visited itself.
*/
public fun onLeave(function: (File) -> Unit): FileTreeWalk {
return FileTreeWalk(start, direction, onEnter = onEnter, onLeave = function, onFail = onFail, maxDepth = maxDepth)
}
/**
* Set a callback [function], that is called on a directory when it's impossible to get its file list.
*
* [onEnter] and [onLeave] callback functions are called even in this case.
*/
public fun onFail(function: (File, IOException) -> Unit): FileTreeWalk {
return FileTreeWalk(start, direction, onEnter = onEnter, onLeave = onLeave, onFail = function, maxDepth = maxDepth)
}
/**
* Sets the maximum [depth] of a directory tree to traverse. By default there is no limit.
*
* The value must be positive and [Int.MAX_VALUE] is used to specify an unlimited depth.
*
* With a value of 1, walker visits only the origin directory and all its immediate children,
* with a value of 2 also grandchildren, etc.
*/
public fun maxDepth(depth: Int): FileTreeWalk {
if (depth <= 0)
throw IllegalArgumentException("depth must be positive, but was $depth.")
return FileTreeWalk(start, direction, onEnter, onLeave, onFail, depth)
}
}
/**
* Gets a sequence for visiting this directory and all its content.
*
* @param direction walk direction, top-down (by default) or bottom-up.
*/
public fun File.walk(direction: FileWalkDirection = FileWalkDirection.TOP_DOWN): FileTreeWalk =
FileTreeWalk(this, direction)
/**
* Gets a sequence for visiting this directory and all its content in top-down order.
* Depth-first search is used and directories are visited before all their files.
*/
public fun File.walkTopDown(): FileTreeWalk = walk(FileWalkDirection.TOP_DOWN)
/**
* Gets a sequence for visiting this directory and all its content in bottom-up order.
* Depth-first search is used and directories are visited after all their files.
*/
public fun File.walkBottomUp(): FileTreeWalk = walk(FileWalkDirection.BOTTOM_UP)