-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBlobTree.jl
370 lines (304 loc) · 10.8 KB
/
BlobTree.jl
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
361
362
363
364
365
366
367
368
369
370
# Many datasets have tree-like indices. Examples:
#
# Index Data
#
# * OS: directories files
# * Git: trees blobs
# * S3: prefixes blobs
# * HDF5 group typed data
# * Zip flattend directory(?) blobs
#
import AbstractTrees: AbstractTrees, children
#-------------------------------------------------------------------------------
abstract type AbstractBlobTree; end
# The tree API
# TODO: Should we have `istree` separate from `isdir`?
Base.isdir(x::AbstractBlobTree) = true
Base.isfile(tree::AbstractBlobTree) = false
Base.ispath(x::AbstractBlobTree) = true
# Number of children is not known without a (potentially high-latency) call to
# an external resource
Base.IteratorSize(tree::AbstractBlobTree) = Base.SizeUnknown()
function Base.iterate(tree::AbstractBlobTree, state=nothing)
if state == nothing
# By default, call `children(tree)` to eagerly get a list of children
# for iteration.
cs = children(tree)
itr = iterate(cs)
else
(cs, cstate) = state
itr = iterate(cs, cstate)
end
if itr == nothing
return nothing
else
(c, cstate) = itr
(c, (cs, cstate))
end
end
"""
children(tree::AbstractBlobTree)
Return an array of the children of `tree`. A child `x` may abstractly either be
another tree (`children(x)` returns a collection) or a file, where `children(x)`
returns `()`.
Note that this is subtly different from `readdir(path)` which returns relative
paths, or `readdir(path, join=true)` which returns absolute paths.
"""
function children(tree::AbstractBlobTree)
# TODO: Is dispatch to the root a correct default?
children(tree.root, tree.path)
end
"""
showtree([io,], tree)
Pretty printing of file trees, in the spirit of the unix `tree` utility.
"""
function showtree(io::IO, tree::AbstractBlobTree; maxdepth=5)
println(io, "📂 ", tree)
_showtree(io, tree, "", maxdepth)
end
struct ShownTree
tree
end
# Use a wrapper rather than defaulting to stdout so that this works in more
# functional environments such as Pluto.jl
showtree(tree::AbstractBlobTree) = ShownTree(tree)
Base.show(io::IO, s::ShownTree) = showtree(io, s.tree)
function _showtree(io::IO, tree::AbstractBlobTree, prefix, depth)
cs = children(tree)
for (i,x) in enumerate(cs)
islast = i == lastindex(cs) # TODO: won't work if children() is lazy
first_prefix = prefix * (islast ? "└──" : "├──")
other_prefix = prefix * (islast ? " " : "│ ")
if isdir(x)
print(io, first_prefix, "📂 ")
printstyled(io, basename(x), "\n", color=:light_blue, bold=true)
if depth > 1
_showtree(io, x, other_prefix, depth-1)
else
print(io, other_prefix, '⋮')
end
else
println(io, first_prefix, " ", basename(x))
end
end
end
function Base.copy!(dst::AbstractBlobTree, src::AbstractBlobTree)
for x in src
newpath = joinpath(dst, basename(x))
if isdir(x)
newdir = mkdir(newpath)
copy!(newdir, x)
else
open(x) do io_src
open(newpath, write=true) do io_dst
write(io_dst, io_src)
end
end
end
end
end
#-------------------------------------------------------------------------------
"""
Blob(root)
Blob(root, relpath)
`Blob` represents the location of a collection of unstructured binary data. The
location is a path `relpath` relative to some `root` data resource.
A `Blob` can naturally be `open()`ed as a `Vector{UInt8}`, but can also be
mapped into the program as an `IO` byte stream, or interpreted as a `String`.
Blobs can be arranged into hierarchies "directories" via the `BlobTree` type.
"""
mutable struct Blob{Root}
root::Root
path::RelPath
end
Blob(root) = Blob(root, RelPath())
Base.basename(file::Blob) = basename(file.path)
Base.abspath(file::Blob) = AbsPath(file.root, file.path)
Base.isdir(file::Blob) = false
Base.isfile(file::Blob) = true
Base.ispath(file::Blob) = true
function Base.show(io::IO, ::MIME"text/plain", file::Blob)
print(io, "📄 ", file.path, " @ ", summary(file.root))
end
function AbstractTrees.printnode(io::IO, file::Blob)
print(io, "📄 ", basename(file))
end
# Opening as Vector{UInt8} or as String defers to IO interface
function Base.open(f::Function, ::Type{Vector{UInt8}}, file::Blob)
open(IO, file.root, file.path) do io
f(read(io)) # TODO: use Mmap?
end
end
function Base.open(f::Function, ::Type{String}, file::Blob)
open(IO, file.root, file.path) do io
f(read(io, String))
end
end
# Default open-type for Blob is IO
Base.open(f::Function, file::Blob; kws...) = open(f, IO, file.root, file.path; kws...)
# Opening Blob as itself is trivial
function Base.open(f::Function, ::Type{Blob}, file::Blob)
f(file)
end
# open with other types T defers to the underlying storage system
function Base.open(f::Function, ::Type{T}, file::Blob; kws...) where {T}
open(f, T, file.root, file.path; kws...)
end
# ResourceContexts.jl - based versions of the above.
@! function Base.open(::Type{Vector{UInt8}}, file::Blob)
@context begin
# TODO: use Mmap?
read(@! open(IO, file.root, file.path))
end
end
@! function Base.open(::Type{String}, file::Blob)
@context begin
read(@!(open(IO, file.root, file.path)), String)
end
end
# Default open-type for Blob is IO
@! function Base.open(file::Blob; kws...)
@! open(IO, file.root, file.path; kws...)
end
# Opening Blob as itself is trivial
@! function Base.open(::Type{Blob}, file::Blob)
file
end
# open with other types T defers to the underlying storage system
@! function Base.open(::Type{T}, file::Blob; kws...) where {T}
@! open(T, file.root, file.path; kws...)
end
# Fallback implementation of `@! open(T, root, path)` based on enter_do.
#
# TODO: Update other backends to avoid calling this; using enter_do is pretty
# inefficient.
@! function Base.open(::Type{T}, root, path; kws...) where {T}
(res,) = @! enter_do(open, T, root, path; kws...)
res
end
# Unscoped form of open for Blob
function Base.open(::Type{T}, blob::Blob; kws...) where {T}
@context begin
result = @! open(T, blob; kws...)
@! ResourceContexts.detach_context_cleanup(result)
end
end
# read() is also supported for `Blob`s
Base.read(file::Blob) = read(file.root, file.path)
Base.read(file::Blob, ::Type{T}) where {T} = read(file.root, file.path, T)
# Support for opening AbsPath
#
# TODO: Put this elsewhere?
function Base.open(f::Function, ::Type{T}, path::AbsPath; kws...) where {T}
open(f, T, path.root, path.path; kws...)
end
Base.open(f::Function, path::AbsPath; kws...) = open(f, IO, path.root, path.path; kws...)
#-------------------------------------------------------------------------------
"""
BlobTree(root)
`BlobTree` is a "directory tree" like hierarchy which may have `Blob`s and
`BlobTree`s as children.
The tree implements the `AbstracTrees.children()` interface and may be indexed
with paths to traverse the hierarchy down to the leaves ("files") which are of
type `Blob`. Individual leaves may be `open()`ed as various Julia types.
# Example
Normally you'd construct these via the [`dataset`](@ref) function which takes
care of constructing the correct `root` object. However, here's a direct
demonstration:
```
julia> tree = BlobTree(DataSets.FileSystemRoot(dirname(pathof(DataSets))), path"../test/data")
📂 Tree ../test/data @ /home/chris/.julia/dev/DataSets/src
📁 csvset
📄 file.txt
📄 foo.txt
📄 people.csv.gz
julia> tree["csvset"]
📂 Tree ../test/data/csvset @ /home/chris/.julia/dev/DataSets/src
📄 1.csv
📄 2.csv
julia> tree[path"csvset"]
📂 Tree ../test/data/csvset @ /home/chris/.julia/dev/DataSets/src
📄 1.csv
📄 2.csv
```
"""
mutable struct BlobTree{Root} <: AbstractBlobTree
root::Root
path::RelPath
end
BlobTree(root) = BlobTree(root, RelPath())
function AbstractTrees.printnode(io::IO, tree::BlobTree)
print(io, "📂 ", basename(tree))
end
function Base.show(io::IO, ::MIME"text/plain", tree::AbstractBlobTree)
# TODO: Ideally we'd use
# AbstractTrees.print_tree(io, tree, 1)
# However, this is hard to use efficiently; we'd need to implement a lazy
# `children()` for all our trees. It'd be much easier if
# `AbstractTrees.has_children()` was used consistently upstream.
cs = children(tree)
println(io, "📂 Tree ", tree.path, " @ ", summary(tree.root))
for (i, c) in enumerate(cs)
print(io, " ", isdir(c) ? '📁' : '📄', " ", basename(c))
if i != length(cs)
print(io, '\n')
end
end
end
Base.basename(tree::BlobTree) = basename(tree.path)
Base.abspath(tree::BlobTree) = AbsPath(tree.root, tree.path)
# getindex vs joinpath:
# - getindex about indexing the datastrcutre; therefore it looks in the
# filesystem to only return things which exist.
# - joinpath just makes paths, not knowing whether they exist.
function Base.getindex(tree::BlobTree, path::RelPath)
relpath = joinpath(tree.path, path)
root = tree.root
# TODO: Make this more efficient by moving this work to the storage backend?
# Sort of like an equivalent of `stat`?
if isdir(root, relpath)
BlobTree(root, relpath)
elseif isfile(root, relpath)
Blob(root, relpath)
elseif ispath(root, relpath)
AbsPath(root, relpath) # Not great?
else
error("Path $relpath @ $root doesn't exist")
end
end
function Base.getindex(tree::BlobTree, name::AbstractString)
getindex(tree, joinpath(RelPath(), name))
end
# We've got a weird mishmash of path vs tree handling here.
# TODO: Can we refactor this to cleanly separate the filesystem-like commands
# (which take abstract paths?) from BlobTree and Blob which act as an
# abstraction over the filesystem or other storage mechanisms?
function Base.joinpath(tree::BlobTree, r::RelPath)
AbsPath(tree.root, joinpath(tree.path, r))
end
function Base.joinpath(tree::BlobTree, s::AbstractString)
AbsPath(tree.root, joinpath(tree.path, s))
end
function Base.haskey(tree::BlobTree, name::AbstractString)
ispath(tree.root, joinpath(tree.path, name))
end
function Base.readdir(tree::BlobTree)
readdir(tree.root, tree.path)
end
function Base.keys(tree::BlobTree)
readdir(tree.root, tree.path)
end
function Base.rm(tree::BlobTree; kws...)
rm(tree.root, tree.path; kws...)
end
function children(tree::BlobTree)
child_names = readdir(tree)
[tree[c] for c in child_names]
end
function Base.open(f::Function, ::Type{BlobTree}, tree::BlobTree)
f(tree)
end
@! function Base.open(::Type{BlobTree}, tree::BlobTree)
tree
end
# Base.open(::Type{T}, file::Blob; kws...) where {T} = open(identity, T, file.root, file.path; kws...)