-
Notifications
You must be signed in to change notification settings - Fork 482
/
Utilities.jl
630 lines (535 loc) · 18.4 KB
/
Utilities.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
"""
Provides a collection of utility functions and types that are used in other submodules.
"""
module Utilities
using Base.Meta
import Base: isdeprecated, Docs.Binding
using DocStringExtensions
import Markdown, LibGit2
import Base64: stringmime
# Logging output.
const __log__ = Ref(true)
"""
logging(flag::Bool)
Enable or disable logging output for [`log`](@ref) and [`warn`](@ref).
"""
logging(flag::Bool) = __log__[] = flag
"""
Format and print a message to the user.
"""
log(msg) = __log__[] ? printstyled(stdout, "Documenter: ", msg, "\n", color=:magenta) : nothing
# Print logging output to the "real" stdout.
function log(doc, msg)
__log__[] && printstyled(stdout, "Documenter: ", msg, "\n", color=:magenta)
return nothing
end
debug(msg) = printstyled(" ?? ", msg, "\n", color=:green)
"""
warn(file, msg)
warn(msg)
Format and print a warning message to the user. Passing a `file` will include the filename
where the warning was raised.
"""
function warn(file, msg)
if __log__[]
msg = string(" !! ", msg, " [", file, "]\n")
printstyled(stdout, msg, color=:red)
else
nothing
end
end
warn(msg) = __log__[] ? printstyled(stdout, " !! ", msg, "\n", color=:red) : nothing
function warn(file, msg, err, ex, mod)
if __log__[]
warn(file, msg)
printstyled(stdout, "\nERROR: $err\n\nexpression '$(repr(ex))' in module '$mod'\n\n", color=:red)
else
nothing
end
end
function warn(doc, page, msg, err)
file = page.source
printstyled(stdout, " !! Warning in $(file):\n\n$(msg)\n\nERROR: $(err)\n\n", color=:red)
end
# Directory paths.
"""
Returns the current directory.
"""
function currentdir()
d = Base.source_dir()
d === nothing ? pwd() : d
end
"""
Returns the path to the Documenter `assets` directory.
"""
assetsdir() = normpath(joinpath(dirname(@__FILE__), "..", "..", "assets"))
cleandir(d::AbstractString) = (isdir(d) && rm(d, recursive = true); mkdir(d))
"""
Find the path of a file relative to the `source` directory. `root` is the path
to the directory containing the file `file`.
It is meant to be used with `walkdir(source)`.
"""
srcpath(source, root, file) = normpath(joinpath(relpath(root, source), file))
# Slugify text.
"""
Slugify a string into a suitable URL.
"""
function slugify(s::AbstractString)
s = replace(s, r"\s+" => "-")
s = replace(s, r"^\d+" => "")
s = replace(s, r"&" => "-and-")
s = replace(s, r"[^\p{L}\p{P}\d\-]+" => "")
s = strip(replace(s, r"\-\-+" => "-"), '-')
end
slugify(object) = string(object) # Non-string slugifying doesn't do anything.
# Parse code blocks.
"""
Returns a vector of parsed expressions and their corresponding raw strings.
Returns a `Vector` of tuples `(expr, code)`, where `expr` is the corresponding expression
(e.g. a `Expr` or `Symbol` object) and `code` is the string of code the expression was
parsed from.
The keyword argument `skip = N` drops the leading `N` lines from the input string.
"""
function parseblock(code::AbstractString, doc, page; skip = 0, keywords = true)
# Drop `skip` leading lines from the code block. Needed for deprecated `{docs}` syntax.
code = string(code, '\n')
code = last(split(code, '\n', limit = skip + 1))
endofstr = lastindex(code)
results = []
cursor = 1
while cursor < endofstr
# Check for keywords first since they will throw parse errors if we `parse` them.
line = match(r"^(.*)\r?\n"m, SubString(code, cursor)).match
keyword = Symbol(strip(line))
(ex, ncursor) =
# TODO: On 0.7 Symbol("") is in Docs.keywords, remove that check when dropping 0.6
if keywords && (haskey(Docs.keywords, keyword) || keyword == Symbol(""))
(QuoteNode(keyword), cursor + lastindex(line))
else
try
Meta.parse(code, cursor)
catch err
push!(doc.internal.errors, :parse_error)
Utilities.warn(doc, page, "Failed to parse expression.", err)
break
end
end
push!(results, (ex, SubString(code, cursor, prevind(code, ncursor))))
cursor = ncursor
end
results
end
isassign(x) = isexpr(x, :(=), 2) && isa(x.args[1], Symbol)
# Checking arguments.
"""
Prints a formatted warning to the user listing unrecognised keyword arguments.
"""
function check_kwargs(kws)
isempty(kws) && return
out = IOBuffer()
println(out, "Unknown keywords:\n")
for (k, v) in kws
println(out, " ", k, " = ", v)
end
warn(String(take!(out)))
end
# Finding submodules.
const ModVec = Union{Module, Vector{Module}}
"""
Returns the set of submodules of a given root module/s.
"""
function submodules(modules::Vector{Module})
out = Set{Module}()
for each in modules
submodules(each, out)
end
out
end
function submodules(root::Module, seen = Set{Module}())
push!(seen, root)
for name in names(root, all=true)
if Base.isidentifier(name) && isdefined(root, name) && !isdeprecated(root, name)
object = getfield(root, name)
if isa(object, Module) && !(object in seen)
submodules(object, seen)
end
end
end
return seen
end
## objects
## =======
"""
Represents an object stored in the docsystem by its binding and signature.
"""
struct Object
binding :: Binding
signature :: Type
function Object(b::Binding, signature::Type)
m = nameof(b.mod) === b.var ? parentmodule(b.mod) : b.mod
new(Binding(m, b.var), signature)
end
end
function splitexpr(x::Expr)
isexpr(x, :macrocall) ? splitexpr(x.args[1]) :
isexpr(x, :.) ? (x.args[1], x.args[2]) :
error("Invalid @var syntax `$x`.")
end
splitexpr(s::Symbol) = :(Main), quot(s)
splitexpr(other) = error("Invalid @var syntax `$other`.")
"""
object(ex, str)
Returns a expression that, when evaluated, returns an [`Object`](@ref) representing `ex`.
"""
function object(ex::Union{Symbol, Expr}, str::AbstractString)
binding = Expr(:call, Binding, splitexpr(Docs.namify(ex))...)
signature = Base.Docs.signature(ex)
isexpr(ex, :macrocall, 2) && !endswith(str, "()") && (signature = :(Union{}))
Expr(:call, Object, binding, signature)
end
function object(qn::QuoteNode, str::AbstractString)
if haskey(Base.Docs.keywords, qn.value)
binding = Expr(:call, Binding, Main, qn)
Expr(:call, Object, binding, Union{})
else
error("'$(qn.value)' is not a documented keyword.")
end
end
function Base.print(io::IO, obj::Object)
print(io, obj.binding)
print_signature(io, obj.signature)
end
print_signature(io::IO, signature::Union{Union, Type{Union{}}}) = nothing
print_signature(io::IO, signature) = print(io, '-', signature)
## docs
## ====
"""
docs(ex, str)
Returns an expression that, when evaluated, returns the docstrings associated with `ex`.
"""
function docs end
# Macro representation changed between 0.4 and 0.5.
function docs(ex::Union{Symbol, Expr}, str::AbstractString)
isexpr(ex, :macrocall, 2) && !endswith(rstrip(str), "()") && (ex = quot(ex))
:(Base.Docs.@doc $ex)
end
docs(qn::QuoteNode, str::AbstractString) = :(Base.Docs.@doc $(qn.value))
"""
Returns the category name of the provided [`Object`](@ref).
"""
doccat(obj::Object) = startswith(string(obj.binding.var), '@') ?
"Macro" : doccat(obj.binding, obj.signature)
function doccat(b::Binding, ::Union{Union, Type{Union{}}})
if b.mod === Main && haskey(Base.Docs.keywords, b.var)
"Keyword"
elseif startswith(string(b.var), '@')
"Macro"
else
doccat(getfield(b.mod, b.var))
end
end
doccat(b::Binding, ::Type) = "Method"
doccat(::Function) = "Function"
doccat(::DataType) = "Type"
doccat(x::UnionAll) = doccat(Base.unwrap_unionall(x))
doccat(::Module) = "Module"
doccat(::Any) = "Constant"
"""
filterdocs(doc, modules)
Remove docstrings from the markdown object, `doc`, that are not from one of `modules`.
"""
function filterdocs(doc::Markdown.MD, modules::Set{Module})
if isempty(modules)
# When no modules are specified in `makedocs` then don't filter anything.
doc
else
if haskey(doc.meta, :module)
doc.meta[:module] ∈ modules ? doc : nothing
else
if haskey(doc.meta, :results)
out = []
results = []
for (each, result) in zip(doc.content, doc.meta[:results])
r = filterdocs(each, modules)
if r !== nothing
push!(out, r)
push!(results, result)
end
end
if isempty(out)
nothing
else
md = Markdown.MD(out)
md.meta[:results] = results
md
end
else
out = []
for each in doc.content
r = filterdocs(each, modules)
r === nothing || push!(out, r)
end
isempty(out) ? nothing : Markdown.MD(out)
end
end
end
end
# Non-markdown docs won't have a `.meta` field so always just accept those.
filterdocs(other, modules::Set{Module}) = other
"""
Does the given docstring represent actual documentation or a no docs error message?
"""
nodocs(x) = occursin("No documentation found.", stringmime("text/plain", x))
nodocs(::Nothing) = false
header_level(::Markdown.Header{N}) where {N} = N
"""
repo_root(file; dbdir=".git")
Tries to determine the root directory of the repository containing `file`. If the file is
not in a repository, the function returns `nothing`.
The `dbdir` keyword argument specifies the name of the directory we are searching for to
determine if this is a repostory or not. If there is a file called `dbdir`, then it's
contents is checked under the assumption that it is a Git worktree.
"""
function repo_root(file; dbdir=".git")
parent_dir, parent_dir_last = dirname(abspath(file)), ""
while parent_dir != parent_dir_last
dbdir_path = joinpath(parent_dir, dbdir)
isdir(dbdir_path) && return parent_dir
# Let's see if this is a worktree checkout
if isfile(dbdir_path)
contents = chomp(read(dbdir_path, String))
if startswith(contents, "gitdir: ")
if isdir(contents[9:end])
return parent_dir
end
end
end
parent_dir, parent_dir_last = dirname(parent_dir), parent_dir
end
return nothing
end
"""
$(SIGNATURES)
Returns the path of `file`, relative to the root of the Git repository, or `nothing` if the
file is not in a Git repository.
"""
function relpath_from_repo_root(file)
cd(dirname(file)) do
root = repo_root(file)
root !== nothing && startswith(file, root) ? relpath(file, root) : nothing
end
end
function repo_commit(file)
cd(dirname(file)) do
readchomp(`git rev-parse HEAD`)
end
end
function url(repo, file; commit=nothing)
file = realpath(abspath(file))
remote = getremote(dirname(file))
isempty(repo) && (repo = "https://github.com/$remote/blob/{commit}{path}")
path = relpath_from_repo_root(file)
if path === nothing
nothing
else
repo = replace(repo, "{commit}" => commit === nothing ? repo_commit(file) : commit)
# Note: replacing any backslashes in path (e.g. if building the docs on Windows)
repo = replace(repo, "{path}" => string("/", replace(path, '\\' => '/')))
repo = replace(repo, "{line}" => "")
repo
end
end
url(remote, repo, doc) = url(remote, repo, doc.data[:module], doc.data[:path], linerange(doc))
function url(remote, repo, mod, file, linerange)
file === nothing && return nothing # needed on julia v0.6, see #689
remote = getremote(dirname(file))
isabspath(file) && isempty(remote) && isempty(repo) && return nothing
# make sure we get the true path, as otherwise we will get different paths when we compute `root` below
if isfile(file)
file = realpath(abspath(file))
end
# Format the line range.
line = format_line(linerange, LineRangeFormatting(repo_host_from_url(repo)))
# Macro-generated methods such as those produced by `@deprecate` list their file as
# `deprecated.jl` since that is where the macro is defined. Use that to help
# determine the correct URL.
if inbase(mod) || !isabspath(file)
file = replace(file, '\\' => '/')
base = "https://github.com/JuliaLang/julia/blob"
dest = "base/$file#$line"
if isempty(Base.GIT_VERSION_INFO.commit)
"$base/v$VERSION/$dest"
else
commit = Base.GIT_VERSION_INFO.commit
"$base/$commit/$dest"
end
else
path = relpath_from_repo_root(file)
if isempty(repo)
repo = "https://github.com/$remote/blob/{commit}{path}#{line}"
end
if path === nothing
nothing
else
repo = replace(repo, "{commit}" => repo_commit(file))
# Note: replacing any backslashes in path (e.g. if building the docs on Windows)
repo = replace(repo, "{path}" => string("/", replace(path, '\\' => '/')))
repo = replace(repo, "{line}" => line)
repo
end
end
end
function getremote(dir::AbstractString)
remote =
try
cd(() -> readchomp(`git config --get remote.origin.url`), dir)
catch err
""
end
m = match(LibGit2.GITHUB_REGEX, remote)
if m === nothing
travis = get(ENV, "TRAVIS_REPO_SLUG", "")
isempty(travis) ? "" : travis
else
m[1]
end
end
"""
$(SIGNATURES)
Returns the first 5 characters of the current git commit hash of the directory `dir`.
"""
function get_commit_short(dir)
commit = cd(dir) do
readchomp(`git rev-parse HEAD`)
end
(length(commit) > 5) ? commit[1:5] : commit
end
function inbase(m::Module)
if m ≡ Base
true
else
parent = parentmodule(m)
parent ≡ m ? false : inbase(parent)
end
end
# Repository hosts
# RepoUnknown denotes that the repository type could not be determined automatically
@enum RepoHost RepoGithub RepoBitbucket RepoGitlab RepoUnknown
# Repository host from repository url
# i.e. "https://github.com/something" => RepoGithub
# "https://bitbucket.org/xxx" => RepoBitbucket
# If no match, returns RepoUnknown
function repo_host_from_url(repoURL::String)
if occursin("bitbucket", repoURL)
return RepoBitbucket
elseif occursin("github", repoURL)
return RepoGithub
elseif occursin("gitlab", repoURL)
return RepoGitlab
else
return RepoUnknown
end
end
# Find line numbers.
# ------------------
linerange(doc) = linerange(doc.text, doc.data[:linenumber])
function linerange(text, from)
lines = sum([isodd(n) ? newlines(s) : 0 for (n, s) in enumerate(text)])
return lines > 0 ? (from:(from + lines + 1)) : (from:from)
end
struct LineRangeFormatting
prefix::String
separator::String
function LineRangeFormatting(host::RepoHost)
if host == RepoBitbucket
new("", ":")
elseif host == RepoGitlab
new("L", "-")
else
# default is github-style
new("L", "-L")
end
end
end
function format_line(range::AbstractRange, format::LineRangeFormatting)
if length(range) <= 1
string(format.prefix, first(range))
else
string(format.prefix, first(range), format.separator, last(range))
end
end
newlines(s::AbstractString) = count(c -> c === '\n', s)
newlines(other) = 0
# Output redirection.
# -------------------
using Logging
"""
Call a function and capture all `stdout` and `stderr` output.
withoutput(f) --> (result, success, backtrace, output)
where
* `result` is the value returned from calling function `f`.
* `success` signals whether `f` has thrown an error, in which case `result` stores the
`Exception` that was raised.
* `backtrace` a `Vector{Ptr{Cvoid}}` produced by `catch_backtrace()` if an error is thrown.
* `output` is the combined output of `stdout` and `stderr` during execution of `f`.
"""
function withoutput(f)
# Save the default output streams.
default_stdout = stdout
default_stderr = stderr
# Redirect both the `stdout` and `stderr` streams to a single `Pipe` object.
pipe = Pipe()
Base.link_pipe!(pipe; reader_supports_async = true, writer_supports_async = true)
redirect_stdout(pipe.in)
redirect_stderr(pipe.in)
# Also redirect logging stream to the same pipe
logger = ConsoleLogger(pipe.in)
# Bytes written to the `pipe` are captured in `output` and converted to a `String`.
output = UInt8[]
# Run the function `f`, capturing all output that it might have generated.
# Success signals whether the function `f` did or did not throw an exception.
result, success, backtrace = with_logger(logger) do
try
f(), true, Vector{Ptr{Cvoid}}()
catch err
# InterruptException should never happen during normal doc-testing
# and not being able to abort the doc-build is annoying (#687).
isa(err, InterruptException) && rethrow(err)
err, false, catch_backtrace()
finally
# Force at least a single write to `pipe`, otherwise `readavailable` blocks.
println()
# Restore the original output streams.
redirect_stdout(default_stdout)
redirect_stderr(default_stderr)
# NOTE: `close` must always be called *after* `readavailable`.
append!(output, readavailable(pipe))
close(pipe)
end
end
return result, success, backtrace, chomp(String(output))
end
"""
issubmodule(sub, mod)
Checks whether `sub` is a submodule of `mod`. A module is also considered to be
its own submodule.
E.g. `A.B.C` is a submodule of `A`, `A.B` and `A.B.C`, but it is not a submodule
of `D`, `A.D` nor `A.B.C.D`.
"""
function issubmodule(sub, mod)
if (sub === Main) && (mod !== Main)
return false
end
(sub === mod) || issubmodule(parentmodule(sub), mod)
end
"""
isabsurl(url)
Checks whether `url` is an absolute URL (as opposed to a relative one).
"""
isabsurl(url) = occursin(ABSURL_REGEX, url)
const ABSURL_REGEX = r"^[[:alpha:]+-.]+://"
include("DOM.jl")
include("MDFlatten.jl")
include("TextDiff.jl")
include("Selectors.jl")
end