2021-12-12 12:28:52 +00:00
|
|
|
/-
|
|
|
|
Copyright (c) 2021 Henrik Böving. All rights reserved.
|
|
|
|
Released under Apache 2.0 license as described in the file LICENSE.
|
|
|
|
Authors: Henrik Böving
|
|
|
|
-/
|
2021-12-12 12:20:03 +00:00
|
|
|
import Lean
|
|
|
|
|
|
|
|
namespace DocGen4
|
|
|
|
|
2022-02-26 01:41:25 +00:00
|
|
|
open Lean System IO Lean.Elab.Term FS
|
|
|
|
|
|
|
|
deriving instance DecidableEq for FileType
|
|
|
|
|
|
|
|
/--
|
|
|
|
Traverse all subdirectories fo `f` to find if one satisfies `p`.
|
|
|
|
-/
|
|
|
|
partial def traverseDir (f : FilePath) (p : FilePath → IO Bool) : IO (Option FilePath) := do
|
|
|
|
if (← p f) then
|
|
|
|
return f
|
|
|
|
for d in (← System.FilePath.readDir f) do
|
|
|
|
let subDir := d.path
|
|
|
|
let metadata ← subDir.metadata
|
|
|
|
if metadata.type = FileType.dir then
|
|
|
|
if let some p ← traverseDir subDir p then
|
|
|
|
return p
|
|
|
|
return none
|
2021-12-12 12:20:03 +00:00
|
|
|
|
|
|
|
syntax (name := includeStr) "include_str" str : term
|
|
|
|
|
|
|
|
@[termElab includeStr] def includeStrImpl : TermElab := λ stx expectedType? => do
|
2022-02-26 01:41:25 +00:00
|
|
|
let str := stx[1].isStrLit?.get!
|
|
|
|
let srcPath := (FilePath.mk (← read).fileName)
|
|
|
|
let currentDir ← IO.currentDir
|
|
|
|
-- HACK: Currently we cannot get current file path in VSCode, we have to traversely find the matched subdirectory in the current directory.
|
|
|
|
if let some path ← match srcPath.parent with
|
|
|
|
| some p => pure $ some $ p / str
|
|
|
|
| none => do
|
|
|
|
let foundDir ← traverseDir currentDir λ p => p / str |>.pathExists
|
|
|
|
pure $ foundDir.map (· / str)
|
|
|
|
then
|
2021-12-12 12:20:03 +00:00
|
|
|
if ←path.pathExists then
|
|
|
|
if ←path.isDir then
|
|
|
|
throwError s!"{str} is a directory"
|
|
|
|
else
|
|
|
|
let content ← FS.readFile path
|
2022-02-12 14:09:13 +00:00
|
|
|
pure $ mkStrLit content
|
2021-12-12 12:20:03 +00:00
|
|
|
else
|
2022-02-26 01:41:25 +00:00
|
|
|
throwError s!"{path} does not exist as a file"
|
|
|
|
else
|
|
|
|
throwError s!"No such file in whole directory: {str}"
|
2021-12-12 12:20:03 +00:00
|
|
|
|
|
|
|
end DocGen4
|